Reorganized the project to put the library one folder down.

This commit is contained in:
antiduh
2014-06-27 14:38:28 +00:00
parent ffb7e36edb
commit c1b7785440
40 changed files with 9 additions and 9 deletions

52
NSspi/ByteWriter.cs Normal file
View File

@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace NSspi
{
public static class ByteWriter
{
// Big endian: Most significant byte at lowest address in memory.
public static void WriteInt16_BE( Int16 value, byte[] buffer, int position )
{
buffer[position + 0] = (byte)( value >> 8 );
buffer[position + 1] = (byte)( value );
}
public static void WriteInt32_BE( Int32 value, byte[] buffer, int position )
{
buffer[position + 0] = (byte)( value >> 24 );
buffer[position + 1] = (byte)( value >> 16 );
buffer[position + 2] = (byte)( value >> 8 );
buffer[position + 3] = (byte)( value);
}
public static Int16 ReadInt16_BE( byte[] buffer, int position )
{
Int16 value;
value = (Int16)( buffer[position + 0] << 8 );
value += (Int16)( buffer[position + 1] );
return value;
}
public static Int32 ReadInt32_BE( byte[] buffer, int position )
{
Int32 value;
value = (Int32)( buffer[position + 0] << 24 );
value |= (Int32)( buffer[position + 1] << 16 );
value |= (Int32)( buffer[position + 2] << 8 );
value |= (Int32)( buffer[position + 3] );
return value;
}
}
}

View File

@@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using NSspi.Buffers;
using NSspi.Credentials;
namespace NSspi.Contexts
{
public class ClientContext : Context
{
private ContextAttrib requestedAttribs;
private ContextAttrib finalAttribs;
private string serverPrinc;
public ClientContext( ClientCredential cred, string serverPrinc, ContextAttrib requestedAttribs )
: base( cred )
{
this.serverPrinc = serverPrinc;
this.requestedAttribs = requestedAttribs;
}
public SecurityStatus Init( byte[] serverToken, out byte[] outToken )
{
long expiry = 0;
SecurityStatus status;
SecureBuffer outTokenBuffer;
SecureBufferAdapter outAdapter;
SecureBuffer serverBuffer;
SecureBufferAdapter serverAdapter;
if ( (serverToken != null) && ( this.ContextHandle.IsInvalid ) )
{
throw new InvalidOperationException( "Out-of-order usage detected - have a server token, but no previous client token had been created." );
}
else if ( (serverToken == null) && ( this.ContextHandle.IsInvalid == false ) )
{
throw new InvalidOperationException( "Must provide the server's response when continuing the init process." );
}
outTokenBuffer = new SecureBuffer( new byte[12288], BufferType.Token );
serverBuffer = null;
if ( serverToken != null )
{
serverBuffer = new SecureBuffer( serverToken, BufferType.Token );
}
// Some notes on handles and invoking InitializeSecurityContext
// - The first time around, the phContext parameter (the 'old' handle) is a null pointer to what
// would be an RawSspiHandle, to indicate this is the first time it's being called.
// The phNewContext is a pointer (reference) to an RawSspiHandle struct of where to write the
// new handle's values.
// - The next time you invoke ISC, it takes a pointer to the handle it gave you last time in phContext,
// and takes a pointer to where it should write the new handle's values in phNewContext.
// - After the first time, you can provide the same handle to both parameters. From MSDN:
// "On the second call, phNewContext can be the same as the handle specified in the phContext
// parameter."
// It will overwrite the handle you gave it with the new handle value.
// - All handle structures themselves are actually *two* pointer variables, eg, 64 bits on 32-bit
// Windows, 128 bits on 64-bit Windows.
// - So in the end, on a 64-bit machine, we're passing a 64-bit value (the pointer to the struct) that
// points to 128 bits of memory (the struct itself) for where to write the handle numbers.
using ( outAdapter = new SecureBufferAdapter( outTokenBuffer ) )
{
if ( this.ContextHandle.IsInvalid )
{
status = ContextNativeMethods.InitializeSecurityContext_1(
ref this.Credential.Handle.rawHandle,
IntPtr.Zero,
this.serverPrinc,
this.requestedAttribs,
0,
SecureBufferDataRep.Network,
IntPtr.Zero,
0,
ref this.ContextHandle.rawHandle,
outAdapter.Handle,
ref this.finalAttribs,
ref expiry
);
}
else
{
using ( serverAdapter = new SecureBufferAdapter( serverBuffer ) )
{
status = ContextNativeMethods.InitializeSecurityContext_2(
ref this.Credential.Handle.rawHandle,
ref this.ContextHandle.rawHandle,
this.serverPrinc,
this.requestedAttribs,
0,
SecureBufferDataRep.Network,
serverAdapter.Handle,
0,
ref this.ContextHandle.rawHandle,
outAdapter.Handle,
ref this.finalAttribs,
ref expiry
);
}
}
}
if ( status == SecurityStatus.OK )
{
this.Initialized = true;
outToken = null;
}
else if ( status == SecurityStatus.ContinueNeeded )
{
this.Initialized = false;
outToken = new byte[outTokenBuffer.Length];
Array.Copy( outTokenBuffer.Buffer, outToken, outToken.Length );
}
else
{
throw new SSPIException( "Failed to invoke InitializeSecurityContext for a client", status );
}
return status;
}
}
}

494
NSspi/Contexts/Context.cs Normal file
View File

@@ -0,0 +1,494 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using NSspi.Buffers;
using NSspi.Contexts;
using NSspi.Credentials;
namespace NSspi.Contexts
{
public class Context : IDisposable
{
public Context( Credential cred )
{
this.Credential = cred;
this.ContextHandle = new SafeContextHandle();
this.Disposed = false;
this.Initialized = false;
}
~Context()
{
Dispose( false );
}
/// <summary>
/// Whether or not the context is fully formed.
/// </summary>
public bool Initialized { get; protected set; }
protected Credential Credential { get; private set; }
public SafeContextHandle ContextHandle { get; protected set; }
public string AuthorityName
{
get
{
return QueryContextString( ContextQueryAttrib.Authority );
}
}
public string ContextUserName
{
get
{
return QueryContextString( ContextQueryAttrib.Names );
}
}
public bool Disposed { get; private set; }
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize( this );
}
protected virtual void Dispose( bool disposing )
{
if( this.Disposed ) { return; }
if( disposing )
{
this.ContextHandle.Dispose();
}
this.Disposed = true;
}
/// <summary>
/// Encrypts the byte array using the context's session key. The encrypted data is stored in a new
/// byte array, which is formatted such that the first four bytes are the original message length
/// as an unsigned integer and the remaining bytes are the encrypted bytes of the original message.
/// </summary>
/// <remarks>
/// The resulting byte array stores the SSPI buffer data in the following buffer format:
/// - Token
/// - Data
/// - Padding
/// </remarks>
/// <param name="input"></param>
/// <returns></returns>
public byte[] Encrypt( byte[] input )
{
// The message is encrypted in place in the buffer we provide to Win32 EncryptMessage
SecPkgContext_Sizes sizes;
SecureBuffer trailerBuffer;
SecureBuffer dataBuffer;
SecureBuffer paddingBuffer;
SecureBufferAdapter adapter;
SecurityStatus status = SecurityStatus.InvalidHandle;
byte[] result;
if ( this.Initialized == false )
{
throw new InvalidOperationException( "The context is not fully formed." );
}
sizes = QueryBufferSizes();
trailerBuffer = new SecureBuffer( new byte[sizes.SecurityTrailer], BufferType.Token );
dataBuffer = new SecureBuffer( new byte[input.Length], BufferType.Data );
paddingBuffer = new SecureBuffer( new byte[sizes.BlockSize], BufferType.Padding );
Array.Copy( input, dataBuffer.Buffer, input.Length );
using( adapter = new SecureBufferAdapter( new[] { trailerBuffer, dataBuffer, paddingBuffer } ) )
{
status = ContextNativeMethods.SafeEncryptMessage(
this.ContextHandle,
0,
adapter,
0
);
}
if( status != SecurityStatus.OK )
{
throw new SSPIException( "Failed to encrypt message", status );
}
int position = 0;
// Enough room to fit:
// -- 2 bytes for the trailer buffer size
// -- 4 bytes for the message size
// -- 2 bytes for the padding size.
// -- The encrypted message
result = new byte[2 + 4 + 2 + trailerBuffer.Length + dataBuffer.Length + paddingBuffer.Length];
ByteWriter.WriteInt16_BE( (short)trailerBuffer.Length, result, position );
position += 2;
ByteWriter.WriteInt32_BE( dataBuffer.Length, result, position );
position += 4;
ByteWriter.WriteInt16_BE( (short)paddingBuffer.Length, result, position );
position += 2;
Array.Copy( trailerBuffer.Buffer, 0, result, position, trailerBuffer.Length );
position += trailerBuffer.Length;
Array.Copy( dataBuffer.Buffer, 0, result, position, dataBuffer.Length );
position += dataBuffer.Length;
Array.Copy( paddingBuffer.Buffer, 0, result, position, paddingBuffer.Length );
position += paddingBuffer.Length;
return result;
}
public byte[] Decrypt( byte[] input )
{
SecPkgContext_Sizes sizes;
SecureBuffer trailerBuffer;
SecureBuffer dataBuffer;
SecureBuffer paddingBuffer;
SecureBufferAdapter adapter;
SecurityStatus status;
byte[] result = null;
int remaining;
int position;
int trailerLength;
int dataLength;
int paddingLength;
if ( this.Initialized == false )
{
throw new InvalidOperationException( "The context is not fully formed." );
}
sizes = QueryBufferSizes();
// This check is required, but not sufficient. We could be stricter.
if( input.Length < 2 + 4 + 2 + sizes.SecurityTrailer )
{
throw new ArgumentException( "Buffer is too small to possibly contain an encrypted message" );
}
position = 0;
trailerLength = ByteWriter.ReadInt16_BE( input, position );
position += 2;
dataLength = ByteWriter.ReadInt32_BE( input, position );
position += 4;
paddingLength = ByteWriter.ReadInt16_BE( input, position );
position += 2;
trailerBuffer = new SecureBuffer( new byte[trailerLength], BufferType.Token );
dataBuffer = new SecureBuffer( new byte[dataLength], BufferType.Data );
paddingBuffer = new SecureBuffer( new byte[paddingLength], BufferType.Padding );
remaining = input.Length - position;
if( trailerBuffer.Length <= remaining )
{
Array.Copy( input, position, trailerBuffer.Buffer, 0, trailerBuffer.Length );
position += trailerBuffer.Length;
remaining -= trailerBuffer.Length;
}
else
{
throw new ArgumentException( "Input is missing data - it is not long enough to contain a fully encrypted message" );
}
if( dataBuffer.Length <= remaining )
{
Array.Copy( input, position, dataBuffer.Buffer, 0, dataBuffer.Length );
position += dataBuffer.Length;
remaining -= dataBuffer.Length;
}
else
{
throw new ArgumentException( "Input is missing data - it is not long enough to contain a fully encrypted message" );
}
if( paddingBuffer.Length <= remaining )
{
Array.Copy( input, position, paddingBuffer.Buffer, 0, paddingBuffer.Length );
}
// else there was no padding.
using( adapter = new SecureBufferAdapter( new [] { trailerBuffer, dataBuffer, paddingBuffer } ) )
{
status = ContextNativeMethods.SafeDecryptMessage(
this.ContextHandle,
0,
adapter,
0
);
}
if( status != SecurityStatus.OK )
{
throw new SSPIException( "Failed to encrypt message", status );
}
result = new byte[dataBuffer.Length];
Array.Copy( dataBuffer.Buffer, 0, result, 0, dataBuffer.Length );
return result;
}
public byte[] MakeSignature( byte[] message )
{
SecurityStatus status = SecurityStatus.InternalError;
SecPkgContext_Sizes sizes;
SecureBuffer dataBuffer;
SecureBuffer signatureBuffer;
SecureBufferAdapter adapter;
if ( this.Initialized == false )
{
throw new InvalidOperationException( "The context is not fully formed" );
}
sizes = QueryBufferSizes();
dataBuffer = new SecureBuffer( new byte[message.Length], BufferType.Data );
signatureBuffer = new SecureBuffer( new byte[sizes.MaxSignature], BufferType.Token );
Array.Copy( message, dataBuffer.Buffer, message.Length );
using ( adapter = new SecureBufferAdapter( new[] { dataBuffer, signatureBuffer } ) )
{
status = ContextNativeMethods.SafeMakeSignature(
this.ContextHandle,
0,
adapter,
0
);
}
if ( status != SecurityStatus.OK )
{
throw new SSPIException( "Failed to create message signature.", status );
}
byte[] outMessage;
int position = 0;
// Enough room for
// - original message length (4 bytes)
// - signature length (2 bytes)
// - original message
// - signature
outMessage = new byte[4 + 2 + dataBuffer.Length + signatureBuffer.Length];
ByteWriter.WriteInt32_BE( dataBuffer.Length, outMessage, position );
position += 4;
ByteWriter.WriteInt16_BE( (Int16)signatureBuffer.Length, outMessage, position );
position += 2;
Array.Copy( dataBuffer.Buffer, 0, outMessage, position, dataBuffer.Length );
position += dataBuffer.Length;
Array.Copy( signatureBuffer.Buffer, 0, outMessage, position, signatureBuffer.Length );
position += signatureBuffer.Length;
return outMessage;
}
public bool VerifySignature( byte[] signedMessage, out byte[] origMessage )
{
SecurityStatus status = SecurityStatus.InternalError;
SecPkgContext_Sizes sizes;
SecureBuffer dataBuffer;
SecureBuffer signatureBuffer;
SecureBufferAdapter adapter;
if ( this.Initialized == false )
{
throw new InvalidOperationException( "The context is not fully formed." );
}
sizes = QueryBufferSizes();
if ( signedMessage.Length < 2 + 4 + sizes.MaxSignature )
{
throw new ArgumentException( "Input message is too small to possibly fit a valid message" );
}
int position = 0;
int messageLen;
int sigLen;
messageLen = ByteWriter.ReadInt32_BE( signedMessage, 0 );
position += 4;
sigLen = ByteWriter.ReadInt16_BE( signedMessage, position );
position += 2;
dataBuffer = new SecureBuffer( new byte[messageLen], BufferType.Data );
Array.Copy( signedMessage, position, dataBuffer.Buffer, 0, messageLen );
position += messageLen;
signatureBuffer = new SecureBuffer( new byte[sigLen], BufferType.Token );
Array.Copy( signedMessage, position, signatureBuffer.Buffer, 0, sigLen );
position += sigLen;
using ( adapter = new SecureBufferAdapter( new[] { dataBuffer, signatureBuffer } ) )
{
status = ContextNativeMethods.SafeVerifySignature(
this.ContextHandle,
0,
adapter,
0
);
}
if ( status == SecurityStatus.OK )
{
origMessage = dataBuffer.Buffer;
return true;
}
else if ( status == SecurityStatus.MessageAltered ||
status == SecurityStatus.OutOfSequence )
{
origMessage = null;
return false;
}
else
{
throw new SSPIException( "Failed to determine the veracity of a signed message.", status );
}
}
private SecPkgContext_Sizes QueryBufferSizes()
{
SecPkgContext_Sizes sizes = new SecPkgContext_Sizes();
SecurityStatus status = SecurityStatus.InternalError;
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.QueryContextAttributes_Sizes(
ref this.ContextHandle.rawHandle,
ContextQueryAttrib.Sizes,
ref sizes
);
this.ContextHandle.DangerousRelease();
}
}
if( status != SecurityStatus.OK )
{
throw new SSPIException( "Failed to query context buffer size attributes", status );
}
return sizes;
}
private string QueryContextString(ContextQueryAttrib attrib)
{
SecPkgContext_String stringAttrib;
SecurityStatus status = SecurityStatus.InternalError;
string result = null;
bool gotRef = false;
if( attrib != ContextQueryAttrib.Names && attrib != ContextQueryAttrib.Authority )
{
throw new InvalidOperationException( "QueryContextString can only be used to query context Name and Authority attributes" );
}
stringAttrib = new SecPkgContext_String();
RuntimeHelpers.PrepareConstrainedRegions();
try
{
this.ContextHandle.DangerousAddRef( ref gotRef );
}
catch ( Exception )
{
if ( gotRef )
{
this.ContextHandle.DangerousRelease();
gotRef = false;
}
throw;
}
finally
{
if ( gotRef )
{
status = ContextNativeMethods.QueryContextAttributes_String(
ref this.ContextHandle.rawHandle,
attrib,
ref stringAttrib
);
this.ContextHandle.DangerousRelease();
if ( status == SecurityStatus.OK )
{
result = Marshal.PtrToStringUni( stringAttrib.StringResult );
ContextNativeMethods.FreeContextBuffer( stringAttrib.StringResult );
}
}
}
if( status == SecurityStatus.Unsupported )
{
return null;
}
else if( status != SecurityStatus.OK )
{
throw new SSPIException( "Failed to query the context's associated user name", status );
}
return result;
}
private void InitSecPkgInfo()
{
}
}
}

View File

@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Contexts
{
/// <summary>
/// Defines options for creating a security context via win32 InitializeSecurityContext
/// (used by clients) and AcceptSecurityContext (used by servers).
/// Required attribute flags are specified when creating the context. InitializeSecurityContext
/// and AcceptSecurityContext returns a value indicating what final attributes the created context
/// actually has.
/// </summary>
[Flags]
public enum ContextAttrib : int
{
/// <summary>
/// No additional attributes are provided.
/// </summary>
Zero = 0,
/// <summary>
/// The server can use the context to authenticate to other servers as the client. The
/// MutualAuth flag must be set for this flag to work. Valid for Kerberos. Ignore this flag for
/// constrained delegation, (TODO)(which is handled through a separate mechanism?).
/// </summary>
Delegate = 0x00000001,
/// <summary>
/// The mutual authentication policy of the service will be satisfied.
/// *Caution* - This does not necessarily mean that mutual authentication is performed, only that
/// the authentication policy of the service is satisfied. To ensure that mutual authentication is
/// performed, query the context attributes after it is created.
/// </summary>
MutualAuth = 0x00000002,
/// <summary>
/// Detect replayed messages that have been encoded by using the EncryptMessage or MakeSignature
/// message support functionality.
/// </summary>
ReplayDetect = 0x00000004,
/// <summary>
/// Detect messages received out of sequence when using the message support functionality.
/// This flag implies all of the conditions specified by the Integrity flag - out-of-order sequence
/// detection can only be trusted if the integrity of any underlying sequence detection mechanism
/// in transmitted data can be trusted.
/// </summary>
SequenceDetect = 0x00000008,
// The context must protect data while in transit.
// Confidentiality is supported for NTLM with Microsoft
// Windows NT version 4.0, SP4 and later and with the
// Kerberos protocol in Microsoft Windows 2000 and later.
/// <summary>
/// The context must protect data while in transit. Encrypt messages by using the EncryptMessage function.
/// </summary>
Confidentiality = 0x00000010,
/// <summary>
/// A new session key must be negotiated.
/// This value is supported only by the Kerberos security package.
/// </summary>
UseSessionKey = 0x00000020,
/// <summary>
/// The security package allocates output buffers for you. Buffers allocated by the security package have
/// to be released by the context memory management functions.
/// </summary>
AllocateMemory = 0x00000100,
/// <summary>
/// The security context will not handle formatting messages. This value is the default for the Kerberos,
/// Negotiate, and NTLM security packages.
/// </summary>
Connection = 0x00000800,
/// <summary>
/// When errors occur, the remote party will be notified.
/// </summary>
/// <remarks>
/// A client specifies InitExtendedError in InitializeSecurityContext
/// and the server specifies AcceptExtendedError in AcceptSecurityContext.
/// </remarks>
InitExtendedError = 0x00004000,
/// <summary>
/// When errors occur, the remote party will be notified.
/// </summary>
/// <remarks>
/// A client specifies InitExtendedError in InitializeSecurityContext
/// and the server specifies AcceptExtendedError in AcceptSecurityContext.
/// </remarks>
AcceptExtendedError = 0x00008000,
/// <summary>
/// Support a stream-oriented connection. Provided by clients.
/// </summary>
InitStream = 0x00008000,
/// <summary>
/// Support a stream-oriented connection. Provided by servers.
/// </summary>
AcceptStream = 0x00010000,
/// <summary>
/// Sign messages and verify signatures by using the EncryptMessage and MakeSignature functions.
/// Replayed and out-of-sequence messages will not be detected with the setting of this attribute.
/// Set ReplayDetect and SequenceDetect also if these behaviors are desired.
/// </summary>
InitIntegrity = 0x00010000,
/// <summary>
/// Sign messages and verify signatures by using the EncryptMessage and MakeSignature functions.
/// Replayed and out-of-sequence messages will not be detected with the setting of this attribute.
/// Set ReplayDetect and SequenceDetect also if these behaviors are desired.
/// </summary>
AcceptIntegrity = 0x00020000,
InitIdentify = 0x00020000,
AcceptIdentify = 0x00080000,
/// <summary>
/// An Schannel provider connection is instructed to not authenticate the server automatically.
/// </summary>
InitManualCredValidation = 0x00080000,
/// <summary>
/// An Schannel provider connection is instructed to not authenticate the client automatically.
/// </summary>
InitUseSuppliedCreds = 0x00000080,
}
}

View File

@@ -0,0 +1,345 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using NSspi.Buffers;
using NSspi.Contexts;
namespace NSspi.Contexts
{
internal static class ContextNativeMethods
{
/*
SECURITY_STATUS SEC_Entry AcceptSecurityContext(
_In_opt_ PCredHandle phCredential,
_Inout_ PCtxtHandle phContext,
_In_opt_ PSecBufferDesc pInput,
_In_ ULONG fContextReq,
_In_ ULONG TargetDataRep,
_Inout_opt_ PCtxtHandle phNewContext,
_Inout_opt_ PSecBufferDesc pOutput,
_Out_ PULONG pfContextAttr,
_Out_opt_ PTimeStamp ptsTimeStamp
);
SECURITY_STATUS SEC_Entry InitializeSecurityContext(
_In_opt_ PCredHandle phCredential, // [in] handle to the credentials
_In_opt_ PCtxtHandle phContext, // [in/out] handle of partially formed context. Always NULL the first time through
_In_opt_ SEC_CHAR *pszTargetName, // [in] name of the target of the context. Not needed by NTLM
_In_ ULONG fContextReq, // [in] required context attributes
_In_ ULONG Reserved1, // [reserved] reserved; must be zero
_In_ ULONG TargetDataRep, // [in] data representation on the target
_In_opt_ PSecBufferDesc pInput, // [in/out] pointer to the input buffers. Always NULL the first time through
_In_ ULONG Reserved2, // [reserved] reserved; must be zero
_Inout_opt_ PCtxtHandle phNewContext, // [in/out] receives the new context handle (must be pre-allocated)
_Inout_opt_ PSecBufferDesc pOutput, // [out] pointer to the output buffers
_Out_ PULONG pfContextAttr, // [out] receives the context attributes
_Out_opt_ PTimeStamp ptsExpiry // [out] receives the life span of the security context
);
*/
[DllImport( "Secur32.dll", EntryPoint = "AcceptSecurityContext",CharSet = CharSet.Unicode )]
internal static extern SecurityStatus AcceptSecurityContext_1(
ref RawSspiHandle credHandle,
IntPtr oldContextHandle,
IntPtr inputBuffer,
ContextAttrib requestedAttribs,
SecureBufferDataRep dataRep,
ref RawSspiHandle newContextHandle,
IntPtr outputBuffer,
ref ContextAttrib outputAttribs,
ref long expiry
);
[DllImport( "Secur32.dll", EntryPoint = "AcceptSecurityContext", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus AcceptSecurityContext_2(
ref RawSspiHandle credHandle,
ref RawSspiHandle oldContextHandle,
IntPtr inputBuffer,
ContextAttrib requestedAttribs,
SecureBufferDataRep dataRep,
ref RawSspiHandle newContextHandle,
IntPtr outputBuffer,
ref ContextAttrib outputAttribs,
ref long expiry
);
[DllImport( "Secur32.dll", EntryPoint = "InitializeSecurityContext", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus InitializeSecurityContext_1(
ref RawSspiHandle credentialHandle,
IntPtr zero,
string serverPrincipleName,
ContextAttrib requiredAttribs,
int reserved1,
SecureBufferDataRep dataRep,
IntPtr inputBuffer,
int reserved2,
ref RawSspiHandle newContextHandle,
IntPtr outputBuffer,
ref ContextAttrib contextAttribs,
ref long expiry
);
[DllImport( "Secur32.dll", EntryPoint = "InitializeSecurityContext", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus InitializeSecurityContext_2(
ref RawSspiHandle credentialHandle,
ref RawSspiHandle previousHandle,
string serverPrincipleName,
ContextAttrib requiredAttribs,
int reserved1,
SecureBufferDataRep dataRep,
IntPtr inputBuffer,
int reserved2,
ref RawSspiHandle newContextHandle,
IntPtr outputBuffer,
ref ContextAttrib contextAttribs,
ref long expiry
);
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success )]
[DllImport( "Secur32.dll", EntryPoint = "DeleteSecurityContext", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus DeleteSecurityContext( ref RawSspiHandle contextHandle );
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail )]
[DllImport( "Secur32.dll", EntryPoint = "EncryptMessage", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus EncryptMessage(
ref RawSspiHandle contextHandle,
int qualityOfProtection,
IntPtr bufferDescriptor,
int sequenceNumber
);
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
[DllImport( "Secur32.dll", EntryPoint = "DecryptMessage", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus DecryptMessage(
ref RawSspiHandle contextHandle,
IntPtr bufferDescriptor,
int sequenceNumber,
int qualityOfProtection
);
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
[DllImport( "Secur32.dll", EntryPoint = "MakeSignature", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus MakeSignature(
ref RawSspiHandle contextHandle,
int qualityOfProtection,
IntPtr bufferDescriptor,
int sequenceNumber
);
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
[DllImport( "Secur32.dll", EntryPoint = "VerifySignature", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus VerifySignature(
ref RawSspiHandle contextHandle,
IntPtr bufferDescriptor,
int sequenceNumber,
int qualityOfProtection
);
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
[DllImport( "Secur32.dll", EntryPoint = "QueryContextAttributes", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus QueryContextAttributes_Sizes(
ref RawSspiHandle contextHandle,
ContextQueryAttrib attrib,
ref SecPkgContext_Sizes sizes
);
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success)]
[DllImport( "Secur32.dll", EntryPoint = "QueryContextAttributes", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus QueryContextAttributes_String(
ref RawSspiHandle contextHandle,
ContextQueryAttrib attrib,
ref SecPkgContext_String names
);
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
[DllImport( "Secur32.dll", EntryPoint = "FreeContextBuffer", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus FreeContextBuffer( IntPtr handle );
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
[DllImport( "Secur32.dll", EntryPoint = "ImpersonateSecurityContext", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus ImpersonateSecurityContext( ref RawSspiHandle contextHandle );
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
[DllImport( "Secur32.dll", EntryPoint = "RevertSecurityContext", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus RevertSecurityContext( ref RawSspiHandle contextHandle );
internal static SecurityStatus SafeEncryptMessage(
SafeContextHandle handle,
int qualityOfProtection,
SecureBufferAdapter bufferAdapter,
int sequenceNumber )
{
SecurityStatus status = SecurityStatus.InternalError;
bool gotRef = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
handle.DangerousAddRef( ref gotRef );
}
catch ( Exception )
{
if ( gotRef )
{
handle.DangerousRelease();
gotRef = false;
}
throw;
}
finally
{
if ( gotRef )
{
status = ContextNativeMethods.EncryptMessage(
ref handle.rawHandle,
0,
bufferAdapter.Handle,
0
);
handle.DangerousRelease();
}
}
return status;
}
internal static SecurityStatus SafeDecryptMessage(
SafeContextHandle handle,
int qualityOfProtection,
SecureBufferAdapter bufferAdapter,
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,
bufferAdapter.Handle,
0,
0
);
handle.DangerousRelease();
}
}
return status;
}
internal static SecurityStatus SafeMakeSignature(
SafeContextHandle handle,
int qualityOfProtection,
SecureBufferAdapter adapter,
int sequenceNumber )
{
bool gotRef = false;
SecurityStatus status = SecurityStatus.InternalError;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
handle.DangerousAddRef( ref gotRef );
}
catch ( Exception )
{
if ( gotRef )
{
handle.DangerousRelease();
gotRef = false;
}
throw;
}
finally
{
if ( gotRef )
{
status = ContextNativeMethods.MakeSignature(
ref handle.rawHandle,
0,
adapter.Handle,
0
);
handle.DangerousRelease();
}
}
return status;
}
internal static SecurityStatus SafeVerifySignature(
SafeContextHandle handle,
int qualityOfProtection,
SecureBufferAdapter adapter,
int sequenceNumber )
{
bool gotRef = false;
SecurityStatus status = SecurityStatus.InternalError;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
handle.DangerousAddRef( ref gotRef );
}
catch ( Exception )
{
if ( gotRef )
{
handle.DangerousRelease();
gotRef = false;
}
throw;
}
finally
{
if ( gotRef )
{
status = ContextNativeMethods.VerifySignature(
ref handle.rawHandle,
adapter.Handle,
0,
0
);
handle.DangerousRelease();
}
}
return status;
}
}
}

View File

@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Contexts
{
[StructLayout( LayoutKind.Sequential )]
internal struct SecPkgContext_Sizes
{
public int MaxToken;
public int MaxSignature;
public int BlockSize;
public int SecurityTrailer;
}
[StructLayout( LayoutKind.Sequential )]
internal struct SecPkgContext_String
{
public IntPtr StringResult;
}
}

View File

@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Contexts
{
/// <summary>
/// Defines the types of queries that can be performed with QueryContextAttribute.
/// Each query has a different result buffer.
/// </summary>
public enum ContextQueryAttrib : int
{
/// <summary>
/// Queries the buffer size parameters when performing message functions, such
/// as encryption, decryption, signing and signature validation.
/// </summary>
/// <remarks>
/// Results for a query of this type are stored in a Win32 SecPkgContext_Sizes structure.
/// </remarks>
Sizes = 0,
/// <summary>
/// Queries the context for the name of the user assocated with a security context.
/// </summary>
/// <remarks>
/// Results for a query of this type are stored in a Win32 SecPkgContext_Name structure.
/// </remarks>
Names = 1,
/// <summary>
/// Queries the name of the authenticating authority for the security context.
/// </summary>
/// <remarks>
/// Results for a query of this type are stored in a Win32 SecPkgContext_Authority structure.
/// </remarks>
Authority = 6,
}
}

View File

@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Contexts
{
public class ImpersonationHandle : IDisposable
{
// Notes:
// Impersonate:
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa375497(v=vs.85).aspx
//
// Revert:
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa379446(v=vs.85).aspx
//
// QuerySecurityPkgInfo (to learn if it supports impersonation):
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa379359(v=vs.85).aspx
private bool disposed;
private ServerContext server;
internal ImpersonationHandle(ServerContext server)
{
this.server = server;
this.disposed = false;
}
~ImpersonationHandle()
{
Dispose( false );
}
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize( this );
}
protected virtual void Dispose( bool disposing )
{
if( disposing && this.disposed == false && this.server != null && this.server.Disposed == false )
{
this.server.RevertImpersonate();
}
}
}
}

View File

@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Contexts
{
public class SafeContextHandle : SafeSspiHandle
{
public SafeContextHandle()
: base()
{ }
protected override bool ReleaseHandle()
{
SecurityStatus status = ContextNativeMethods.DeleteSecurityContext(
ref base.rawHandle
);
base.ReleaseHandle();
return status == SecurityStatus.OK;
}
}
}

View File

@@ -0,0 +1,207 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using NSspi.Buffers;
using NSspi.Credentials;
namespace NSspi.Contexts
{
public class ServerContext : Context
{
private ContextAttrib requestedAttribs;
private ContextAttrib finalAttribs;
private bool impersonating;
public ServerContext(ServerCredential cred, ContextAttrib requestedAttribs) : base ( cred )
{
this.requestedAttribs = requestedAttribs;
this.finalAttribs = ContextAttrib.Zero;
this.impersonating = false;
}
public SecurityStatus AcceptToken( byte[] clientToken, out byte[] nextToken )
{
SecureBuffer clientBuffer = new SecureBuffer( clientToken, BufferType.Token );
SecureBuffer outBuffer = new SecureBuffer( new byte[12288], BufferType.Token );
SecurityStatus status;
long expiry = 0;
SecureBufferAdapter clientAdapter;
SecureBufferAdapter outAdapter;
using ( clientAdapter = new SecureBufferAdapter( clientBuffer ) )
{
using ( outAdapter = new SecureBufferAdapter( outBuffer ) )
{
if( this.ContextHandle.IsInvalid )
{
status = ContextNativeMethods.AcceptSecurityContext_1(
ref this.Credential.Handle.rawHandle,
IntPtr.Zero,
clientAdapter.Handle,
requestedAttribs,
SecureBufferDataRep.Network,
ref this.ContextHandle.rawHandle,
outAdapter.Handle,
ref this.finalAttribs,
ref expiry
);
}
else
{
status = ContextNativeMethods.AcceptSecurityContext_2(
ref this.Credential.Handle.rawHandle,
ref this.ContextHandle.rawHandle,
clientAdapter.Handle,
requestedAttribs,
SecureBufferDataRep.Network,
ref this.ContextHandle.rawHandle,
outAdapter.Handle,
ref this.finalAttribs,
ref expiry
);
}
}
}
if ( status == SecurityStatus.OK )
{
nextToken = null;
this.Initialized = true;
if ( outBuffer.Length != 0 )
{
nextToken = new byte[outBuffer.Length];
Array.Copy( outBuffer.Buffer, nextToken, nextToken.Length );
}
else
{
nextToken = null;
}
InitProviderCapabilities();
}
else if ( status == SecurityStatus.ContinueNeeded )
{
this.Initialized = false;
nextToken = new byte[outBuffer.Length];
Array.Copy( outBuffer.Buffer, nextToken, nextToken.Length );
}
else
{
throw new SSPIException( "Failed to call AcceptSecurityContext", status );
}
return status;
}
public ImpersonationHandle ImpersonateClient()
{
ImpersonationHandle handle = new ImpersonationHandle( this );
SecurityStatus status = SecurityStatus.InternalError;
bool gotRef = false;
if( impersonating )
{
throw new InvalidOperationException( "Cannot impersonate again while already impersonating." );
}
RuntimeHelpers.PrepareConstrainedRegions();
try
{
this.ContextHandle.DangerousAddRef( ref gotRef );
}
catch( Exception )
{
if( gotRef )
{
this.ContextHandle.DangerousRelease();
gotRef = false;
}
throw;
}
finally
{
if( gotRef )
{
status = ContextNativeMethods.ImpersonateSecurityContext(
ref this.ContextHandle.rawHandle
);
this.ContextHandle.DangerousRelease();
this.impersonating = true;
}
}
if( status == SecurityStatus.NoImpersonation )
{
throw new SSPIException( "Impersonation could not be performed.", status );
}
else if( status == SecurityStatus.Unsupported )
{
throw new SSPIException( "Impersonation is not supported by the security context's Security Support Provider.", status );
}
else if( status != SecurityStatus.OK )
{
throw new SSPIException( "Failed to impersonate the client", status );
}
return handle;
}
internal void RevertImpersonate()
{
bool gotRef = false;
SecurityStatus status = SecurityStatus.InternalError;
if( impersonating == false || this.Disposed )
{
return;
}
RuntimeHelpers.PrepareConstrainedRegions();
try
{
this.ContextHandle.DangerousAddRef( ref gotRef );
}
catch( Exception )
{
if( gotRef )
{
this.ContextHandle.DangerousRelease();
gotRef = false;
}
throw;
}
finally
{
if( gotRef )
{
status = ContextNativeMethods.RevertSecurityContext(
ref this.ContextHandle.rawHandle
);
this.ContextHandle.DangerousRelease();
this.impersonating = false;
}
}
}
private void InitProviderCapabilities()
{
}
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Credentials
{
public class ClientCredential : Credential
{
public ClientCredential( SecurityPackage package ) : base( package, CredentialType.Client ) { }
}
}

View File

@@ -0,0 +1,202 @@
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using NSspi.Credentials;
using NSspi.Credentials.Credentials;
namespace NSspi.Credentials
{
public class Credential : IDisposable
{
private bool disposed;
private SecurityPackage securityPackage;
private SafeCredentialHandle safeCredHandle;
private long expiry;
public Credential(SecurityPackage package, CredentialType credentialType)
{
this.disposed = false;
this.securityPackage = package;
this.expiry = 0;
Init( package, credentialType );
}
private void Init( SecurityPackage package, CredentialType credentialType )
{
string packageName;
CredentialUse use;
// -- Package --
if ( package == SecurityPackage.Kerberos )
{
packageName = PackageNames.Kerberos;
}
else if ( package == SecurityPackage.Negotiate )
{
packageName = PackageNames.Negotiate;
}
else if ( package == SecurityPackage.NTLM )
{
packageName = PackageNames.Ntlm;
}
else
{
throw new ArgumentException( "Invalid value provided for the 'package' parameter." );
}
// -- Credential --
if ( credentialType == CredentialType.Client )
{
use = CredentialUse.Outbound;
}
else if ( credentialType == CredentialType.Server )
{
use = CredentialUse.Inbound;
}
else
{
throw new ArgumentException( "Invalid value provided for the 'credentialType' parameter." );
}
// -- Invoke --
SecurityStatus status = SecurityStatus.InternalError;
this.safeCredHandle = new SafeCredentialHandle();
// The finally clause is the actual constrained region. The VM pre-allocates any stack space,
// performs any allocations it needs to prepare methods for execution, and postpones any
// instances of the 'uncatchable' exceptions (ThreadAbort, StackOverflow, OutOfMemory).
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
status = CredentialNativeMethods.AcquireCredentialsHandle(
null,
packageName,
use,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
ref this.safeCredHandle.rawHandle,
ref this.expiry
);
}
if ( status != SecurityStatus.OK )
{
throw new SSPIException( "Failed to call AcquireCredentialHandle", status );
}
}
~Credential()
{
Dispose( false );
}
public SecurityPackage SecurityPackage
{
get
{
if( this.disposed )
{
throw new ObjectDisposedException( base.GetType().Name );
}
return this.securityPackage;
}
}
public string Name
{
get
{
QueryNameAttribCarrier carrier = new QueryNameAttribCarrier();
SecurityStatus status = SecurityStatus.InternalError;
string name = null;
bool gotRef = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
this.safeCredHandle.DangerousAddRef( ref gotRef );
}
catch( Exception )
{
if( gotRef == true )
{
this.safeCredHandle.DangerousRelease();
gotRef = false;
}
throw;
}
finally
{
if( gotRef )
{
status = CredentialNativeMethods.QueryCredentialsAttribute_Name(
ref this.safeCredHandle.rawHandle,
CredentialQueryAttrib.Names,
ref carrier
);
this.safeCredHandle.DangerousRelease();
if( status == SecurityStatus.OK && carrier.Name != IntPtr.Zero )
{
name = Marshal.PtrToStringUni( carrier.Name );
NativeMethods.FreeContextBuffer( carrier.Name );
}
}
}
if( status.IsError() )
{
throw new SSPIException( "Failed to query credential name", status );
}
return name;
}
}
public SafeCredentialHandle Handle
{
get
{
return this.safeCredHandle;
}
}
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize( this );
}
protected virtual void Dispose( bool disposing )
{
if ( this.disposed == false )
{
if ( disposing )
{
this.safeCredHandle.Dispose();
}
this.disposed = true;
}
}
}
}

View File

@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using NSspi.Credentials;
using NSspi.Credentials.Credentials;
namespace NSspi.Credentials
{
internal static class CredentialNativeMethods
{
/*
SECURITY_STATUS SEC_Entry AcquireCredentialsHandle(
_In_ SEC_CHAR *pszPrincipal, // [in] name of principal. NULL = principal of current security context
_In_ SEC_CHAR *pszPackage, // [in] name of security package - "Kerberos", "Negotiate", "NTLM", etc
_In_ ULONG fCredentialUse, // [in] flags indicating use.
_In_ PLUID pvLogonID, // [in] pointer to logon identifier. NULL = we're not specifying the id of another logon session
_In_ PVOID pAuthData, // [in] package-specific data. NULL = default credentials for security package
_In_ SEC_GET_KEY_FN pGetKeyFn, // [in] pointer to GetKey function. NULL = we're not using a callback to retrieve the credentials
_In_ PVOID pvGetKeyArgument, // [in] value to pass to GetKey
_Out_ PCredHandle phCredential, // [out] credential handle (this must be already allocated)
_Out_ PTimeStamp ptsExpiry // [out] lifetime of the returned credentials
);
SECURITY_STATUS SEC_Entry FreeCredentialsHandle(
_In_ PCredHandle phCredential
);
SECURITY_STATUS SEC_Entry QueryCredentialsAttributes(
_In_ PCredHandle phCredential,
_In_ ULONG ulAttribute,
_Out_ PVOID pBuffer
);
*/
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail)]
[DllImport( "Secur32.dll", EntryPoint = "AcquireCredentialsHandle", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus AcquireCredentialsHandle(
string principleName,
string packageName,
CredentialUse credentialUse,
IntPtr loginId,
IntPtr packageData,
IntPtr getKeyFunc,
IntPtr getKeyData,
ref RawSspiHandle credentialHandle,
ref long expiry
);
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
[DllImport( "Secur32.dll", EntryPoint = "FreeCredentialsHandle", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus FreeCredentialsHandle(
ref RawSspiHandle credentialHandle
);
/// <summary>
/// The overload of the QueryCredentialsAttribute method that is used for querying the name attribute.
/// In this call, it takes a void* to a structure that contains a wide char pointer. The wide character
/// pointer is allocated by the SSPI api, and thus needs to be released by a call to FreeContextBuffer().
/// </summary>
/// <param name="credentialHandle"></param>
/// <param name="attributeName"></param>
/// <param name="name"></param>
/// <returns></returns>
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
[DllImport( "Secur32.dll", EntryPoint = "QueryCredentialsAttributes", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus QueryCredentialsAttribute_Name(
ref RawSspiHandle credentialHandle,
CredentialQueryAttrib attributeName,
ref QueryNameAttribCarrier name
);
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Credentials
{
public enum SecurityPackage
{
Negotiate = 0,
Kerberos = 1,
NTLM = 2
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Credentials
{
/*
#define SECPKG_CRED_ATTR_NAMES 1
#define SECPKG_CRED_ATTR_SSI_PROVIDER 2
#define SECPKG_CRED_ATTR_KDC_PROXY_SETTINGS 3
#define SECPKG_CRED_ATTR_CERT 4
*/
public enum CredentialQueryAttrib : uint
{
Names = 1,
SsiProvider = 2,
KdcProxySettings = 3,
Cert = 4
}
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Credentials
{
public enum CredentialType
{
Client = 0,
Server = 1
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Credentials
{
public enum CredentialUse : uint
{
Inbound = 1,
Outbound = 2,
Both = 3,
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Credentials.Credentials
{
[StructLayout( LayoutKind.Sequential )]
public struct QueryNameAttribCarrier
{
public IntPtr Name;
}
}

View File

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Credentials
{
public class SafeCredentialHandle : SafeSspiHandle
{
public SafeCredentialHandle()
: base()
{ }
protected override bool ReleaseHandle()
{
SecurityStatus status = CredentialNativeMethods.FreeCredentialsHandle(
ref base.rawHandle
);
base.ReleaseHandle();
return status == SecurityStatus.OK;
}
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Credentials
{
public class ServerCredential : Credential
{
public ServerCredential( SecurityPackage package ) : base( package, CredentialType.Server ) { }
}
}

93
NSspi/NSspi.csproj Normal file
View File

@@ -0,0 +1,93 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{4B4CD933-BF62-4F92-B8FA-6771758C5197}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>NSspi</RootNamespace>
<AssemblyName>NSspi</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject>NSspi.Program</StartupObject>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.DirectoryServices" />
<Reference Include="System.DirectoryServices.AccountManagement" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ByteWriter.cs" />
<Compile Include="Contexts\ClientContext.cs" />
<Compile Include="Contexts\Context.cs" />
<Compile Include="Contexts\ContextAttrib.cs" />
<Compile Include="Contexts\ContextNativeMethods.cs" />
<Compile Include="Contexts\ContextQueries.cs" />
<Compile Include="Contexts\ContextQueryAttrib.cs" />
<Compile Include="Contexts\ImpersonationHandle.cs" />
<Compile Include="Contexts\SafeContextHandle.cs" />
<Compile Include="SecPkgInfo.cs" />
<Compile Include="Contexts\ServerContext.cs" />
<Compile Include="Credentials\ClientCredential.cs" />
<Compile Include="Credentials\Credential.cs" />
<Compile Include="Credentials\CredentialNativeMethods.cs" />
<Compile Include="Credentials\CredentialPackage.cs" />
<Compile Include="Credentials\CredentialQueryAttrib.cs" />
<Compile Include="Credentials\CredentialType.cs" />
<Compile Include="Credentials\CredentialUse.cs" />
<Compile Include="Credentials\QueryNameSupport.cs" />
<Compile Include="Credentials\SafeCredentialHandle.cs" />
<Compile Include="Credentials\ServerCredential.cs" />
<Compile Include="NativeMethods.cs" />
<Compile Include="PackageSupport.cs" />
<Compile Include="PackageNames.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SecureBuffer\SecureBuffer.cs" />
<Compile Include="SecureBuffer\SecureBufferAdapter.cs" />
<Compile Include="SecureBuffer\SecureBufferDataRep.cs" />
<Compile Include="SecureBuffer\SecureBufferDesc.cs" />
<Compile Include="SecureBuffer\SecureBufferType.cs" />
<Compile Include="SecurityStatus.cs" />
<Compile Include="SSPIException.cs" />
<Compile Include="SspiHandle.cs" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

37
NSspi/NativeMethods.cs Normal file
View File

@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using NSspi.Contexts;
namespace NSspi
{
internal class NativeMethods
{
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa374713(v=vs.85).aspx
// The REMSSPI sample:
// A C++ pure client/server example:
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa380536(v=vs.85).aspx
/*
SECURITY_STATUS SEC_Entry FreeContextBuffer(
_In_ PVOID pvContextBuffer
);
*/
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success)]
[DllImport( "Secur32.dll", EntryPoint = "FreeContextBuffer", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus FreeContextBuffer( IntPtr buffer );
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
[DllImport( "Secur32.dll", EntryPoint = "QuerySecurityPackageInfo", CharSet = CharSet.Unicode )]
internal static extern SecurityStatus QuerySecurityPackageInfo( string packageName, ref IntPtr pkgInfo );
}
}

17
NSspi/PackageNames.cs Normal file
View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi
{
public static class PackageNames
{
public const string Negotiate = "Negotiate";
public const string Kerberos = "Kerberos";
public const string Ntlm = "NTLM";
}
}

52
NSspi/PackageSupport.cs Normal file
View File

@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace NSspi
{
internal static class PackageSupport
{
internal static SecPkgInfo GetPackageCapabilities( string packageName )
{
SecPkgInfo info;
SecurityStatus status;
SecurityStatus freeStatus;
IntPtr rawInfoPtr;
rawInfoPtr = new IntPtr();
info = new SecPkgInfo();
RuntimeHelpers.PrepareConstrainedRegions();
try
{ }
finally
{
status = NativeMethods.QuerySecurityPackageInfo( packageName, ref rawInfoPtr );
if ( rawInfoPtr != IntPtr.Zero )
{
try
{
if ( status == SecurityStatus.OK )
{
// This performs allocations as it makes room for the strings contained in the SecPkgInfo class.
Marshal.PtrToStructure( rawInfoPtr, info );
}
}
finally
{
freeStatus = NativeMethods.FreeContextBuffer( rawInfoPtr );
}
}
}
return info;
}
}
}

192
NSspi/Program.cs Normal file
View File

@@ -0,0 +1,192 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using NSspi.Contexts;
using NSspi.Credentials;
namespace NSspi
{
public class Program
{
public static void Main( string[] args )
{
CredTest();
}
private static void IdentTest()
{
WindowsIdentity current = WindowsIdentity.GetCurrent( TokenAccessLevels.MaximumAllowed );
Stream stream = new MemoryStream();
StringWriter writer = new StringWriter();
ISerializable serializable = current;
SerializationInfo info = new SerializationInfo( current.GetType(), new FormatterConverter() );
StreamingContext streamingContext = new StreamingContext();
serializable.GetObjectData( info, streamingContext );
WindowsIdentity newId = new WindowsIdentity( info, streamingContext );
}
private static void CredTest()
{
ClientCredential clientCred = null;
ClientContext client = null;
ServerCredential serverCred = null;
ServerContext server = null;
byte[] clientToken;
byte[] serverToken;
SecurityStatus clientStatus;
SecurityStatus serverStatus;
try
{
clientCred = new ClientCredential( SecurityPackage.Negotiate );
Console.Out.WriteLine( clientCred.Name );
client = new ClientContext(
clientCred,
"",
ContextAttrib.MutualAuth |
ContextAttrib.InitIdentify |
ContextAttrib.Confidentiality |
ContextAttrib.ReplayDetect |
ContextAttrib.SequenceDetect |
ContextAttrib.Connection |
ContextAttrib.Delegate
);
serverCred = new ServerCredential( SecurityPackage.Negotiate );
server = new ServerContext(
serverCred,
ContextAttrib.MutualAuth |
ContextAttrib.AcceptIdentify |
ContextAttrib.Confidentiality |
ContextAttrib.ReplayDetect |
ContextAttrib.SequenceDetect |
ContextAttrib.Connection |
ContextAttrib.Delegate
);
clientToken = null;
serverToken = null;
clientStatus = client.Init( serverToken, out clientToken );
while ( true )
{
serverStatus = server.AcceptToken( clientToken, out serverToken );
if ( serverStatus != SecurityStatus.ContinueNeeded && clientStatus != SecurityStatus.ContinueNeeded ) { break; }
clientStatus = client.Init( serverToken, out clientToken );
if ( serverStatus != SecurityStatus.ContinueNeeded && clientStatus != SecurityStatus.ContinueNeeded ) { break; }
}
Console.Out.WriteLine( "Server authority: " + server.AuthorityName );
Console.Out.WriteLine( "Server context user: " + server.ContextUserName );
Console.Out.WriteLine();
Console.Out.WriteLine( "Client authority: " + client.AuthorityName );
Console.Out.WriteLine( "Client context user: " + client.ContextUserName );
string message = "Hello, world. This is a long message that will be encrypted";
string rtMessage;
byte[] plainText = new byte[Encoding.UTF8.GetByteCount( message )];
byte[] cipherText;
byte[] roundTripPlaintext;
Encoding.UTF8.GetBytes( message, 0, message.Length, plainText, 0 );
cipherText = client.Encrypt( plainText );
roundTripPlaintext = server.Decrypt( cipherText );
if( roundTripPlaintext.Length != plainText.Length )
{
throw new Exception();
}
for( int i= 0; i < plainText.Length; i++ )
{
if( plainText[i] != roundTripPlaintext[i] )
{
throw new Exception();
}
}
rtMessage = Encoding.UTF8.GetString( roundTripPlaintext, 0, roundTripPlaintext.Length );
if( rtMessage.Equals( message ) == false )
{
throw new Exception();
}
using( server.ImpersonateClient() )
{
}
cipherText = client.MakeSignature( plainText );
bool goodSig = server.VerifySignature( cipherText, out roundTripPlaintext );
if ( goodSig == false ||
roundTripPlaintext.Length != plainText.Length )
{
throw new Exception();
}
for ( int i = 0; i < plainText.Length; i++ )
{
if ( plainText[i] != roundTripPlaintext[i] )
{
throw new Exception();
}
}
Console.Out.Flush();
}
finally
{
if ( server != null )
{
server.Dispose();
}
if ( client != null )
{
client.Dispose();
}
if( clientCred != null )
{
clientCred.Dispose();
}
if ( serverCred != null )
{
serverCred.Dispose();
}
}
}
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NSspi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Kevin Thompson")]
[assembly: AssemblyProduct("NSspi")]
[assembly: AssemblyCopyright("Copyright © Kevin Thompson 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9abf710c-c646-42aa-8183-76bfa141a07b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

53
NSspi/SSPIException.cs Normal file
View File

@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace NSspi
{
[Serializable]
public class SSPIException : Exception
{
private SecurityStatus errorCode;
private string message;
public SSPIException( SerializationInfo info, StreamingContext context )
: base( info, context )
{
this.message = info.GetString( "messsage" );
this.errorCode = (SecurityStatus)info.GetUInt32( "errorCode" );
}
public SSPIException( string message, SecurityStatus errorCode )
{
this.message = message;
this.errorCode = errorCode;
}
public override void GetObjectData( SerializationInfo info, StreamingContext context )
{
base.GetObjectData( info, context );
info.AddValue( "message", this.message );
info.AddValue( "errorCode", this.errorCode );
}
public SecurityStatus ErrorCode
{
get
{
return this.errorCode;
}
}
public override string Message
{
get
{
return string.Format( "{0}. Error Code = '{1:X}'.", this.message, this.errorCode );
}
}
}
}

75
NSspi/SecPkgInfo.cs Normal file
View File

@@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace NSspi
{
[StructLayout( LayoutKind.Sequential )]
public class SecPkgInfo
{
public SecPkgCapability Capabilities;
public short Version;
public short RpcId;
public int MaxTokenLength;
[MarshalAs( UnmanagedType.LPWStr )]
public string Name;
[MarshalAs( UnmanagedType.LPWStr )]
public string Comment;
}
[Flags]
public enum SecPkgCapability : uint
{
Integrity = 0x1,
Privacy = 0x2,
TokenOnly = 0x4,
Datagram = 0x8,
Connection = 0x10,
MultiLeg = 0x20,
ClientOnly = 0x40,
ExtendedError = 0x80,
Impersonation = 0x100,
AcceptWin32Name = 0x200,
Stream = 0x400,
Negotiable = 0x800,
GssCompatible = 0x1000,
Logon = 0x2000,
AsciiBuffers = 0x4000,
Fragment = 0x8000,
MutualAuth = 0x10000,
Delegation = 0x20000,
ReadOnlyChecksum = 0x40000,
RestrictedTokens = 0x80000,
ExtendsNego = 0x00100000,
Negotiable2 = 0x00200000,
}
}

View File

@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Buffers
{
[StructLayout( LayoutKind.Sequential )]
internal struct SecureBufferInternal
{
public int Count;
public BufferType Type;
// A pointer to a byte[]
public IntPtr Buffer;
}
internal class SecureBuffer
{
public SecureBuffer( byte[] buffer, BufferType type )
{
this.Buffer = buffer;
this.Type = type;
this.Length = this.Buffer.Length;
}
public BufferType Type { get; set; }
public byte[] Buffer { get; set; }
public int Length { get; internal set; }
}
}

View File

@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Buffers
{
internal class SecureBufferAdapter : IDisposable
{
private bool disposed;
private IList<SecureBuffer> buffers;
private GCHandle descriptorHandle;
private GCHandle[] bufferHandles;
private SecureBufferDescInternal descriptor;
private SecureBufferInternal[] bufferCarrier;
private GCHandle bufferCarrierHandle;
public SecureBufferAdapter( SecureBuffer buffer )
: this( new[] { buffer } )
{
}
//[ReliabilityContract( Consistency.MayCorruptAppDomain, Cer.None)]
public SecureBufferAdapter( IList<SecureBuffer> buffers )
{
this.buffers = buffers;
this.disposed = false;
this.bufferHandles = new GCHandle[this.buffers.Count];
this.bufferCarrier = new SecureBufferInternal[this.buffers.Count];
for ( int i = 0; i < this.buffers.Count; i++ )
{
this.bufferHandles[i] = GCHandle.Alloc( this.buffers[i].Buffer, GCHandleType.Pinned );
this.bufferCarrier[i] = new SecureBufferInternal();
this.bufferCarrier[i].Type = this.buffers[i].Type;
this.bufferCarrier[i].Count = this.buffers[i].Buffer.Length;
this.bufferCarrier[i].Buffer = bufferHandles[i].AddrOfPinnedObject();
}
this.bufferCarrierHandle = GCHandle.Alloc( bufferCarrier, GCHandleType.Pinned );
this.descriptor = new SecureBufferDescInternal();
this.descriptor.Version = SecureBufferDescInternal.ApiVersion;
this.descriptor.NumBuffers = this.buffers.Count;
this.descriptor.Buffers = bufferCarrierHandle.AddrOfPinnedObject();
this.descriptorHandle = GCHandle.Alloc( descriptor, GCHandleType.Pinned );
}
~SecureBufferAdapter()
{
Dispose( false );
}
public IntPtr Handle
{
get
{
if ( this.disposed )
{
throw new ObjectDisposedException( "Cannot use SecureBufferListHandle after it has been disposed" );
}
return this.descriptorHandle.AddrOfPinnedObject();
}
}
public void Dispose()
{
this.Dispose( true );
GC.SuppressFinalize( this );
}
protected virtual void Dispose( bool disposing )
{
if ( this.disposed == true ) { return; }
if ( disposing )
{
for ( int i = 0; i < this.buffers.Count; i++ )
{
this.buffers[i].Length = this.bufferCarrier[i].Count;
}
}
for ( int i = 0; i < this.bufferHandles.Length; i++ )
{
this.bufferHandles[i].Free();
}
this.bufferCarrierHandle.Free();
this.descriptorHandle.Free();
this.disposed = true;
}
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Buffers
{
internal enum SecureBufferDataRep : int
{
/*
#define SECURITY_NATIVE_DREP 0x00000010
#define SECURITY_NETWORK_DREP 0x00000000
*/
Nativee = 0x10,
Network = 0x00
}
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Buffers
{
[StructLayout( LayoutKind.Sequential)]
internal struct SecureBufferDescInternal
{
public int Version;
public int NumBuffers;
// A pointer to a SecureBuffer[]
public IntPtr Buffers;
public const int ApiVersion = 0;
}
}

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Buffers
{
internal enum BufferType : int
{
Empty = 0x00,
Data = 0x01,
Token = 0x02,
Parameters = 0x03,
Missing = 0x04,
Extra = 0x05,
Trailer = 0x06,
Header = 0x07,
Padding = 0x09,
Stream = 0x0A,
ChannelBindings = 0x0E,
TargetHost = 0x10,
ReadOnlyFlag = unchecked( (int)0x80000000 ),
ReadOnlyWithChecksum = 0x10000000
}
}

77
NSspi/SecurityStatus.cs Normal file
View File

@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi
{
/*
// From winerror.h
#define SEC_E_OK ((HRESULT)0x00000000L)
#define SEC_E_INSUFFICIENT_MEMORY _HRESULT_TYPEDEF_(0x80090300L)
#define SEC_E_INVALID_HANDLE _HRESULT_TYPEDEF_(0x80090301L)
#define SEC_E_UNSUPPORTED_FUNCTION _HRESULT_TYPEDEF_(0x80090302L)
#define SEC_E_TARGET_UNKNOWN _HRESULT_TYPEDEF_(0x80090303L)
#define SEC_E_INTERNAL_ERROR _HRESULT_TYPEDEF_(0x80090304L)
#define SEC_E_SECPKG_NOT_FOUND _HRESULT_TYPEDEF_(0x80090305L)
#define SEC_E_NOT_OWNER _HRESULT_TYPEDEF_(0x80090306L)
#define SEC_E_UNKNOWN_CREDENTIALS _HRESULT_TYPEDEF_(0x8009030DL)
#define SEC_E_NO_CREDENTIALS _HRESULT_TYPEDEF_(0x8009030EL)
*/
public enum SecurityStatus : uint
{
// Success / Informational
OK = 0x00000000,
ContinueNeeded = 0x00090312,
CompleteNeeded = 0x00090313,
CompAndContinue = 0x00090314,
ContextExpired = 0x00090317,
CredentialsNeeded = 0x00090320,
Renegotiate = 0x00090321,
// Errors
OutOfMemory = 0x80090300,
InvalidHandle = 0x80090301,
Unsupported = 0x80090302,
TargetUnknown = 0x80090303,
InternalError = 0x80090304,
PackageNotFound = 0x80090305,
NotOwner = 0x80090306,
CannotInstall = 0x80090307,
InvalidToken = 0x80090308,
CannotPack = 0x80090309,
QopNotSupported = 0x8009030A,
NoImpersonation = 0x8009030B,
LogonDenied = 0x8009030C,
UnknownCredentials = 0x8009030D,
NoCredentials = 0x8009030E,
MessageAltered = 0x8009030F,
OutOfSequence = 0x80090310,
NoAuthenticatingAuthority = 0x80090311,
IncompleteMessage = 0x80090318,
IncompleteCredentials = 0x80090320,
BufferNotEnough = 0x80090321,
WrongPrincipal = 0x80090322,
TimeSkew = 0x80090324,
UntrustedRoot = 0x80090325,
IllegalMessage = 0x80090326,
CertUnknown = 0x80090327,
CertExpired = 0x80090328,
AlgorithmMismatch = 0x80090331,
SecurityQosFailed = 0x80090332,
SmartcardLogonRequired = 0x8009033E,
UnsupportedPreauth = 0x80090343,
BadBinding = 0x80090346
}
public static class SecurityStatusExtensions
{
public static bool IsError( this SecurityStatus status )
{
return (uint)status > 0x80000000u;
}
}
}

69
NSspi/SspiHandle.cs Normal file
View File

@@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using NSspi.Contexts;
namespace NSspi
{
/// <summary>
/// Represents any SSPI handle created for credential handles, context handles, and security package
/// handles. Any SSPI handle is always the size of two native pointers.
/// </summary>
/// <remarks>
/// The documentation for SSPI handles can be found here:
/// http://msdn.microsoft.com/en-us/library/windows/desktop/aa380495(v=vs.85).aspx
///
/// This class is not reference safe - if used directly, or referenced directly, it may be leaked,
/// or subject to finalizer races, or any of the hundred of things SafeHandles were designed to fix.
/// Do not directly use this class - use only though SafeHandle wrapper objects. Any reference needed
/// to this handle for performing work (InitializeSecurityContext, eg), should be done through
/// a second class SafeSspiHandleReference so that reference counting is properly executed.
/// </remarks>
[StructLayout( LayoutKind.Sequential, Pack = 1 ) ]
internal struct RawSspiHandle
{
private IntPtr lowPart;
private IntPtr highPart;
public bool IsZero()
{
return this.lowPart == IntPtr.Zero && this.highPart == IntPtr.Zero;
}
// This guy has to be executed in a CER.
[ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success)]
public void SetInvalid()
{
this.lowPart = IntPtr.Zero;
this.highPart = IntPtr.Zero;
}
}
public abstract class SafeSspiHandle : SafeHandle
{
internal RawSspiHandle rawHandle;
protected SafeSspiHandle()
: base( IntPtr.Zero, true )
{
this.rawHandle = new RawSspiHandle();
}
public override bool IsInvalid
{
get { return IsClosed || this.rawHandle.IsZero(); }
}
protected override bool ReleaseHandle()
{
this.rawHandle.SetInvalid();
return true;
}
}
}

3
NSspi/app.config Normal file
View File

@@ -0,0 +1,3 @@
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup></configuration>