From 2b52e1d84fa610f2ffd3acb668d0dad6c7b88fea Mon Sep 17 00:00:00 2001 From: antiduh Date: Tue, 24 Jun 2014 22:57:02 +0000 Subject: [PATCH] Helper method for invoking native methods with a CER. --- Contexts/Context.cs | 39 ++++++----------------------- Contexts/ContextNativeMethods.cs | 43 ++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 32 deletions(-) diff --git a/Contexts/Context.cs b/Contexts/Context.cs index 4dbfa1e..0df256c 100644 --- a/Contexts/Context.cs +++ b/Contexts/Context.cs @@ -178,7 +178,7 @@ namespace NSspi SecureBuffer paddingBuffer; SecureBufferAdapter adapter; - SecurityStatus status = SecurityStatus.InvalidHandle; + SecurityStatus status; byte[] result = null; int remaining; int position; @@ -242,37 +242,12 @@ namespace NSspi using( adapter = new SecureBufferAdapter( new [] { trailerBuffer, dataBuffer, paddingBuffer } ) ) { - bool gotRef = false; - - RuntimeHelpers.PrepareConstrainedRegions(); - try - { - this.ContextHandle.DangerousAddRef( ref gotRef ); - } - catch( Exception ) - { - if( gotRef ) - { - this.ContextHandle.DangerousRelease(); - gotRef = false; - } - - throw; - } - finally - { - if( gotRef ) - { - status = ContextNativeMethods.DecryptMessage( - ref this.ContextHandle.rawHandle, - adapter.Handle, - 0, - 0 - ); - - this.ContextHandle.DangerousRelease(); - } - } + status = ContextNativeMethods.SafeDecryptMessage( + this.ContextHandle, + 0, + adapter.Handle, + 0 + ); } if( status != SecurityStatus.OK ) diff --git a/Contexts/ContextNativeMethods.cs b/Contexts/ContextNativeMethods.cs index c6375a7..5ff0b1e 100644 --- a/Contexts/ContextNativeMethods.cs +++ b/Contexts/ContextNativeMethods.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Text; @@ -141,5 +142,47 @@ namespace NSspi [DllImport( "Secur32.dll", EntryPoint = "FreeContextBuffer", CharSet = CharSet.Unicode )] public static extern SecurityStatus FreeContextBuffer( IntPtr handle ); + + public static SecurityStatus SafeDecryptMessage( + SafeContextHandle handle, + int qualityOfProtection, + IntPtr bufferDescriptor, + int sequenceNumber ) + { + SecurityStatus status = SecurityStatus.InvalidHandle; + bool gotRef = false; + + RuntimeHelpers.PrepareConstrainedRegions(); + try + { + handle.DangerousAddRef( ref gotRef ); + } + catch( Exception ) + { + if( gotRef ) + { + handle.DangerousRelease(); + gotRef = false; + } + + throw; + } + finally + { + if( gotRef ) + { + status = ContextNativeMethods.DecryptMessage( + ref handle.rawHandle, + bufferDescriptor, + 0, + 0 + ); + + handle.DangerousRelease(); + } + } + + return status; + } } }