public int CompleteAuthToken(ref SafeDeleteContext refContext, SecurityBuffer[] inputBuffers)
 {
     if (ComNetOS.IsWin9x)
     {
         throw new NotSupportedException();
     }
     return SafeDeleteContext.CompleteAuthToken(Library, ref refContext, inputBuffers);
 }
 public int DecryptMessage(SafeDeleteContext context, SecurityBufferDescriptor inputOutput, uint sequenceNumber)
 {
     if (ComNetOS.IsWin9x)
     {
         throw ExceptionHelper.MethodNotImplementedException;
     }
     return this.DecryptMessageHelper(context, inputOutput, sequenceNumber);
 }
 internal static int AcceptSecurityContext(SSPIInterface SecModule, ref SafeFreeCredentials credential, ref SafeDeleteContext context, ContextFlags inFlags, Endianness datarep, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref ContextFlags outFlags)
 {
     if (Logging.On)
     {
         Logging.PrintInfo(Logging.Web, string.Concat(new object[] { "AcceptSecurityContext(credential = ", credential.ToString(), ", context = ", ValidationHelper.ToString(context), ", inFlags = ", inFlags, ")" }));
     }
     int num = SecModule.AcceptSecurityContext(ref credential, ref context, inputBuffer, inFlags, datarep, outputBuffer, ref outFlags);
     if (Logging.On)
     {
         Logging.PrintInfo(Logging.Web, SR.GetString("net_log_sspi_security_context_input_buffer", new object[] { "AcceptSecurityContext", (inputBuffer == null) ? 0 : inputBuffer.size, outputBuffer.size, (SecurityStatus) num }));
     }
     return num;
 }
        public static unsafe int QueryContextChannelBinding(SecurDll dll, SafeDeleteContext phContext, ContextAttribute contextAttribute, Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle)
        {
            switch (dll)
            {
                case SecurDll.SECURITY:
                    return QueryContextChannelBinding_SECURITY(phContext, contextAttribute, buffer, refHandle);

                case SecurDll.SECUR32:
                    return QueryContextChannelBinding_SECUR32(phContext, contextAttribute, buffer, refHandle);

                case SecurDll.SCHANNEL:
                    return QueryContextChannelBinding_SCHANNEL(phContext, contextAttribute, buffer, refHandle);
            }
            return -1;
        }
        public static unsafe int QueryContextAttributes(SecurDll dll, SafeDeleteContext phContext, ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle)
        {
            switch (dll)
            {
                case SecurDll.SECURITY:
                    return QueryContextAttributes_SECURITY(phContext, contextAttribute, buffer, refHandle);

                case SecurDll.SECUR32:
                    return QueryContextAttributes_SECUR32(phContext, contextAttribute, buffer, refHandle);

                case SecurDll.SCHANNEL:
                    return QueryContextAttributes_SCHANNEL(phContext, contextAttribute, buffer, refHandle);
            }
            return -1;
        }
 private static unsafe int QueryContextAttributes_SCHANNEL(SafeDeleteContext phContext, ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle)
 {
     int num = -2146893055;
     bool success = false;
     RuntimeHelpers.PrepareConstrainedRegions();
     try
     {
         phContext.DangerousAddRef(ref success);
     }
     catch (Exception exception)
     {
         if (success)
         {
             phContext.DangerousRelease();
             success = false;
         }
         if (!(exception is ObjectDisposedException))
         {
             throw;
         }
     }
     finally
     {
         if (success)
         {
             num = UnsafeNclNativeMethods.SafeNetHandles_SCHANNEL.QueryContextAttributesA(ref phContext._handle, contextAttribute, (void*) buffer);
             phContext.DangerousRelease();
         }
         if ((num == 0) && (refHandle != null))
         {
             if (refHandle is SafeFreeContextBuffer)
             {
                 ((SafeFreeContextBuffer) refHandle).Set(*((IntPtr*) buffer));
             }
             else
             {
                 ((SafeFreeCertContext) refHandle).Set(*((IntPtr*) buffer));
             }
         }
         if ((num != 0) && (refHandle != null))
         {
             refHandle.SetHandleAsInvalid();
         }
     }
     return num;
 }
 private static unsafe int QueryContextChannelBinding_SCHANNEL(SafeDeleteContext phContext, ContextAttribute contextAttribute, Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle)
 {
     int num = -2146893055;
     bool success = false;
     RuntimeHelpers.PrepareConstrainedRegions();
     try
     {
         phContext.DangerousAddRef(ref success);
     }
     catch (Exception exception)
     {
         if (success)
         {
             phContext.DangerousRelease();
             success = false;
         }
         if (!(exception is ObjectDisposedException))
         {
             throw;
         }
     }
     finally
     {
         if (success)
         {
             num = UnsafeNclNativeMethods.SafeNetHandles_SCHANNEL.QueryContextAttributesA(ref phContext._handle, contextAttribute, (void*) buffer);
             phContext.DangerousRelease();
         }
         if ((num == 0) && (refHandle != null))
         {
             refHandle.Set(buffer.pBindings);
             refHandle.size = buffer.BindingsLength;
         }
         if ((num != 0) && (refHandle != null))
         {
             refHandle.SetHandleAsInvalid();
         }
     }
     return num;
 }
 private unsafe int DecryptMessageHelper(SafeDeleteContext context, SecurityBufferDescriptor inputOutput, uint sequenceNumber)
 {
     int num = -2146893055;
     bool success = false;
     uint qualityOfProtection = 0;
     RuntimeHelpers.PrepareConstrainedRegions();
     try
     {
         context.DangerousAddRef(ref success);
     }
     catch (Exception exception)
     {
         if (success)
         {
             context.DangerousRelease();
             success = false;
         }
         if (!(exception is ObjectDisposedException))
         {
             throw;
         }
     }
     finally
     {
         if (success)
         {
             num = UnsafeNclNativeMethods.NativeNTSSPI.DecryptMessage(ref context._handle, inputOutput, sequenceNumber, &qualityOfProtection);
             context.DangerousRelease();
         }
     }
     if ((num == 0) && (qualityOfProtection == 0x80000001))
     {
         throw new InvalidOperationException(SR.GetString("net_auth_message_not_encrypted"));
     }
     return num;
 }
 public int QueryContextChannelBinding(SafeDeleteContext context, ContextAttribute attribute, out SafeFreeContextBufferChannelBinding binding)
 {
     binding = null;
     throw new NotSupportedException();
 }
예제 #10
0
 public int QueryContextChannelBinding(SafeDeleteContext context, Interop.Secur32.ContextAttribute attribute, out SafeFreeContextBufferChannelBinding binding)
 {
     // Querying an auth SSP for a CBT is not supported.
     binding = null;
     throw new NotSupportedException();
 }
예제 #11
0
 public int QuerySecurityContextToken(SafeDeleteContext phContext, out SecurityContextTokenHandle phToken)
 {
     return(GetSecurityContextToken(phContext, out phToken));
 }
 public int InitializeSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, ContextFlags inFlags, Endianness endianness, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref ContextFlags outFlags)
 {
     return(SafeDeleteContext.InitializeSecurityContext(Library, ref credential, ref context, targetName, inFlags, endianness, inputBuffer, null, outputBuffer, ref outFlags));
 }
        //
        // After PINvoke call the method will fix the refHandle.handle with the returned value.
        // The caller is responsible for creating a correct SafeHandle template or null can be passed if no handle is returned.
        //
        // This method switches between three non-interruptible helper methods.  (This method can't be both non-interruptible and
        // reference imports from all three DLLs - doing so would cause all three DLLs to try to be bound to.)
        //
        public unsafe static int QueryContextAttributes(SecurDll dll, SafeDeleteContext phContext, ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle)
        {
            switch (dll)
            {
                case SecurDll.SECURITY:
                    return QueryContextAttributes_SECURITY(phContext, contextAttribute, buffer, refHandle);

                default:
                    return -1;
            }
        }
예제 #14
0
        private unsafe static int QueryContextChannelBinding_SECURITY(SafeDeleteContext phContext, ContextAttribute contextAttribute, Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle)
        {
            int status = (int)SecurityStatus.InvalidHandle;
            bool b = false;

            // SCHANNEL only supports SECPKG_ATTR_ENDPOINT_BINDINGS and SECPKG_ATTR_UNIQUE_BINDINGS which
            // map to our enum ChannelBindingKind.Endpoint and ChannelBindingKind.Unique.
            if (contextAttribute != ContextAttribute.EndpointBindings && contextAttribute != ContextAttribute.UniqueBindings)
            {
                return status;
            }

            // We don't want to be interrupted by thread abort exceptions or unexpected out-of-memory errors failing to jit
            // one of the following methods. So run within a CER non-interruptible block.
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                phContext.DangerousAddRef(ref b);
            }
            catch(Exception e) {
                if (b)
                {
                    phContext.DangerousRelease();
                    b = false;
                }
                if (!(e is ObjectDisposedException))
                    throw;
            }
            finally {

                if (b)
                {
                    status = UnsafeNclNativeMethods.SafeNetHandles_SECURITY.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer);
                    phContext.DangerousRelease();
                }

                if (status == 0 && refHandle != null) {
                    refHandle.Set((*buffer).pBindings);
                    refHandle.size = (*buffer).BindingsLength;
                }

                if (status != 0 && refHandle != null) {
                    refHandle.SetHandleAsInvalid();
                }
            }

            return status;
        }
예제 #15
0
        private static int GetSecurityContextToken(SafeDeleteContext phContext, out SafeCloseHandle safeHandle) {

            int status = (int)SecurityStatus.InvalidHandle;
            bool b = false;
            safeHandle = null;

            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                phContext.DangerousAddRef(ref b);
            }
            catch (Exception e) {
                if (b) {
                    phContext.DangerousRelease();
                    b = false;
                }
                if (!(e is ObjectDisposedException))
                    throw;
            }
            finally {
                if (b) {
                    status = UnsafeNclNativeMethods.SafeNetHandles.QuerySecurityContextToken(ref phContext._handle, out safeHandle);
                    phContext.DangerousRelease();
                }
            }

            return status;
        }
예제 #16
0
        public static SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute)
        {
            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Enter("QueryContextChannelBinding", contextAttribute.ToString());
            }

            SafeFreeContextBufferChannelBinding result;
            int errorCode = secModule.QueryContextChannelBinding(securityContext, contextAttribute, out result);

            if (errorCode != 0)
            {
                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.Leave("QueryContextChannelBinding", "ERROR = " + ErrorDescription(errorCode));
                }
                return(null);
            }

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Leave("QueryContextChannelBinding", LoggingHash.HashString(result));
            }
            return(result);
        }
예제 #17
0
        private unsafe static int EncryptDecryptHelper(OP op, SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
        {
            Interop.SspiCli.SecurityBufferDescriptor sdcInOut = new Interop.SspiCli.SecurityBufferDescriptor(input.Length);
            var unmanagedBuffer = new Interop.SspiCli.SecurityBufferStruct[input.Length];

            fixed(Interop.SspiCli.SecurityBufferStruct *unmanagedBufferPtr = unmanagedBuffer)
            {
                sdcInOut.UnmanagedPointer = unmanagedBufferPtr;
                GCHandle[] pinnedBuffers = new GCHandle[input.Length];
                byte[][]   buffers       = new byte[input.Length][];
                try
                {
                    for (int i = 0; i < input.Length; i++)
                    {
                        SecurityBuffer iBuffer = input[i];
                        unmanagedBuffer[i].count = iBuffer.size;
                        unmanagedBuffer[i].type  = iBuffer.type;
                        if (iBuffer.token == null || iBuffer.token.Length == 0)
                        {
                            unmanagedBuffer[i].token = IntPtr.Zero;
                        }
                        else
                        {
                            pinnedBuffers[i]         = GCHandle.Alloc(iBuffer.token, GCHandleType.Pinned);
                            unmanagedBuffer[i].token = Marshal.UnsafeAddrOfPinnedArrayElement(iBuffer.token, iBuffer.offset);
                            buffers[i] = iBuffer.token;
                        }
                    }

                    // The result is written in the input Buffer passed as type=BufferType.Data.
                    int errorCode;
                    switch (op)
                    {
                    case OP.Encrypt:
                        errorCode = secModule.EncryptMessage(context, sdcInOut, sequenceNumber);
                        break;

                    case OP.Decrypt:
                        errorCode = secModule.DecryptMessage(context, sdcInOut, sequenceNumber);
                        break;

                    case OP.MakeSignature:
                        errorCode = secModule.MakeSignature(context, sdcInOut, sequenceNumber);
                        break;

                    case OP.VerifySignature:
                        errorCode = secModule.VerifySignature(context, sdcInOut, sequenceNumber);
                        break;

                    default:
                        if (GlobalLog.IsEnabled)
                        {
                            GlobalLog.Assert("SSPIWrapper::EncryptDecryptHelper", "Unknown OP: " + op);
                        }

                        Debug.Fail("SSPIWrapper::EncryptDecryptHelper", "Unknown OP: " + op);
                        throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
                    }

                    // Marshalling back returned sizes / data.
                    for (int i = 0; i < input.Length; i++)
                    {
                        SecurityBuffer iBuffer = input[i];
                        iBuffer.size = unmanagedBuffer[i].count;
                        iBuffer.type = unmanagedBuffer[i].type;

                        if (iBuffer.size == 0)
                        {
                            iBuffer.offset = 0;
                            iBuffer.token  = null;
                        }
                        else
                        {
                            checked
                            {
                                // Find the buffer this is inside of.  Usually they all point inside buffer 0.
                                int j;
                                for (j = 0; j < input.Length; j++)
                                {
                                    if (buffers[j] == null)
                                    {
                                        continue;
                                    }

                                    byte *bufferAddress = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement(buffers[j], 0);
                                    if ((byte *)unmanagedBuffer[i].token >= bufferAddress &&
                                        (byte *)unmanagedBuffer[i].token + iBuffer.size <= bufferAddress + buffers[j].Length)
                                    {
                                        iBuffer.offset = (int)((byte *)unmanagedBuffer[i].token - bufferAddress);
                                        iBuffer.token  = buffers[j];
                                        break;
                                    }
                                }

                                if (j >= input.Length)
                                {
                                    if (GlobalLog.IsEnabled)
                                    {
                                        GlobalLog.Assert("SSPIWrapper::EncryptDecryptHelper", "Output buffer out of range.");
                                    }

                                    Debug.Fail("SSPIWrapper::EncryptDecryptHelper", "Output buffer out of range.");
                                    iBuffer.size   = 0;
                                    iBuffer.offset = 0;
                                    iBuffer.token  = null;
                                }
                            }
                        }

                        // Backup validate the new sizes.
                        if (iBuffer.offset < 0 || iBuffer.offset > (iBuffer.token == null ? 0 : iBuffer.token.Length))
                        {
                            if (GlobalLog.IsEnabled)
                            {
                                GlobalLog.AssertFormat("SSPIWrapper::EncryptDecryptHelper|'offset' out of range.  [{0}]", iBuffer.offset);
                            }

                            Debug.Fail("SSPIWrapper::EncryptDecryptHelper|'offset' out of range.  [" + iBuffer.offset + "]");
                        }

                        if (iBuffer.size < 0 || iBuffer.size > (iBuffer.token == null ? 0 : iBuffer.token.Length - iBuffer.offset))
                        {
                            if (GlobalLog.IsEnabled)
                            {
                                GlobalLog.AssertFormat("SSPIWrapper::EncryptDecryptHelper|'size' out of range.  [{0}]", iBuffer.size);
                            }

                            Debug.Fail("SSPIWrapper::EncryptDecryptHelper|'size' out of range.  [" + iBuffer.size + "]");
                        }
                    }

                    if (errorCode != 0 && NetEventSource.Log.IsEnabled())
                    {
                        if (errorCode == Interop.SspiCli.SEC_I_RENEGOTIATE)
                        {
                            NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.event_OperationReturnedSomething, op, "SEC_I_RENEGOTIATE"));
                        }
                        else
                        {
                            NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.net_log_operation_failed_with_error, op, String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
                        }
                    }

                    return(errorCode);
                }
                finally
                {
                    for (int i = 0; i < pinnedBuffers.Length; ++i)
                    {
                        if (pinnedBuffers[i].IsAllocated)
                        {
                            pinnedBuffers[i].Free();
                        }
                    }
                }
            }
        }
예제 #18
0
 public static int VerifySignature(SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
 {
     return(EncryptDecryptHelper(OP.VerifySignature, secModule, context, input, sequenceNumber));
 }
예제 #19
0
 public static int QuerySecurityContextToken(SSPIInterface secModule, SafeDeleteContext context, out SecurityContextTokenHandle token)
 {
     return(secModule.QuerySecurityContextToken(context, out token));
 }
예제 #20
0
        internal static int AcceptSecurityContext(SSPIInterface secModule, SafeFreeCredentials credential, ref SafeDeleteContext context, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
        {
            if (SecurityEventSource.Log.IsEnabled())
            {
                SecurityEventSource.Log.AcceptSecurityContext(credential.ToString(), LoggingHash.ObjectToString(context), inFlags);
            }

            int errorCode = secModule.AcceptSecurityContext(credential, ref context, inputBuffers, inFlags, datarep, outputBuffer, ref outFlags);

            if (SecurityEventSource.Log.IsEnabled())
            {
                SecurityEventSource.Log.SecurityContextInputBuffers("AcceptSecurityContext", (inputBuffers == null ? 0 : inputBuffers.Length), outputBuffer.size, (Interop.SecurityStatus)errorCode);
            }

            return(errorCode);
        }
예제 #21
0
        internal static int InitializeSecurityContext(SSPIInterface secModule, ref SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
        {
            if (SecurityEventSource.Log.IsEnabled())
            {
                SecurityEventSource.Log.InitializeSecurityContext(credential.ToString(),
                                                                  LoggingHash.ObjectToString(context),
                                                                  targetName,
                                                                  inFlags);
            }

            int errorCode = secModule.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, datarep, inputBuffer, outputBuffer, ref outFlags);

            if (SecurityEventSource.Log.IsEnabled())
            {
                SecurityEventSource.Log.SecurityContextInputBuffer("InitializeSecurityContext", (inputBuffer == null ? 0 : inputBuffer.size), outputBuffer.size, (Interop.SecurityStatus)errorCode);
            }

            return(errorCode);
        }
예제 #22
0
 public int InitializeSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags)
 {
     return(SafeDeleteContext.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, endianness, null, inputBuffers, outputBuffer, ref outFlags));
 }
예제 #23
0
 public int QuerySecurityContextToken(SafeDeleteContext phContext, out SafeCloseHandle phToken) {
     return GetSecurityContextToken(phContext, out phToken);
 }
예제 #24
0
        public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute)
        {
            int errorCode;

            return(QueryContextAttributes(secModule, securityContext, contextAttribute, out errorCode));
        }
예제 #25
0
 public int InitializeSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, ContextFlags inFlags, Endianness endianness, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref ContextFlags outFlags) {
     return SafeDeleteContext.InitializeSecurityContext(Library, ref credential, ref context, targetName, inFlags, endianness, null, inputBuffers, outputBuffer, ref outFlags);
 }
예제 #26
0
        public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute, out int errorCode)
        {
            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Enter("QueryContextAttributes", contextAttribute.ToString());
            }

            int  nativeBlockSize = IntPtr.Size;
            Type handleType      = null;

            switch (contextAttribute)
            {
            case Interop.SspiCli.ContextAttribute.Sizes:
                nativeBlockSize = SecSizes.SizeOf;
                break;

            case Interop.SspiCli.ContextAttribute.StreamSizes:
                nativeBlockSize = StreamSizes.SizeOf;
                break;

            case Interop.SspiCli.ContextAttribute.Names:
                handleType = typeof(SafeFreeContextBuffer);
                break;

            case Interop.SspiCli.ContextAttribute.PackageInfo:
                handleType = typeof(SafeFreeContextBuffer);
                break;

            case Interop.SspiCli.ContextAttribute.NegotiationInfo:
                handleType      = typeof(SafeFreeContextBuffer);
                nativeBlockSize = Marshal.SizeOf <NegotiationInfo>();
                break;

            case Interop.SspiCli.ContextAttribute.ClientSpecifiedSpn:
                handleType = typeof(SafeFreeContextBuffer);
                break;

            case Interop.SspiCli.ContextAttribute.RemoteCertificate:
                handleType = typeof(SafeFreeCertContext);
                break;

            case Interop.SspiCli.ContextAttribute.LocalCertificate:
                handleType = typeof(SafeFreeCertContext);
                break;

            case Interop.SspiCli.ContextAttribute.IssuerListInfoEx:
                nativeBlockSize = Marshal.SizeOf <Interop.SspiCli.IssuerListInfoEx>();
                handleType      = typeof(SafeFreeContextBuffer);
                break;

            case Interop.SspiCli.ContextAttribute.ConnectionInfo:
                nativeBlockSize = Marshal.SizeOf <SslConnectionInfo>();
                break;

            default:
                throw new ArgumentException(SR.Format(SR.net_invalid_enum, "ContextAttribute"), "contextAttribute");
            }

            SafeHandle sspiHandle = null;
            object     attribute  = null;

            try
            {
                var nativeBuffer = new byte[nativeBlockSize];
                errorCode = secModule.QueryContextAttributes(securityContext, contextAttribute, nativeBuffer, handleType, out sspiHandle);
                if (errorCode != 0)
                {
                    if (GlobalLog.IsEnabled)
                    {
                        GlobalLog.Leave("Win32:QueryContextAttributes", "ERROR = " + ErrorDescription(errorCode));
                    }
                    return(null);
                }

                switch (contextAttribute)
                {
                case Interop.SspiCli.ContextAttribute.Sizes:
                    attribute = new SecSizes(nativeBuffer);
                    break;

                case Interop.SspiCli.ContextAttribute.StreamSizes:
                    attribute = new StreamSizes(nativeBuffer);
                    break;

                case Interop.SspiCli.ContextAttribute.Names:
                    attribute = Marshal.PtrToStringUni(sspiHandle.DangerousGetHandle());
                    break;

                case Interop.SspiCli.ContextAttribute.PackageInfo:
                    attribute = new SecurityPackageInfoClass(sspiHandle, 0);
                    break;

                case Interop.SspiCli.ContextAttribute.NegotiationInfo:
                    unsafe
                    {
                        fixed(void *ptr = nativeBuffer)
                        {
                            attribute = new NegotiationInfoClass(sspiHandle, Marshal.ReadInt32(new IntPtr(ptr), NegotiationInfo.NegotiationStateOffest));
                        }
                    }
                    break;

                case Interop.SspiCli.ContextAttribute.ClientSpecifiedSpn:
                    attribute = Marshal.PtrToStringUni(sspiHandle.DangerousGetHandle());
                    break;

                case Interop.SspiCli.ContextAttribute.LocalCertificate:
                // Fall-through to RemoteCertificate is intentional.
                case Interop.SspiCli.ContextAttribute.RemoteCertificate:
                    attribute  = sspiHandle;
                    sspiHandle = null;
                    break;

                case Interop.SspiCli.ContextAttribute.IssuerListInfoEx:
                    attribute  = new Interop.SspiCli.IssuerListInfoEx(sspiHandle, nativeBuffer);
                    sspiHandle = null;
                    break;

                case Interop.SspiCli.ContextAttribute.ConnectionInfo:
                    attribute = new SslConnectionInfo(nativeBuffer);
                    break;

                default:
                    // Will return null.
                    break;
                }
            }
            finally
            {
                if (sspiHandle != null)
                {
                    sspiHandle.Dispose();
                }
            }

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Leave("QueryContextAttributes", LoggingHash.ObjectToString(attribute));
            }

            return(attribute);
        }
        //
        // After PINvoke call the method will fix the handleTemplate.handle with the returned value.
        // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavour or null can be passed if no handle is returned.
        //
        // Since it has a CER, this method can't have any references to imports from DLLs that may not exist on the system.
        //
        private static unsafe int MustRunAcceptSecurityContext_SECURITY(
                                                  ref SafeFreeCredentials     inCredentials,
                                                  void*            inContextPtr,
                                                  SecurityBufferDescriptor inputBuffer,
                                                  ContextFlags     inFlags,
                                                  Endianness       endianness,
                                                  SafeDeleteContext outContext,
                                                  SecurityBufferDescriptor outputBuffer,
                                                  ref ContextFlags outFlags,
                                                  SafeFreeContextBuffer handleTemplate)
        {
            int errorCode = (int) SecurityStatus.InvalidHandle;
            bool b1 = false;
            bool b2 = false;

            // Run the body of this method as a non-interruptible block.
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                inCredentials.DangerousAddRef(ref b1);
                outContext.DangerousAddRef(ref b2);
            }
            catch(Exception e)
            {
                if (b1)
                {
                    inCredentials.DangerousRelease();
                    b1 = false;
                }
                if (b2)
                {
                    outContext.DangerousRelease();
                    b2 = false;
                }
                if (!(e is ObjectDisposedException))
                    throw;
            }
            finally {
                SSPIHandle credentialHandle = inCredentials._handle;
                long timeStamp;

                if (!b1)
                {
                    // caller should retry
                    inCredentials = null;
                }
                else if (b1 && b2)
                {
                    errorCode = UnsafeNclNativeMethods.SafeNetHandles_SECURITY.AcceptSecurityContext(
                                ref credentialHandle,
                                inContextPtr,
                                inputBuffer,
                                inFlags,
                                endianness,
                                ref outContext._handle,
                                outputBuffer,
                                ref outFlags,
                                out timeStamp);

                    //
                    // When a credential handle is first associated with the context we keep credential
                    // ref count bumped up to ensure ordered finalization.
                    // If the credential handle has been changed we de-ref the old one and associate the
                    //  context with the new cred handle but only if the call was successful.
                    if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0)
                    {
                        // Disassociate the previous credential handle
                        if (outContext._EffectiveCredential != null)
                            outContext._EffectiveCredential.DangerousRelease();
                        outContext._EffectiveCredential = inCredentials;
                    }
                    else
                    {
                        inCredentials.DangerousRelease();
                    }

                    outContext.DangerousRelease();

                    // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer.
                    if (handleTemplate != null)
                    {
                        handleTemplate.Set(((SecurityBufferStruct*)outputBuffer.UnmanagedPointer)->token); //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes
                        if (handleTemplate.IsInvalid)
                        {
                            handleTemplate.SetHandleAsInvalid();
                        }
                    }
                }

                if (inContextPtr == null && (errorCode & 0x80000000) != 0)
                {
                    // an error on the first call, need to set the out handle to invalid value
                    outContext._handle.SetToInvalid();
                }
            }

            return errorCode;
        }
예제 #28
0
 public static void QueryContextStreamSizes(SafeDeleteContext securityContext, out StreamSizes streamSizes)
 {
     streamSizes = s_streamSizes;
 }
        public static int SetContextAttributes(SecurDll dll, SafeDeleteContext phContext, 
            ContextAttribute contextAttribute, byte[] buffer)
        {
            switch (dll)
            {
                case SecurDll.SECURITY:
                    return SetContextAttributes_SECURITY(phContext, contextAttribute, buffer);

                default:
                    return -1;
            }
        }
예제 #30
0
 public static void QueryContextConnectionInfo(SafeDeleteContext securityContext, out SslConnectionInfo connectionInfo)
 {
     connectionInfo = new SslConnectionInfo(((SafeDeleteSslContext)securityContext).SslContext);
 }
예제 #31
0
 public int CompleteAuthToken(ref SafeDeleteContext refContext, SecurityBuffer[] inputBuffers)
 {
     return(SafeDeleteContext.CompleteAuthToken(ref refContext, inputBuffers));
 }
예제 #32
0
        public unsafe int QueryContextChannelBinding(SafeDeleteContext phContext, ContextAttribute attribute, out SafeFreeContextBufferChannelBinding refHandle)
        {
            refHandle = SafeFreeContextBufferChannelBinding.CreateEmptyHandle(Library);

            // bindings is on the stack, so there's no need for a fixed block
            Bindings bindings = new Bindings();
            return SafeFreeContextBufferChannelBinding.QueryContextChannelBinding(Library, phContext, attribute, &bindings, refHandle);
        }
예제 #33
0
 public int SetContextAttributes(SafeDeleteContext context, Interop.Secur32.ContextAttribute attribute, byte[] buffer)
 {
     throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
 }
예제 #34
0
 public int QuerySecurityContextToken(SafeDeleteContext phContext, out SafeCloseHandle phToken) {
     throw new NotSupportedException();
 }
예제 #35
0
        public unsafe int DecryptMessage(SafeDeleteContext context, SecurityBufferDescriptor inputOutput, uint sequenceNumber) {
            int status = (int)SecurityStatus.InvalidHandle;
            bool b = false;
            uint qop = 0;

            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                context.DangerousAddRef(ref b);
            }
            catch(Exception e) {
                if (b)
                {
                    context.DangerousRelease();
                    b = false;
                }
                if (!(e is ObjectDisposedException))
                    throw;
            }
            finally {

                if (b)
                {
                    status = UnsafeNclNativeMethods.NativeNTSSPI.DecryptMessage(ref context._handle, inputOutput, sequenceNumber, &qop);
                    context.DangerousRelease();
                }
            }

            const uint SECQOP_WRAP_NO_ENCRYPT = 0x80000001;
            if (status == 0 && qop == SECQOP_WRAP_NO_ENCRYPT)
            {
                GlobalLog.Assert("NativeNTSSPI.DecryptMessage", "Expected qop = 0, returned value = " + qop.ToString("x", CultureInfo.InvariantCulture));
                throw new InvalidOperationException(SR.GetString(SR.net_auth_message_not_encrypted));
            }


            return status;
        }
예제 #36
0
        public unsafe int QueryContextAttributes(SafeDeleteContext context, ContextAttribute  attribute, byte[] buffer, Type handleType, out SafeHandle refHandle) {

            refHandle = null;
            if (handleType != null) {
                if (handleType == typeof(SafeFreeContextBuffer)) {
                    refHandle = SafeFreeContextBuffer.CreateEmptyHandle(Library);
                }
                else if (handleType == typeof(SafeFreeCertContext)) {
                    refHandle = new SafeFreeCertContext();
                }
                else {
                    throw new ArgumentException(SR.GetString(SR.SSPIInvalidHandleType, handleType.FullName), "handleType");
                }
            }

            fixed (byte* bufferPtr = buffer) {
                return SafeFreeContextBuffer.QueryContextAttributes(Library, context, attribute, bufferPtr, refHandle);
            }
        }
예제 #37
0
        private static SecurityStatusPal HandshakeInternal(SafeFreeCredentials credential, ref SafeDeleteContext context,
                                                           SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, bool isServer, bool remoteCertRequired)
        {
            Debug.Assert(!credential.IsInvalid);

            try
            {
                if ((null == context) || context.IsInvalid)
                {
                    context = new SafeDeleteSslContext(credential as SafeFreeSslCredentials, isServer, remoteCertRequired);
                }

                byte[] output = null;
                int    outputSize;
                bool   done;

                if (null == inputBuffer)
                {
                    done = Interop.OpenSsl.DoSslHandshake(((SafeDeleteSslContext)context).SslContext, null, 0, 0, out output, out outputSize);
                }
                else
                {
                    done = Interop.OpenSsl.DoSslHandshake(((SafeDeleteSslContext)context).SslContext, inputBuffer.token, inputBuffer.offset, inputBuffer.size, out output, out outputSize);
                }

                outputBuffer.size   = outputSize;
                outputBuffer.offset = 0;
                outputBuffer.token  = outputSize > 0 ? output : null;

                return(new SecurityStatusPal(done ? SecurityStatusPalErrorCode.OK : SecurityStatusPalErrorCode.ContinueNeeded));
            }
            catch (Exception exc)
            {
                return(new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, exc));
            }
        }
예제 #38
0
 public int AcceptSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, SecurityBuffer[] inputBuffers, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags)
 {
     return(SafeDeleteContext.AcceptSecurityContext(ref credential, ref context, inFlags, endianness, null, inputBuffers, outputBuffer, ref outFlags));
 }
예제 #39
0
 public int SetContextAttributes(SafeDeleteContext phContext, ContextAttribute attribute, byte[] buffer) {
     return SafeFreeContextBuffer.SetContextAttributes(Library, phContext, attribute, buffer);
 }
예제 #40
0
 public int QueryContextIssuerList(SafeDeleteContext securityContext, out Object issuerList)
 {
     // TODO (Issue #3362) To be implemented
     throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
 }
예제 #41
0
 public int CompleteAuthToken(ref SafeDeleteContext refContext, SecurityBuffer[] inputBuffers) {
     throw new NotSupportedException();
 }
예제 #42
0
 public SecurityStatus AcceptSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context,
                                             SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, bool remoteCertRequired)
 {
     return(HandshakeInternal(credential, ref context, inputBuffer, outputBuffer, true, remoteCertRequired));
 }
예제 #43
0
 public int QueryContextChannelBinding(SafeDeleteContext context, ContextAttribute attribute, out SafeFreeContextBufferChannelBinding binding)
 {
     // Querying an auth SSP for a CBT doesn't make sense
     binding = null;
     throw new NotSupportedException();
 }
예제 #44
0
 public SecurityStatus InitializeSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context,
                                                 string targetName, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer)
 {
     return(HandshakeInternal(credential, ref context, inputBuffer, outputBuffer, false, false));
 }
예제 #45
0
 public int SetContextAttributes(SafeDeleteContext context, ContextAttribute  attribute, byte[] buffer) {
     throw new NotImplementedException();
 }
예제 #46
0
 public SecurityStatus InitializeSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer)
 {
     Debug.Assert(inputBuffers.Length == 2);
     Debug.Assert(inputBuffers[1].token == null);
     return(HandshakeInternal(credential, ref context, inputBuffers[0], outputBuffer, false, false));
 }
예제 #47
0
 public int CompleteAuthToken(ref SafeDeleteContext refContext, SecurityBuffer[] inputBuffers) {
     return SafeDeleteContext.CompleteAuthToken(Library, ref refContext, inputBuffers);
 }
예제 #48
0
 public SecurityStatus EncryptMessage(SafeDeleteContext securityContext, byte[] buffer, int size, int headerSize, int trailerSize, out int resultSize)
 {
     // Unencrypted data starts at an offset of headerSize
     return(EncryptDecryptHelper(securityContext, buffer, headerSize, size, headerSize, trailerSize, true, out resultSize));
 }
예제 #49
0
 public int AcceptSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, SecurityBuffer[] inputBuffers, ContextFlags inFlags, Endianness endianness, SecurityBuffer outputBuffer, ref ContextFlags outFlags) {
     return SafeDeleteContext.AcceptSecurityContext(Library, ref credential, ref context, inFlags, endianness, null, inputBuffers, outputBuffer, ref outFlags);
 }
예제 #50
0
 public int QueryContextChannelBinding(SafeDeleteContext phContext, ChannelBindingKind attribute,
                                       out SafeFreeContextBufferChannelBinding refHandle)
 {
     // TODO (Issue #3362) To be implemented
     throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
 }
예제 #51
0
        public int EncryptMessage(SafeDeleteContext context, SecurityBufferDescriptor inputOutput, uint sequenceNumber)
        {
            int status = (int)SecurityStatus.InvalidHandle;
            bool b = false;

            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                context.DangerousAddRef(ref b);
            }
            catch(Exception e) {
                if (b)
                {
                    context.DangerousRelease();
                    b = false;
                }
                if (!(e is ObjectDisposedException))
                    throw;
            }
            finally {

                if (b)
                {
                    status = UnsafeNclNativeMethods.NativeNTSSPI.EncryptMessage(ref context._handle, 0, inputOutput, sequenceNumber);
                    context.DangerousRelease();
                }
            }
            return status;
        }
예제 #52
0
 public unsafe static SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute)
 {
     return(SSPIWrapper.QueryContextChannelBinding(GlobalSSPI.SSPISecureChannel, securityContext, (Interop.SspiCli.ContextAttribute)attribute));
 }
        //-------------------------------------------------------------------
        internal unsafe static int AcceptSecurityContext(
            SecurDll                dll,
            ref SafeFreeCredentials inCredentials,
            ref SafeDeleteContext   refContext,
            ContextFlags            inFlags,
            Endianness              endianness,
            SecurityBuffer          inSecBuffer,
            SecurityBuffer[]        inSecBuffers,
            SecurityBuffer          outSecBuffer,
            ref ContextFlags        outFlags) {

#if TRAVE
            GlobalLog.Enter("SafeDeleteContext::AcceptSecurityContex");
            GlobalLog.Print("    DLL              = " + dll);
            GlobalLog.Print("    credential       = " + inCredentials.ToString());
            GlobalLog.Print("    refContext       = " + ValidationHelper.ToString(refContext));

            GlobalLog.Print("    inFlags          = " + inFlags);
//            GlobalLog.Print("    endianness       = " + endianness);
//            GlobalLog.Print("    inSecBuffer      = " + SecurityBuffer.ToString(inSecBuffer));
//
            if (inSecBuffers==null)
            {
                GlobalLog.Print("    inSecBuffers     = (null)");
            }
            else
            {
                GlobalLog.Print("    inSecBuffers[]   = length:" + inSecBuffers.Length);
//                for (int index=0; index<inSecBuffers.Length; index++) { GlobalLog.Print("    inSecBuffers[" + index + "]   = " + SecurityBuffer.ToString(inSecBuffers[index])); }
            }
//            GlobalLog.Print("    newContext       = {ref} inContext");
//            GlobalLog.Print("    outSecBuffer     = " + SecurityBuffer.ToString(outSecBuffer));
//            GlobalLog.Print("    outFlags         = {ref} " + outFlags);
//            GlobalLog.Print("    timestamp        = null");
#endif
            GlobalLog.Assert(outSecBuffer != null, "SafeDeleteContext::AcceptSecurityContext()|outSecBuffer != null");
            GlobalLog.Assert(inSecBuffer == null || inSecBuffers == null, "SafeDeleteContext::AcceptSecurityContext()|inSecBuffer == null || inSecBuffers == null");

            if (inCredentials == null)
            {
                throw new ArgumentNullException("inCredentials");
            }

            SecurityBufferDescriptor inSecurityBufferDescriptor = null;
            if (inSecBuffer!=null)
            {
                inSecurityBufferDescriptor = new SecurityBufferDescriptor(1);
            }
            else if (inSecBuffers!=null)
            {
                inSecurityBufferDescriptor = new SecurityBufferDescriptor(inSecBuffers.Length);
            }
            SecurityBufferDescriptor outSecurityBufferDescriptor = new SecurityBufferDescriptor(1);

            // actually this is returned in outFlags
            bool isSspiAllocated = (inFlags & ContextFlags.AllocateMemory) != 0 ? true : false;

            int errorCode = -1;

            SSPIHandle contextHandle = new SSPIHandle();
            if (refContext != null)
                contextHandle = refContext._handle;

            // these are pinned user byte arrays passed along with SecurityBuffers
            GCHandle[] pinnedInBytes = null;
            GCHandle pinnedOutBytes = new GCHandle();
            // optional output buffer that may need to be freed
            SafeFreeContextBuffer outFreeContextBuffer = null;
            try
            {
                pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned);
                SecurityBufferStruct[] inUnmanagedBuffer = new SecurityBufferStruct[inSecurityBufferDescriptor==null ? 1:inSecurityBufferDescriptor.Count];
                fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer)
                {
                    if (inSecurityBufferDescriptor!=null)
                    {
                        // Fix Descriptor pointer that points to unmanaged SecurityBuffers
                        inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr;
                        pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count];
                        SecurityBuffer securityBuffer;
                        for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index)
                        {
                            securityBuffer = inSecBuffer!=null ? inSecBuffer : inSecBuffers[index];
                            if (securityBuffer!=null)
                            {
                                // Copy the SecurityBuffer content into unmanaged place holder
                                inUnmanagedBuffer[index].count = securityBuffer.size;
                                inUnmanagedBuffer[index].type  = securityBuffer.type;

                                // use the unmanaged token if it's not null; otherwise use the managed buffer
                                if (securityBuffer.unmanagedToken != null)
                                {
                                    inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle();
                                }
                                else if (securityBuffer.token == null || securityBuffer.token.Length == 0)
                                {
                                    inUnmanagedBuffer[index].token = IntPtr.Zero;
                                }
                                else
                                {
                                    pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
                                    inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
                                }
    #if TRAVE
                                GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size +  " BufferType:" + securityBuffer.type);
    #endif
                            }
                        }
                    }
                    SecurityBufferStruct[] outUnmanagedBuffer = new SecurityBufferStruct[1];
                    fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer)
                    {
                        // Fix Descriptor pointer that points to unmanaged SecurityBuffers
                        outSecurityBufferDescriptor.UnmanagedPointer = outUnmanagedBufferPtr;
                        // Copy the SecurityBuffer content into unmanaged place holder
                        outUnmanagedBuffer[0].count = outSecBuffer.size;
                        outUnmanagedBuffer[0].type  = outSecBuffer.type;

                        if (outSecBuffer.token == null || outSecBuffer.token.Length == 0)
                            outUnmanagedBuffer[0].token  = IntPtr.Zero;
                        else
                            outUnmanagedBuffer[0].token  = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset);

                        if (isSspiAllocated)
                            outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle(dll);

                        switch (dll)
                        {
                        case SecurDll.SECURITY:
                                    if (refContext == null || refContext.IsInvalid)
                                        refContext = new SafeDeleteContext_SECURITY();

                                    errorCode = MustRunAcceptSecurityContext_SECURITY(
                                                    ref inCredentials,
                                                    contextHandle.IsZero? null: &contextHandle,
                                                    inSecurityBufferDescriptor,
                                                    inFlags,
                                                    endianness,
                                                    refContext,
                                                    outSecurityBufferDescriptor,
                                                    ref outFlags,
                                                    outFreeContextBuffer
                                                    );

                                    break;

                        default:  throw new ArgumentException(SR.GetString(SR.net_invalid_enum, "SecurDll"), "Dll");
                        }

                        GlobalLog.Print("SafeDeleteContext:AcceptSecurityContext  Marshalling OUT buffer");
                        // Get unmanaged buffer with index 0 as the only one passed into PInvoke
                        outSecBuffer.size = outUnmanagedBuffer[0].count;
                        outSecBuffer.type = outUnmanagedBuffer[0].type;
                        if (outSecBuffer.size > 0)
                        {
                            outSecBuffer.token = new byte[outSecBuffer.size];
                            Marshal.Copy(outUnmanagedBuffer[0].token, outSecBuffer.token, 0, outSecBuffer.size);
                        }
                        else
                        {
                            outSecBuffer.token = null;
                        }
                    }
                }
            }
            finally {
                if (pinnedInBytes!=null)
                {
                    for (int index=0; index<pinnedInBytes.Length; index++)
                    {
                        if (pinnedInBytes[index].IsAllocated)
                            pinnedInBytes[index].Free();
                    }
                }

                if (pinnedOutBytes.IsAllocated)
                    pinnedOutBytes.Free();

                if (outFreeContextBuffer != null)
                    outFreeContextBuffer.Close();
            }

            GlobalLog.Leave("SafeDeleteContext::AcceptSecurityContex() unmanaged AcceptSecurityContex()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + ValidationHelper.ToString(refContext));

            return errorCode;
        }
예제 #54
0
        public static SecurityStatusPal AcceptSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, bool remoteCertRequired)
        {
            Interop.SspiCli.ContextFlags unusedAttributes = default(Interop.SspiCli.ContextFlags);

            int errorCode = SSPIWrapper.AcceptSecurityContext(
                GlobalSSPI.SSPISecureChannel,
                ref credentialsHandle,
                ref context,
                ServerRequiredFlags | (remoteCertRequired ? Interop.SspiCli.ContextFlags.MutualAuth : Interop.SspiCli.ContextFlags.Zero),
                Interop.SspiCli.Endianness.Native,
                inputBuffer,
                outputBuffer,
                ref unusedAttributes);

            return(GetSecurityStatusPalFromWin32Int(errorCode));
        }
        //
        //
        //
        internal unsafe static int CompleteAuthToken(
            SecurDll                dll,
            ref SafeDeleteContext   refContext,
            SecurityBuffer[]        inSecBuffers) {

            GlobalLog.Enter("SafeDeleteContext::CompleteAuthToken");
            GlobalLog.Print("    DLL              = " + dll);
            GlobalLog.Print("    refContext       = " + ValidationHelper.ToString(refContext));
#if TRAVE
            GlobalLog.Print("    inSecBuffers[]   = length:" + inSecBuffers.Length);
//            for (int index=0; index<inSecBuffers.Length; index++) { GlobalLog.Print("    inSecBuffers[" + index + "]   = " + SecurityBuffer.ToString(inSecBuffers[index])); }
#endif
            GlobalLog.Assert(inSecBuffers != null, "SafeDeleteContext::CompleteAuthToken()|inSecBuffers == null");
            SecurityBufferDescriptor inSecurityBufferDescriptor = new SecurityBufferDescriptor(inSecBuffers.Length);

            int errorCode = (int)SecurityStatus.InvalidHandle;

            // these are pinned user byte arrays passed along with SecurityBuffers
            GCHandle[] pinnedInBytes = null;

            SecurityBufferStruct[] inUnmanagedBuffer = new SecurityBufferStruct[inSecurityBufferDescriptor.Count];
            fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) {
                // Fix Descriptor pointer that points to unmanaged SecurityBuffers
                inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr;
                pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count];
                SecurityBuffer securityBuffer;
                for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index) {
                    securityBuffer = inSecBuffers[index];
                    if (securityBuffer!=null) {
                        inUnmanagedBuffer[index].count = securityBuffer.size;
                        inUnmanagedBuffer[index].type  = securityBuffer.type;

                        // use the unmanaged token if it's not null; otherwise use the managed buffer
                        if (securityBuffer.unmanagedToken != null)
                        {
                            inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle();
                        }
                        else if (securityBuffer.token==null || securityBuffer.token.Length==0) {
                            inUnmanagedBuffer[index].token = IntPtr.Zero;
                        }
                        else {
                            pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
                            inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
                        }
#if TRAVE
                        GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size +  " BufferType:" + securityBuffer.type);
//                        securityBuffer.DebugDump();
#endif
                    }
                }

                SSPIHandle contextHandle = new SSPIHandle();
                if (refContext != null) {
                    contextHandle = refContext._handle;
                }
                try {
                    if (dll==SecurDll.SECURITY) {
                        if (refContext == null || refContext.IsInvalid) {
                            refContext = new SafeDeleteContext_SECURITY();
                        }

                        bool b = false;
                        RuntimeHelpers.PrepareConstrainedRegions();
                        try {
                            refContext.DangerousAddRef(ref b);
                        }
                        catch(Exception e) {
                            if (b)
                            {
                                refContext.DangerousRelease();
                                b = false;
                            }
                            if (!(e is ObjectDisposedException))
                                throw;
                        }
                        finally {
                            if (b)
                            {
                                errorCode = UnsafeNclNativeMethods.SafeNetHandles_SECURITY.CompleteAuthToken(contextHandle.IsZero? null: &contextHandle, inSecurityBufferDescriptor);
                                refContext.DangerousRelease();
                            }
                        }

                    }
                    else {
                        throw new ArgumentException(SR.GetString(SR.net_invalid_enum, "SecurDll"), "Dll");
                    }
                }
                finally {
                    if (pinnedInBytes!=null) {
                        for (int index=0; index<pinnedInBytes.Length; index++) {
                            if (pinnedInBytes[index].IsAllocated) {
                                pinnedInBytes[index].Free();
                            }
                        }
                    }
                }
            }

            GlobalLog.Leave("SafeDeleteContext::CompleteAuthToken() unmanaged CompleteAuthToken()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + ValidationHelper.ToString(refContext));

            return errorCode;
        }
예제 #56
0
        public static SecurityStatusPal InitializeSecurityContext(SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, string targetName, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer)
        {
            Interop.SspiCli.ContextFlags unusedAttributes = default(Interop.SspiCli.ContextFlags);

            int errorCode = SSPIWrapper.InitializeSecurityContext(
                GlobalSSPI.SSPISecureChannel,
                credentialsHandle,
                ref context,
                targetName,
                RequiredFlags | Interop.SspiCli.ContextFlags.InitManualCredValidation,
                Interop.SspiCli.Endianness.Native,
                inputBuffers,
                outputBuffer,
                ref unusedAttributes);

            return(GetSecurityStatusPalFromWin32Int(errorCode));
        }
        private unsafe static int QueryContextAttributes_SECURITY(
            SafeDeleteContext phContext,
            ContextAttribute contextAttribute,
            byte* buffer,
            SafeHandle refHandle)
        {
            int status = (int)SecurityStatus.InvalidHandle;
            bool b = false;

            // We don't want to be interrupted by thread abort exceptions or unexpected out-of-memory errors failing to jit
            // one of the following methods. So run within a CER non-interruptible block.
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                phContext.DangerousAddRef(ref b);
            }
            catch(Exception e) {
                if (b)
                {
                    phContext.DangerousRelease();
                    b = false;
                }
                if (!(e is ObjectDisposedException))
                    throw;
            }
            finally {

                if (b)
                {
                    status = UnsafeNclNativeMethods.SafeNetHandles_SECURITY.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer);
                    phContext.DangerousRelease();
                }

                if (status == 0 && refHandle != null) {
                    if (refHandle is SafeFreeContextBuffer) {
                        ((SafeFreeContextBuffer)refHandle).Set(*(IntPtr*)buffer);
                    }
                    else {
                        ((SafeFreeCertContext)refHandle).Set(*(IntPtr*)buffer);
                    }
                }

                if (status != 0 && refHandle != null) {
                    refHandle.SetHandleAsInvalid();
                }
            }

            return status;
        }
예제 #58
0
 //
 // Extracts a remote certificate upon request.
 //
 internal static X509Certificate2?GetRemoteCertificate(SafeDeleteContext securityContext)
 {
     return(GetRemoteCertificate(securityContext, null));
 }
        private static int SetContextAttributes_SECURITY(
            SafeDeleteContext phContext,
            ContextAttribute contextAttribute,
            byte[] buffer)
        {
            int status = (int)SecurityStatus.InvalidHandle;
            bool b = false;

            // We don't want to be interrupted by thread abort exceptions or unexpected out-of-memory errors failing 
            // to jit one of the following methods. So run within a CER non-interruptible block.
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                phContext.DangerousAddRef(ref b);
            }
            catch(Exception e) {
                if (b)
                {
                    phContext.DangerousRelease();
                    b = false;
                }
                if (!(e is ObjectDisposedException))
                    throw;
            }
            finally {

                if (b)
                {
                    status = UnsafeNclNativeMethods.SafeNetHandles_SECURITY.SetContextAttributesW(
                        ref phContext._handle, contextAttribute, buffer, buffer.Length);
                    phContext.DangerousRelease();
                }
            }

            return status;
        }
 public int AcceptSecurityContext(ref SafeFreeCredentials credential, ref SafeDeleteContext context, SecurityBuffer inputBuffer, ContextFlags inFlags, Endianness endianness, SecurityBuffer outputBuffer, ref ContextFlags outFlags)
 {
     return(SafeDeleteContext.AcceptSecurityContext(Library, ref credential, ref context, inFlags, endianness, inputBuffer, null, outputBuffer, ref outFlags));
 }