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();
 }
Ejemplo n.º 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();
 }
Ejemplo n.º 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));
 }
Ejemplo n.º 13
0
        //
        // 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;
            }
        }
Ejemplo n.º 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;
        }
Ejemplo n.º 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;
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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();
                        }
                    }
                }
            }
        }
Ejemplo n.º 18
0
 public static int VerifySignature(SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
 {
     return(EncryptDecryptHelper(OP.VerifySignature, secModule, context, input, sequenceNumber));
 }
Ejemplo n.º 19
0
 public static int QuerySecurityContextToken(SSPIInterface secModule, SafeDeleteContext context, out SecurityContextTokenHandle token)
 {
     return(secModule.QuerySecurityContextToken(context, out token));
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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));
 }
Ejemplo n.º 23
0
 public int QuerySecurityContextToken(SafeDeleteContext phContext, out SafeCloseHandle phToken) {
     return GetSecurityContextToken(phContext, out phToken);
 }
Ejemplo n.º 24
0
        public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute)
        {
            int errorCode;

            return(QueryContextAttributes(secModule, securityContext, contextAttribute, out errorCode));
        }
Ejemplo n.º 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);
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 27
0
        //
        // 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;
        }
Ejemplo n.º 28
0
 public static void QueryContextStreamSizes(SafeDeleteContext securityContext, out StreamSizes streamSizes)
 {
     streamSizes = s_streamSizes;
 }
Ejemplo n.º 29
0
        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;
            }
        }
Ejemplo n.º 30
0
 public static void QueryContextConnectionInfo(SafeDeleteContext securityContext, out SslConnectionInfo connectionInfo)
 {
     connectionInfo = new SslConnectionInfo(((SafeDeleteSslContext)securityContext).SslContext);
 }
Ejemplo n.º 31
0
 public int CompleteAuthToken(ref SafeDeleteContext refContext, SecurityBuffer[] inputBuffers)
 {
     return(SafeDeleteContext.CompleteAuthToken(ref refContext, inputBuffers));
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 33
0
 public int SetContextAttributes(SafeDeleteContext context, Interop.Secur32.ContextAttribute attribute, byte[] buffer)
 {
     throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
 }
Ejemplo n.º 34
0
 public int QuerySecurityContextToken(SafeDeleteContext phContext, out SafeCloseHandle phToken) {
     throw new NotSupportedException();
 }
Ejemplo n.º 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;
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 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));
            }
        }
Ejemplo n.º 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));
 }
Ejemplo n.º 39
0
 public int SetContextAttributes(SafeDeleteContext phContext, ContextAttribute attribute, byte[] buffer) {
     return SafeFreeContextBuffer.SetContextAttributes(Library, phContext, attribute, buffer);
 }
Ejemplo n.º 40
0
 public int QueryContextIssuerList(SafeDeleteContext securityContext, out Object issuerList)
 {
     // TODO (Issue #3362) To be implemented
     throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
 }
Ejemplo n.º 41
0
 public int CompleteAuthToken(ref SafeDeleteContext refContext, SecurityBuffer[] inputBuffers) {
     throw new NotSupportedException();
 }
Ejemplo n.º 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));
 }
Ejemplo n.º 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();
 }
Ejemplo n.º 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));
 }
Ejemplo n.º 45
0
 public int SetContextAttributes(SafeDeleteContext context, ContextAttribute  attribute, byte[] buffer) {
     throw new NotImplementedException();
 }
Ejemplo n.º 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));
 }
Ejemplo n.º 47
0
 public int CompleteAuthToken(ref SafeDeleteContext refContext, SecurityBuffer[] inputBuffers) {
     return SafeDeleteContext.CompleteAuthToken(Library, ref refContext, inputBuffers);
 }
Ejemplo n.º 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));
 }
Ejemplo n.º 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);
 }
Ejemplo n.º 50
0
 public int QueryContextChannelBinding(SafeDeleteContext phContext, ChannelBindingKind attribute,
                                       out SafeFreeContextBufferChannelBinding refHandle)
 {
     // TODO (Issue #3362) To be implemented
     throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
 }
Ejemplo n.º 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;
        }
Ejemplo n.º 52
0
 public unsafe static SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute)
 {
     return(SSPIWrapper.QueryContextChannelBinding(GlobalSSPI.SSPISecureChannel, securityContext, (Interop.SspiCli.ContextAttribute)attribute));
 }
Ejemplo n.º 53
0
        //-------------------------------------------------------------------
        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;
        }
Ejemplo n.º 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));
        }
Ejemplo n.º 55
0
        //
        //
        //
        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;
        }
Ejemplo n.º 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));
        }
Ejemplo n.º 57
0
        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;
        }
Ejemplo n.º 58
0
 //
 // Extracts a remote certificate upon request.
 //
 internal static X509Certificate2?GetRemoteCertificate(SafeDeleteContext securityContext)
 {
     return(GetRemoteCertificate(securityContext, null));
 }
Ejemplo n.º 59
0
        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));
 }