public static unsafe int AcquireCredentialsHandle(string package, CredentialUse intent, ref SecureCredential authdata, out SafeFreeCredentials outCredential)
 {
     int num = -1;
     IntPtr certContextArray = authdata.certContextArray;
     try
     {
         IntPtr ptr2 = new IntPtr((void*) &certContextArray);
         if (certContextArray != IntPtr.Zero)
         {
             authdata.certContextArray = ptr2;
         }
         outCredential = new SafeFreeCredentials();
         RuntimeHelpers.PrepareConstrainedRegions();
         try
         {
         }
         finally
         {
             long num2;
             num = AcquireCredentialsHandleW(null, package, (int) intent, null, ref authdata, null, null, ref outCredential._handle, out num2);
             if (num != 0)
             {
                 outCredential.SetHandleAsInvalid();
             }
         }
     }
     finally
     {
         authdata.certContextArray = certContextArray;
     }
     return num;
 }
        public override void OnOpening()
        {
            bool flag = System.ServiceModel.Security.SecurityUtils.IsOsGreaterThanXP();

            base.OnOpening();
            if (this.credentialsHandle == null)
            {
                string str;
                if (!this.allowNtlm && !flag)
                {
                    str = "Kerberos";
                }
                else
                {
                    str = "Negotiate";
                }
                NetworkCredential credential = null;
                if (this.clientCredential != null)
                {
                    credential = this.clientCredential.GetCredential(base.TargetAddress.Uri, str);
                }
                if (!this.allowNtlm && flag)
                {
                    this.credentialsHandle = System.ServiceModel.Security.SecurityUtils.GetCredentialsHandle(str, credential, false, new string[] { "!NTLM" });
                }
                else
                {
                    this.credentialsHandle = System.ServiceModel.Security.SecurityUtils.GetCredentialsHandle(str, credential, false, new string[0]);
                }
                this.ownCredentialsHandle = true;
            }
        }
 private void FreeCredentialsHandle()
 {
     if (this.credentialsHandle != null)
     {
         this.credentialsHandle.Close();
         this.credentialsHandle = null;
     }
 }
 public override void OnOpening()
 {
     base.OnOpening();
     if (this.credentialsHandle == null)
     {
         this.credentialsHandle = System.ServiceModel.Security.SecurityUtils.GetCredentialsHandle("Negotiate", this.serverCredential, true, new string[0]);
     }
 }
 public SpnegoTokenProvider(System.IdentityModel.SafeFreeCredentials credentialsHandle, SecurityBindingElement securityBindingElement) : base(securityBindingElement)
 {
     this.allowedImpersonationLevel = TokenImpersonationLevel.Identification;
     this.identityVerifier = System.ServiceModel.Security.IdentityVerifier.CreateDefault();
     this.allowNtlm = true;
     this.authenticateServer = true;
     this.interactiveNegoExLogonEnabled = true;
     this.credentialsHandle = credentialsHandle;
 }
 public override void OnOpening()
 {
     base.OnOpening();
     if (this.credentialsHandle == null)
     {
         this.credentialsHandle    = System.ServiceModel.Security.SecurityUtils.GetCredentialsHandle("Kerberos", this.innerProvider.NetworkCredential, false, new string[0]);
         this.ownCredentialsHandle = true;
     }
 }
 public SpnegoTokenProvider(System.IdentityModel.SafeFreeCredentials credentialsHandle, SecurityBindingElement securityBindingElement) : base(securityBindingElement)
 {
     this.allowedImpersonationLevel = TokenImpersonationLevel.Identification;
     this.identityVerifier          = System.ServiceModel.Security.IdentityVerifier.CreateDefault();
     this.allowNtlm                     = true;
     this.authenticateServer            = true;
     this.interactiveNegoExLogonEnabled = true;
     this.credentialsHandle             = credentialsHandle;
 }
 public static int AcquireCredentialsHandle(string package, CredentialUse intent, ref IntPtr ppAuthIdentity, out SafeFreeCredentials outCredential)
 {
     int num = -1;
     outCredential = new SafeFreeCredentials();
     RuntimeHelpers.PrepareConstrainedRegions();
     try
     {
     }
     finally
     {
         long num2;
         num = AcquireCredentialsHandleW(null, package, (int) intent, null, ppAuthIdentity, null, null, ref outCredential._handle, out num2);
         if (num != 0)
         {
             outCredential.SetHandleAsInvalid();
         }
     }
     return num;
 }
 private WindowsSspiNegotiation(bool isServer, string package, SafeFreeCredentials credentialsHandle, TokenImpersonationLevel impersonationLevel, string servicePrincipalName, bool doMutualAuth, bool interactiveLogonEnabled, bool ntlmEnabled)
 {
     this.syncObject = new object();
     this.interactiveNegoLogonEnabled = true;
     this.saveClientCredentialsOnSspiUi = true;
     this.tokenSize = SspiWrapper.GetVerifyPackageInfo(package).MaxToken;
     this.isServer = isServer;
     this.servicePrincipalName = servicePrincipalName;
     this.securityContext = null;
     if (isServer)
     {
         this.impersonationLevel = TokenImpersonationLevel.Delegation;
         this.doMutualAuth = false;
     }
     else
     {
         this.impersonationLevel = impersonationLevel;
         this.doMutualAuth = doMutualAuth;
         this.interactiveNegoLogonEnabled = interactiveLogonEnabled;
         this.clientPackageName = package;
         this.allowNtlm = ntlmEnabled;
     }
     this.credentialsHandle = credentialsHandle;
 }
Exemple #10
0
        public static int AcquireCredentialsHandle(string package, CredentialUse intent, ref IntPtr ppAuthIdentity, out SafeFreeCredentials outCredential)
        {
            int num = -1;

            outCredential = new SafeFreeCredentials();
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
            }
            finally
            {
                long num2;
                num = AcquireCredentialsHandleW(null, package, (int)intent, null, ppAuthIdentity, null, null, ref outCredential._handle, out num2);
                if (num != 0)
                {
                    outCredential.SetHandleAsInvalid();
                }
            }
            return(num);
        }
 public override void OnOpening()
 {
     bool flag = System.ServiceModel.Security.SecurityUtils.IsOsGreaterThanXP();
     base.OnOpening();
     if (this.credentialsHandle == null)
     {
         string str;
         if (!this.allowNtlm && !flag)
         {
             str = "Kerberos";
         }
         else
         {
             str = "Negotiate";
         }
         NetworkCredential credential = null;
         if (this.clientCredential != null)
         {
             credential = this.clientCredential.GetCredential(base.TargetAddress.Uri, str);
         }
         if (!this.allowNtlm && flag)
         {
             this.credentialsHandle = System.ServiceModel.Security.SecurityUtils.GetCredentialsHandle(str, credential, false, new string[] { "!NTLM" });
         }
         else
         {
             this.credentialsHandle = System.ServiceModel.Security.SecurityUtils.GetCredentialsHandle(str, credential, false, new string[0]);
         }
         this.ownCredentialsHandle = true;
     }
 }
Exemple #12
0
        public static unsafe int AcquireCredentialsHandle(string package, CredentialUse intent, ref SecureCredential authdata, out SafeFreeCredentials outCredential)
        {
            int    num = -1;
            IntPtr certContextArray = authdata.certContextArray;

            try
            {
                IntPtr ptr2 = new IntPtr((void *)&certContextArray);
                if (certContextArray != IntPtr.Zero)
                {
                    authdata.certContextArray = ptr2;
                }
                outCredential = new SafeFreeCredentials();
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                }
                finally
                {
                    long num2;
                    num = AcquireCredentialsHandleW(null, package, (int)intent, null, ref authdata, null, null, ref outCredential._handle, out num2);
                    if (num != 0)
                    {
                        outCredential.SetHandleAsInvalid();
                    }
                }
            }
            finally
            {
                authdata.certContextArray = certContextArray;
            }
            return(num);
        }
 internal KerberosRequestorSecurityToken(string servicePrincipalName, TokenImpersonationLevel tokenImpersonationLevel, NetworkCredential networkCredential, string id, System.IdentityModel.SafeFreeCredentials credentialsHandle, ChannelBinding channelBinding)
 {
     if (servicePrincipalName == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("servicePrincipalName");
     }
     if ((tokenImpersonationLevel != TokenImpersonationLevel.Identification) && (tokenImpersonationLevel != TokenImpersonationLevel.Impersonation))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("tokenImpersonationLevel", System.IdentityModel.SR.GetString("ImpersonationLevelNotSupported", new object[] { tokenImpersonationLevel })));
     }
     if (id == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("id");
     }
     this.servicePrincipalName = servicePrincipalName;
     if (((networkCredential != null) && (networkCredential != CredentialCache.DefaultNetworkCredentials)) && string.IsNullOrEmpty(networkCredential.UserName))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("ProvidedNetworkCredentialsForKerberosHasInvalidUserName"));
     }
     this.id = id;
     try
     {
         this.Initialize(tokenImpersonationLevel, networkCredential, credentialsHandle, channelBinding);
     }
     catch (Win32Exception exception)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(System.IdentityModel.SR.GetString("UnableToCreateKerberosCredentials"), exception));
     }
     catch (SecurityTokenException exception2)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(System.IdentityModel.SR.GetString("UnableToCreateKerberosCredentials"), exception2));
     }
 }
 internal static int AcceptSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext refContext, SspiContextFlags inFlags, Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref SspiContextFlags outFlags)
 {
     return SafeDeleteContext.AcceptSecurityContext(credential, ref refContext, inFlags, datarep, null, inputBuffers, outputBuffer, ref outFlags);
 }
 private void FreeCredentialsHandle()
 {
     if (this.credentialsHandle != null)
     {
         this.credentialsHandle.Close();
         this.credentialsHandle = null;
     }
 }
        // 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.
        // This method is run as non-interruptible.
        static unsafe int MustRunAcceptSecurityContext(
            SafeFreeCredentials inCredentials,
            void* inContextPtr,
            SecurityBufferDescriptor inputBuffer,
            SspiContextFlags inFlags,
            Endianness endianness,
            SafeDeleteContext outContext,
            SecurityBufferDescriptor outputBuffer,
            ref SspiContextFlags outFlags,
            SafeFreeContextBuffer handleTemplate)
        {
            int errorCode = -1;
            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 (System.Runtime.Fx.IsFatal(e))
                    throw;
                
                if (b1)
                {
                    inCredentials.DangerousRelease();
                    b1 = false;
                }
                if (b2)
                {
                    outContext.DangerousRelease();
                    b2 = false;
                }
                if (!(e is ObjectDisposedException))
                    throw;
            }
            finally
            {
                long timeStamp;
                if (!b1)
                {
                    // caller should retry
                    inCredentials = null;
                }
                else if (b1 && b2)
                {

                    SSPIHandle credentialHandle = inCredentials._handle;
                    // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. 
#pragma warning suppress 56523 // This API does not set Win32 Last Error.
                    errorCode = 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;
        }
Exemple #17
0
        private static unsafe int MustRunInitializeSecurityContext(SafeFreeCredentials inCredentials, void *inContextPtr, byte *targetName, SspiContextFlags inFlags, Endianness endianness, SecurityBufferDescriptor inputBuffer, SafeDeleteContext outContext, SecurityBufferDescriptor outputBuffer, ref SspiContextFlags attributes, SafeFreeContextBuffer handleTemplate)
        {
            int  num     = -1;
            bool success = false;
            bool flag2   = false;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                inCredentials.DangerousAddRef(ref success);
                outContext.DangerousAddRef(ref flag2);
            }
            catch (Exception exception)
            {
                if (success)
                {
                    inCredentials.DangerousRelease();
                    success = false;
                }
                if (flag2)
                {
                    outContext.DangerousRelease();
                    flag2 = false;
                }
                if (!(exception is ObjectDisposedException))
                {
                    throw;
                }
            }
            finally
            {
                if (!success)
                {
                    inCredentials = null;
                }
                else if (success && flag2)
                {
                    long num2;
                    num = InitializeSecurityContextW(ref inCredentials._handle, inContextPtr, targetName, inFlags, 0, endianness, inputBuffer, 0, ref outContext._handle, outputBuffer, ref attributes, out num2);
                    if ((outContext._EffectiveCredential != inCredentials) && ((num & 0x80000000L) == 0L))
                    {
                        if (outContext._EffectiveCredential != null)
                        {
                            outContext._EffectiveCredential.DangerousRelease();
                        }
                        outContext._EffectiveCredential = inCredentials;
                    }
                    else
                    {
                        inCredentials.DangerousRelease();
                    }
                    outContext.DangerousRelease();
                    if (handleTemplate != null)
                    {
                        handleTemplate.Set(outputBuffer.UnmanagedPointer.token);
                        if (handleTemplate.IsInvalid)
                        {
                            handleTemplate.SetHandleAsInvalid();
                        }
                    }
                }
                if ((inContextPtr == null) && ((num & 0x80000000L) != 0L))
                {
                    outContext._handle.SetToInvalid();
                }
            }
            return(num);
        }
Exemple #18
0
        internal static unsafe int InitializeSecurityContext(SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, string targetName, SspiContextFlags inFlags, Endianness endianness, SecurityBuffer inSecBuffer, SecurityBuffer[] inSecBuffers, SecurityBuffer outSecBuffer, ref SspiContextFlags outFlags)
        {
            if (inCredentials == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("inCredentials");
            }
            SecurityBufferDescriptor inputBuffer = null;

            if (inSecBuffer != null)
            {
                inputBuffer = new SecurityBufferDescriptor(1);
            }
            else if (inSecBuffers != null)
            {
                inputBuffer = new SecurityBufferDescriptor(inSecBuffers.Length);
            }
            SecurityBufferDescriptor outputBuffer = new SecurityBufferDescriptor(1);
            bool       flag   = (inFlags & SspiContextFlags.AllocateMemory) != SspiContextFlags.Zero;
            int        num    = -1;
            SSPIHandle handle = new SSPIHandle();

            if (refContext != null)
            {
                handle = refContext._handle;
            }
            GCHandle[]            handleArray    = null;
            GCHandle              handle2        = new GCHandle();
            SafeFreeContextBuffer handleTemplate = null;

            try
            {
                handle2 = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned);
                SecurityBufferStruct[] structArray = new SecurityBufferStruct[(inputBuffer == null) ? 1 : inputBuffer.Count];
                try
                {
                    SecurityBufferStruct[] structArray3;
                    if (((structArray3 = structArray) == null) || (structArray3.Length == 0))
                    {
                        ptrRef = null;
                        goto Label_00A9;
                    }
                    fixed(IntPtr *ptrRef = structArray3)
                    {
Label_00A9:
                        if (inputBuffer != null)
                        {
                            inputBuffer.UnmanagedPointer = (void *)ptrRef;
                            handleArray = new GCHandle[inputBuffer.Count];
                            for (int i = 0; i < inputBuffer.Count; i++)
                            {
                                SecurityBuffer buffer2 = (inSecBuffer != null) ? inSecBuffer : inSecBuffers[i];
                                if (buffer2 != null)
                                {
                                    structArray[i].count = buffer2.size;
                                    structArray[i].type  = buffer2.type;
                                    if (buffer2.unmanagedToken != null)
                                    {
                                        structArray[i].token = buffer2.unmanagedToken.DangerousGetHandle();
                                    }
                                    else if ((buffer2.token == null) || (buffer2.token.Length == 0))
                                    {
                                        structArray[i].token = IntPtr.Zero;
                                    }
                                    else
                                    {
                                        handleArray[i]       = GCHandle.Alloc(buffer2.token, GCHandleType.Pinned);
                                        structArray[i].token = Marshal.UnsafeAddrOfPinnedArrayElement(buffer2.token, buffer2.offset);
                                    }
                                }
                            }
                        }
                        SecurityBufferStruct[] structArray2 = new SecurityBufferStruct[1];
                        try
                        {
                            SecurityBufferStruct[] structArray4;
                            if (((structArray4 = structArray2) == null) || (structArray4.Length == 0))
                            {
                                ptrRef2 = null;
                                goto Label_01CF;
                            }
                            fixed(IntPtr *ptrRef2 = structArray4)
                            {
Label_01CF:
                                outputBuffer.UnmanagedPointer = (void *)ptrRef2;
                                structArray2[0].count         = outSecBuffer.size;
                                structArray2[0].type          = outSecBuffer.type;
                                if ((outSecBuffer.token == null) || (outSecBuffer.token.Length == 0))
                                {
                                    structArray2[0].token = IntPtr.Zero;
                                }
                                else
                                {
                                    structArray2[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset);
                                }
                                if (flag)
                                {
                                    handleTemplate = SafeFreeContextBuffer.CreateEmptyHandle();
                                }
                                if ((refContext == null) || refContext.IsInvalid)
                                {
                                    refContext = new SafeDeleteContext();
                                }
                                if ((targetName == null) || (targetName.Length == 0))
                                {
                                    targetName = " ";
                                }
                                fixed(char *str = ((char *)targetName))
                                {
                                    char *chPtr = str;

                                    num = MustRunInitializeSecurityContext(inCredentials, handle.IsZero ? null : ((void *)&handle), (targetName == " ") ? null : ((byte *)chPtr), inFlags, endianness, inputBuffer, refContext, outputBuffer, ref outFlags, handleTemplate);
                                }
                                outSecBuffer.size = structArray2[0].count;
                                outSecBuffer.type = structArray2[0].type;
                                if (outSecBuffer.size > 0)
                                {
                                    outSecBuffer.token = DiagnosticUtility.Utility.AllocateByteArray(outSecBuffer.size);
                                    Marshal.Copy(structArray2[0].token, outSecBuffer.token, 0, outSecBuffer.size);
                                    return(num);
                                }
                                outSecBuffer.token = null;
                                return(num);
                            }
                        }
                        finally
                        {
                            ptrRef2 = null;
                        }
                        return(num);
                    }
                }
                finally
                {
                    ptrRef = null;
                }
            }
            finally
            {
                if (handleArray != null)
                {
                    for (int j = 0; j < handleArray.Length; j++)
                    {
                        if (handleArray[j].IsAllocated)
                        {
                            handleArray[j].Free();
                        }
                    }
                }
                if (handle2.IsAllocated)
                {
                    handle2.Free();
                }
                if (handleTemplate != null)
                {
                    handleTemplate.Close();
                }
            }
            return(num);
        }
 internal WindowsSspiNegotiation(string package, SafeFreeCredentials credentialsHandle, TokenImpersonationLevel impersonationLevel, string servicePrincipalName, bool doMutualAuth, bool interactiveLogonEnabled, bool ntlmEnabled) : this(false, package, credentialsHandle, impersonationLevel, servicePrincipalName, doMutualAuth, interactiveLogonEnabled, ntlmEnabled)
 {
 }
 internal WindowsSspiNegotiation(string package, SafeFreeCredentials credentialsHandle, string defaultServiceBinding) : this(true, package, credentialsHandle, TokenImpersonationLevel.Delegation, defaultServiceBinding, false, false, true)
 {
 }
 public byte[] GetOutgoingBlob(byte[] incomingBlob, ChannelBinding channelbinding, ExtendedProtectionPolicy protectionPolicy)
 {
     this.ThrowIfDisposed();
     int error = 0;
     SspiContextFlags inFlags = SspiContextFlags.Confidentiality | SspiContextFlags.SequenceDetect | SspiContextFlags.ReplayDetect;
     if (this.doMutualAuth)
     {
         inFlags |= SspiContextFlags.MutualAuth;
     }
     if (this.impersonationLevel == TokenImpersonationLevel.Delegation)
     {
         inFlags |= SspiContextFlags.Delegate;
     }
     else if (!this.isServer && (this.impersonationLevel == TokenImpersonationLevel.Identification))
     {
         inFlags |= SspiContextFlags.InitIdentify;
     }
     else if (!this.isServer && (this.impersonationLevel == TokenImpersonationLevel.Anonymous))
     {
         inFlags |= SspiContextFlags.InitAnonymous;
     }
     ExtendedProtectionPolicyHelper helper = new ExtendedProtectionPolicyHelper(channelbinding, protectionPolicy);
     if (this.isServer)
     {
         if (((helper.PolicyEnforcement == PolicyEnforcement.Always) && (helper.ChannelBinding == null)) && (helper.ProtectionScenario != ProtectionScenario.TrustedProxy))
         {
             throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.ServiceModel.SR.GetString("SecurityChannelBindingMissing")));
         }
         if (helper.PolicyEnforcement == PolicyEnforcement.WhenSupported)
         {
             inFlags |= SspiContextFlags.ChannelBindingAllowMissingBindings;
         }
         if (helper.ProtectionScenario == ProtectionScenario.TrustedProxy)
         {
             inFlags |= SspiContextFlags.ChannelBindingProxyBindings;
         }
     }
     List<SecurityBuffer> list = new List<SecurityBuffer>(2);
     if (incomingBlob != null)
     {
         list.Add(new SecurityBuffer(incomingBlob, BufferType.Token));
     }
     if (this.isServer)
     {
         if (helper.ShouldAddChannelBindingToASC())
         {
             list.Add(new SecurityBuffer(helper.ChannelBinding));
         }
     }
     else if (helper.ChannelBinding != null)
     {
         list.Add(new SecurityBuffer(helper.ChannelBinding));
     }
     SecurityBuffer[] inputBuffers = null;
     if (list.Count > 0)
     {
         inputBuffers = list.ToArray();
     }
     SecurityBuffer outputBuffer = new SecurityBuffer(this.tokenSize, BufferType.Token);
     if (!this.isServer)
     {
         error = SspiWrapper.InitializeSecurityContext(this.credentialsHandle, ref this.securityContext, this.servicePrincipalName, inFlags, Endianness.Network, inputBuffers, outputBuffer, ref this.contextFlags);
     }
     else
     {
         bool flag = this.securityContext == null;
         SspiContextFlags contextFlags = this.contextFlags;
         error = SspiWrapper.AcceptSecurityContext(this.credentialsHandle, ref this.securityContext, inFlags, Endianness.Network, inputBuffers, outputBuffer, ref this.contextFlags);
         if ((error == -2146893048) && !flag)
         {
             this.contextFlags = contextFlags;
             this.CloseContext();
             error = SspiWrapper.AcceptSecurityContext(this.credentialsHandle, ref this.securityContext, inFlags, Endianness.Network, inputBuffers, outputBuffer, ref this.contextFlags);
         }
     }
     if ((error & -2147483648) != 0)
     {
         if (((!this.isServer && this.interactiveNegoLogonEnabled) && (System.ServiceModel.Security.SecurityUtils.IsOSGreaterThanOrEqualToWin7() && SspiWrapper.IsSspiPromptingNeeded((uint) error))) && SspiWrapper.IsNegotiateExPackagePresent())
         {
             if (this.MaxPromptAttempts >= 1)
             {
                 throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, System.ServiceModel.SR.GetString("InvalidClientCredentials")));
             }
             IntPtr zero = IntPtr.Zero;
             uint num2 = SspiWrapper.SspiPromptForCredential(this.servicePrincipalName, this.clientPackageName, out zero, ref this.saveClientCredentialsOnSspiUi);
             if (num2 == 0)
             {
                 IntPtr ppNewAuthIdentity = IntPtr.Zero;
                 if (!this.allowNtlm)
                 {
                     UnsafeNativeMethods.SspiExcludePackage(zero, "NTLM", out ppNewAuthIdentity);
                 }
                 else
                 {
                     ppNewAuthIdentity = zero;
                 }
                 this.credentialsHandle = SspiWrapper.AcquireCredentialsHandle(this.clientPackageName, CredentialUse.Outbound, ref ppNewAuthIdentity);
                 if (IntPtr.Zero != ppNewAuthIdentity)
                 {
                     UnsafeNativeMethods.SspiFreeAuthIdentity(ppNewAuthIdentity);
                 }
                 this.CloseContext();
                 this.MaxPromptAttempts++;
                 return this.GetOutgoingBlob(null, channelbinding, protectionPolicy);
             }
             if (IntPtr.Zero != zero)
             {
                 UnsafeNativeMethods.SspiFreeAuthIdentity(zero);
             }
             this.CloseContext();
             this.isCompleted = true;
             throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception((int) num2, System.ServiceModel.SR.GetString("SspiErrorOrInvalidClientCredentials")));
         }
         this.CloseContext();
         this.isCompleted = true;
         if (this.isServer || (((error != -2146893042) && (error != -2146893053)) && (error != -2146893022)))
         {
             throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, System.ServiceModel.SR.GetString("InvalidSspiNegotiation")));
         }
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, System.ServiceModel.SR.GetString("IncorrectSpnOrUpnSpecified", new object[] { this.servicePrincipalName })));
     }
     if (System.ServiceModel.DiagnosticUtility.ShouldTraceInformation)
     {
         if (this.isServer)
         {
             SecurityTraceRecordHelper.TraceServiceOutgoingSpnego(this);
         }
         else
         {
             SecurityTraceRecordHelper.TraceClientOutgoingSpnego(this);
         }
     }
     if (error == 0)
     {
         this.isCompleted = true;
         if ((this.isServer && ((this.contextFlags & SspiContextFlags.AcceptAnonymous) == SspiContextFlags.Zero)) && ((string.Compare(this.ProtocolName, "Kerberos", StringComparison.OrdinalIgnoreCase) != 0) && helper.ShouldCheckServiceBinding))
         {
             helper.CheckServiceBinding(this.securityContext, this.servicePrincipalName);
         }
     }
     return outputBuffer.token;
 }
 public override void OnOpening()
 {
     base.OnOpening();
     if (this.credentialsHandle == null)
     {
         this.credentialsHandle = System.ServiceModel.Security.SecurityUtils.GetCredentialsHandle("Kerberos", this.innerProvider.NetworkCredential, false, new string[0]);
         this.ownCredentialsHandle = true;
     }
 }
        public static unsafe int AcquireCredentialsHandle(
            string package,
            CredentialUse intent,
            ref SecureCredential authdata,
            out SafeFreeCredentials outCredential)
        {
            int errorCode = -1;
            long timeStamp;

            // If there is a certificate, wrap it into an array
            IntPtr copiedPtr = authdata.certContextArray;
            try
            {
                IntPtr certArrayPtr = new IntPtr(&copiedPtr);
                if (copiedPtr != IntPtr.Zero)
                {
                    authdata.certContextArray = certArrayPtr;
                }

                outCredential = new SafeFreeCredentials();
                RuntimeHelpers.PrepareConstrainedRegions();
                try { }
                finally
                {
                    // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. 
#pragma warning suppress 56523 // The API does not set Win32 Last Error. It returns a error code.
                    errorCode = AcquireCredentialsHandleW(
                                    null,
                                    package,
                                    (int)intent,
                                    null,
                                    ref authdata,
                                    null,
                                    null,
                                    ref outCredential._handle,
                                    out timeStamp
                                    );
                    if (errorCode != 0)
                    {
                        outCredential.SetHandleAsInvalid();
                    }
                }
            }
            finally
            {
                authdata.certContextArray = copiedPtr;
            }

            return errorCode;
        }
 internal static int AcceptSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext refContext, SspiContextFlags inFlags, Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref SspiContextFlags outFlags)
 {
     return(SafeDeleteContext.AcceptSecurityContext(credential, ref refContext, inFlags, datarep, null, inputBuffers, outputBuffer, ref outFlags));
 }
        //-------------------------------------------------------------------
        internal static unsafe int AcceptSecurityContext(
            SafeFreeCredentials inCredentials,
            ref SafeDeleteContext refContext,
            SspiContextFlags inFlags,
            Endianness endianness,
            SecurityBuffer inSecBuffer,
            SecurityBuffer[] inSecBuffers,
            SecurityBuffer outSecBuffer,
            ref SspiContextFlags outFlags)
        {

            if (inCredentials == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("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 & SspiContextFlags.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);
                                }
                            }
                        }
                    }
                    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();
                        }

                        if (refContext == null || refContext.IsInvalid)
                        {
                            refContext = new SafeDeleteContext();
                        }
                        errorCode = MustRunAcceptSecurityContext(
                            inCredentials,
                            contextHandle.IsZero ? null : &contextHandle,
                            inSecurityBufferDescriptor,
                            inFlags,
                            endianness,
                            refContext,
                            outSecurityBufferDescriptor,
                            ref outFlags,
                            outFreeContextBuffer
                            );

                        // 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 = DiagnosticUtility.Utility.AllocateByteArray(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();
                }
            }

            return errorCode;
        }
 public KerberosSecurityTokenProviderWrapper(KerberosSecurityTokenProvider innerProvider, System.IdentityModel.SafeFreeCredentials credentialsHandle)
 {
     this.innerProvider = innerProvider;
     this.credentialsHandle = credentialsHandle;
 }
        //This method should never be called for this type
        //public new IntPtr DangerousGetHandle()
        //{
        //    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
        //}

        public static unsafe int AcquireCredentialsHandle(
            string package,
            CredentialUse intent,
            ref AuthIdentityEx authdata,
            out SafeFreeCredentials outCredential)
        {
            int errorCode = -1;
            long timeStamp;

            outCredential = new SafeFreeCredentials();
            RuntimeHelpers.PrepareConstrainedRegions();
            try { }
            finally
            {
                // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. 
#pragma warning suppress 56523 // The API does not set Win32 Last Error. It returns a error code.
                errorCode = AcquireCredentialsHandleW(
                    null,
                    package,
                    (int)intent,
                    null,
                    ref authdata,
                    null,
                    null,
                    ref outCredential._handle,
                    out timeStamp
                    );
                if (errorCode != 0)
                {
                    outCredential.SetHandleAsInvalid();
                }
            }
            return errorCode;
        }
 public SspiIssuanceChannelParameter(bool getTokenOnOpen, SafeFreeCredentials credentialsHandle)
 {
     this.getTokenOnOpen = getTokenOnOpen;
     this.credentialsHandle = credentialsHandle;
 }
 public override void OnOpening()
 {
     base.OnOpening();
     if (this.credentialsHandle == null)
     {
         this.credentialsHandle = System.ServiceModel.Security.SecurityUtils.GetCredentialsHandle("Kerberos", null, true, new string[0]);
     }
 }
 private void AcquireServerCredentials()
 {
     SecureCredential secureCredential = new SecureCredential(SecureCredential.CurrentVersion, this.serverCertificate, SecureCredential.Flags.Zero, this.protocolFlags);
     this.credentialsHandle = SspiWrapper.AcquireCredentialsHandle(
         SecurityPackage,
         CredentialUse.Inbound,
         secureCredential
         );
 }
 internal static int InitializeSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, SspiContextFlags inFlags, Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref SspiContextFlags outFlags)
 {
     return SafeDeleteContext.InitializeSecurityContext(credential, ref context, targetName, inFlags, datarep, null, inputBuffers, outputBuffer, ref outFlags);
 }
 private static unsafe int MustRunInitializeSecurityContext(SafeFreeCredentials inCredentials, void* inContextPtr, byte* targetName, SspiContextFlags inFlags, Endianness endianness, SecurityBufferDescriptor inputBuffer, SafeDeleteContext outContext, SecurityBufferDescriptor outputBuffer, ref SspiContextFlags attributes, SafeFreeContextBuffer handleTemplate)
 {
     int num = -1;
     bool success = false;
     bool flag2 = false;
     RuntimeHelpers.PrepareConstrainedRegions();
     try
     {
         inCredentials.DangerousAddRef(ref success);
         outContext.DangerousAddRef(ref flag2);
     }
     catch (Exception exception)
     {
         if (success)
         {
             inCredentials.DangerousRelease();
             success = false;
         }
         if (flag2)
         {
             outContext.DangerousRelease();
             flag2 = false;
         }
         if (!(exception is ObjectDisposedException))
         {
             throw;
         }
     }
     finally
     {
         if (!success)
         {
             inCredentials = null;
         }
         else if (success && flag2)
         {
             long num2;
             num = InitializeSecurityContextW(ref inCredentials._handle, inContextPtr, targetName, inFlags, 0, endianness, inputBuffer, 0, ref outContext._handle, outputBuffer, ref attributes, out num2);
             if ((outContext._EffectiveCredential != inCredentials) && ((num & 0x80000000L) == 0L))
             {
                 if (outContext._EffectiveCredential != null)
                 {
                     outContext._EffectiveCredential.DangerousRelease();
                 }
                 outContext._EffectiveCredential = inCredentials;
             }
             else
             {
                 inCredentials.DangerousRelease();
             }
             outContext.DangerousRelease();
             if (handleTemplate != null)
             {
                 handleTemplate.Set(outputBuffer.UnmanagedPointer.token);
                 if (handleTemplate.IsInvalid)
                 {
                     handleTemplate.SetHandleAsInvalid();
                 }
             }
         }
         if ((inContextPtr == null) && ((num & 0x80000000L) != 0L))
         {
             outContext._handle.SetToInvalid();
         }
     }
     return num;
 }
        private void Initialize(TokenImpersonationLevel tokenImpersonationLevel, NetworkCredential networkCredential, System.IdentityModel.SafeFreeCredentials credentialsHandle, ChannelBinding channelBinding)
        {
            bool flag = false;

            System.IdentityModel.SafeDeleteContext context = null;
            try
            {
                if (credentialsHandle == null)
                {
                    if ((networkCredential == null) || (networkCredential == CredentialCache.DefaultNetworkCredentials))
                    {
                        credentialsHandle = SspiWrapper.AcquireDefaultCredential("Kerberos", System.IdentityModel.CredentialUse.Outbound, new string[0]);
                    }
                    else
                    {
                        AuthIdentityEx authdata = new AuthIdentityEx(networkCredential.UserName, networkCredential.Password, networkCredential.Domain, new string[0]);
                        credentialsHandle = SspiWrapper.AcquireCredentialsHandle("Kerberos", System.IdentityModel.CredentialUse.Outbound, ref authdata);
                    }
                    flag = true;
                }
                SspiContextFlags inFlags = SspiContextFlags.AllocateMemory | SspiContextFlags.Confidentiality | SspiContextFlags.SequenceDetect | SspiContextFlags.ReplayDetect;
                if (tokenImpersonationLevel == TokenImpersonationLevel.Identification)
                {
                    inFlags |= SspiContextFlags.InitIdentify;
                }
                SspiContextFlags zero = SspiContextFlags.Zero;
                System.IdentityModel.SecurityBuffer inputBuffer = null;
                if (channelBinding != null)
                {
                    inputBuffer = new System.IdentityModel.SecurityBuffer(channelBinding);
                }
                System.IdentityModel.SecurityBuffer outputBuffer = new System.IdentityModel.SecurityBuffer(0, System.IdentityModel.BufferType.Token);
                int error = SspiWrapper.InitializeSecurityContext(credentialsHandle, ref context, this.servicePrincipalName, inFlags, System.IdentityModel.Endianness.Native, inputBuffer, outputBuffer, ref zero);
                switch (error)
                {
                case 0:
                    break;

                case 0x90312:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("KerberosMultilegsNotSupported"), new Win32Exception(error)));

                default:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("FailInitializeSecurityContext"), new Win32Exception(error)));
                }
                this.apreq = outputBuffer.token;
                LifeSpan span = (LifeSpan)SspiWrapper.QueryContextAttributes(context, System.IdentityModel.ContextAttribute.Lifespan);
                this.effectiveTime  = span.EffectiveTimeUtc;
                this.expirationTime = span.ExpiryTimeUtc;
                SecuritySessionKeyClass class2 = (SecuritySessionKeyClass)SspiWrapper.QueryContextAttributes(context, System.IdentityModel.ContextAttribute.SessionKey);
                this.symmetricSecurityKey = new InMemorySymmetricSecurityKey(class2.SessionKey);
            }
            finally
            {
                if (context != null)
                {
                    context.Close();
                }
                if (flag && (credentialsHandle != null))
                {
                    credentialsHandle.Close();
                }
            }
        }
 public KerberosSecurityTokenProviderWrapper(KerberosSecurityTokenProvider innerProvider, System.IdentityModel.SafeFreeCredentials credentialsHandle)
 {
     this.innerProvider     = innerProvider;
     this.credentialsHandle = credentialsHandle;
 }
 internal static int InitializeSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, SspiContextFlags inFlags, Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref SspiContextFlags outFlags)
 {
     return(SafeDeleteContext.InitializeSecurityContext(credential, ref context, targetName, inFlags, datarep, null, inputBuffers, outputBuffer, ref outFlags));
 }
 public SpnegoTokenProvider(System.IdentityModel.SafeFreeCredentials credentialsHandle) : this(credentialsHandle, null)
 {
 }
 private void AcquireServerCredentials()
 {
     SecureCredential scc = new SecureCredential(4, this.serverCertificate, SecureCredential.Flags.Zero, this.protocolFlags);
     this.credentialsHandle = SspiWrapper.AcquireCredentialsHandle("Microsoft Unified Security Protocol Provider", CredentialUse.Inbound, scc);
 }
 private void Dispose(bool disposing)
 {
     lock (this.syncObject)
     {
         if (!this.disposed)
         {
             this.disposed = true;
             if (disposing)
             {
                 if (this.securityContext != null)
                 {
                     this.securityContext.Close();
                     this.securityContext = null;
                 }
                 if (this.credentialsHandle != null)
                 {
                     this.credentialsHandle.Close();
                     this.credentialsHandle = null;
                 }
             }
             this.connectionInfo = null;
             this.destination = null;
             this.streamSizes = null;
         }
     }
 }
 private void AcquireDummyCredentials()
 {
     SecureCredential secureCredential = new SecureCredential(SecureCredential.CurrentVersion, null, SecureCredential.Flags.ValidateManual | SecureCredential.Flags.NoDefaultCred, this.protocolFlags);
     this.credentialsHandle = SspiWrapper.AcquireCredentialsHandle(SecurityPackage, CredentialUse.Outbound, secureCredential);
 }
 private void AcquireDummyCredentials()
 {
     SecureCredential scc = new SecureCredential(4, null, SecureCredential.Flags.NoDefaultCred | SecureCredential.Flags.ValidateManual, this.protocolFlags);
     this.credentialsHandle = SspiWrapper.AcquireCredentialsHandle("Microsoft Unified Security Protocol Provider", CredentialUse.Outbound, scc);
 }
        private void Dispose(bool disposing)
        {
            lock (this.syncObject)
            {
                if (this.disposed == false)
                {
                    this.disposed = true;
                    if (disposing)
                    {
                        if (this.securityContext != null)
                        {
                            this.securityContext.Close();
                            this.securityContext = null;
                        }
                        if (this.credentialsHandle != null)
                        {
                            this.credentialsHandle.Close();
                            this.credentialsHandle = null;
                        }
                    }

                    // set to null any references that aren't finalizable
                    this.connectionInfo = null;
                    this.destination = null;
                    this.streamSizes = null;
                }
            }
        }
 internal static unsafe int InitializeSecurityContext(SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, string targetName, SspiContextFlags inFlags, Endianness endianness, SecurityBuffer inSecBuffer, SecurityBuffer[] inSecBuffers, SecurityBuffer outSecBuffer, ref SspiContextFlags outFlags)
 {
     if (inCredentials == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("inCredentials");
     }
     SecurityBufferDescriptor inputBuffer = null;
     if (inSecBuffer != null)
     {
         inputBuffer = new SecurityBufferDescriptor(1);
     }
     else if (inSecBuffers != null)
     {
         inputBuffer = new SecurityBufferDescriptor(inSecBuffers.Length);
     }
     SecurityBufferDescriptor outputBuffer = new SecurityBufferDescriptor(1);
     bool flag = (inFlags & SspiContextFlags.AllocateMemory) != SspiContextFlags.Zero;
     int num = -1;
     SSPIHandle handle = new SSPIHandle();
     if (refContext != null)
     {
         handle = refContext._handle;
     }
     GCHandle[] handleArray = null;
     GCHandle handle2 = new GCHandle();
     SafeFreeContextBuffer handleTemplate = null;
     try
     {
         handle2 = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned);
         SecurityBufferStruct[] structArray = new SecurityBufferStruct[(inputBuffer == null) ? 1 : inputBuffer.Count];
         try
         {
             SecurityBufferStruct[] structArray3;
             if (((structArray3 = structArray) == null) || (structArray3.Length == 0))
             {
                 ptrRef = null;
                 goto Label_00A9;
             }
             fixed (IntPtr* ptrRef = structArray3)
             {
             Label_00A9:
                 if (inputBuffer != null)
                 {
                     inputBuffer.UnmanagedPointer = (void*) ptrRef;
                     handleArray = new GCHandle[inputBuffer.Count];
                     for (int i = 0; i < inputBuffer.Count; i++)
                     {
                         SecurityBuffer buffer2 = (inSecBuffer != null) ? inSecBuffer : inSecBuffers[i];
                         if (buffer2 != null)
                         {
                             structArray[i].count = buffer2.size;
                             structArray[i].type = buffer2.type;
                             if (buffer2.unmanagedToken != null)
                             {
                                 structArray[i].token = buffer2.unmanagedToken.DangerousGetHandle();
                             }
                             else if ((buffer2.token == null) || (buffer2.token.Length == 0))
                             {
                                 structArray[i].token = IntPtr.Zero;
                             }
                             else
                             {
                                 handleArray[i] = GCHandle.Alloc(buffer2.token, GCHandleType.Pinned);
                                 structArray[i].token = Marshal.UnsafeAddrOfPinnedArrayElement(buffer2.token, buffer2.offset);
                             }
                         }
                     }
                 }
                 SecurityBufferStruct[] structArray2 = new SecurityBufferStruct[1];
                 try
                 {
                     SecurityBufferStruct[] structArray4;
                     if (((structArray4 = structArray2) == null) || (structArray4.Length == 0))
                     {
                         ptrRef2 = null;
                         goto Label_01CF;
                     }
                     fixed (IntPtr* ptrRef2 = structArray4)
                     {
                     Label_01CF:
                         outputBuffer.UnmanagedPointer = (void*) ptrRef2;
                         structArray2[0].count = outSecBuffer.size;
                         structArray2[0].type = outSecBuffer.type;
                         if ((outSecBuffer.token == null) || (outSecBuffer.token.Length == 0))
                         {
                             structArray2[0].token = IntPtr.Zero;
                         }
                         else
                         {
                             structArray2[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset);
                         }
                         if (flag)
                         {
                             handleTemplate = SafeFreeContextBuffer.CreateEmptyHandle();
                         }
                         if ((refContext == null) || refContext.IsInvalid)
                         {
                             refContext = new SafeDeleteContext();
                         }
                         if ((targetName == null) || (targetName.Length == 0))
                         {
                             targetName = " ";
                         }
                         fixed (char* str = ((char*) targetName))
                         {
                             char* chPtr = str;
                             num = MustRunInitializeSecurityContext(inCredentials, handle.IsZero ? null : ((void*) &handle), (targetName == " ") ? null : ((byte*) chPtr), inFlags, endianness, inputBuffer, refContext, outputBuffer, ref outFlags, handleTemplate);
                         }
                         outSecBuffer.size = structArray2[0].count;
                         outSecBuffer.type = structArray2[0].type;
                         if (outSecBuffer.size > 0)
                         {
                             outSecBuffer.token = DiagnosticUtility.Utility.AllocateByteArray(outSecBuffer.size);
                             Marshal.Copy(structArray2[0].token, outSecBuffer.token, 0, outSecBuffer.size);
                             return num;
                         }
                         outSecBuffer.token = null;
                         return num;
                     }
                 }
                 finally
                 {
                     ptrRef2 = null;
                 }
                 return num;
             }
         }
         finally
         {
             ptrRef = null;
         }
     }
     finally
     {
         if (handleArray != null)
         {
             for (int j = 0; j < handleArray.Length; j++)
             {
                 if (handleArray[j].IsAllocated)
                 {
                     handleArray[j].Free();
                 }
             }
         }
         if (handle2.IsAllocated)
         {
             handle2.Free();
         }
         if (handleTemplate != null)
         {
             handleTemplate.Close();
         }
     }
     return num;
 }