/// <summary>
        /// Safely invokes the native VerifySignature function, making sure that handle ref counting is
        /// performed in a proper CER.
        /// </summary>
        /// <param name="handle"></param>
        /// <param name="qualityOfProtection"></param>
        /// <param name="adapter"></param>
        /// <param name="sequenceNumber"></param>
        /// <returns></returns>
        internal static SecurityStatus SafeVerifySignature(
            SafeContextHandle handle,
            int qualityOfProtection,
            SecureBufferAdapter adapter,
            int sequenceNumber)
        {
            bool           gotRef = false;
            SecurityStatus status = SecurityStatus.InternalError;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                handle.DangerousAddRef(ref gotRef);
            }
            catch (Exception)
            {
                if (gotRef)
                {
                    handle.DangerousRelease();
                    gotRef = false;
                }

                throw;
            }
            finally
            {
                if (gotRef)
                {
                    status = ContextNativeMethods.VerifySignature(
                        ref handle.rawHandle,
                        adapter.Handle,
                        sequenceNumber,
                        qualityOfProtection
                        );

                    handle.DangerousRelease();
                }
            }

            return(status);
        }
Example #2
0
        /// <summary>
        /// Returns the properties of the named package.
        /// </summary>
        /// <param name="packageName">The name of the package.</param>
        /// <returns></returns>
        public static SecPkgInfo GetPackageCapabilities(string packageName)
        {
            SecPkgInfo     info;
            SecurityStatus status = SecurityStatus.InternalError;

            IntPtr rawInfoPtr;

            rawInfoPtr = new IntPtr();
            info       = new SecPkgInfo();

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            { }
            finally
            {
                status = NativeMethods.QuerySecurityPackageInfo(packageName, ref rawInfoPtr);

                if (rawInfoPtr != IntPtr.Zero)
                {
                    try
                    {
                        if (status == SecurityStatus.OK)
                        {
                            // This performs allocations as it makes room for the strings contained in the SecPkgInfo class.
                            Marshal.PtrToStructure(rawInfoPtr, info);
                        }
                    }
                    finally
                    {
                        NativeMethods.FreeContextBuffer(rawInfoPtr);
                    }
                }
            }

            if (status != SecurityStatus.OK)
            {
                throw new SSPIException("Failed to query security package provider details", status);
            }

            return(info);
        }
Example #3
0
        /// <summary>
        /// Queries the security package's expections regarding message/token/signature/padding buffer sizes.
        /// </summary>
        /// <returns></returns>
        private SecPkgContext_Sizes QueryBufferSizes()
        {
            SecPkgContext_Sizes sizes  = new SecPkgContext_Sizes();
            SecurityStatus      status = SecurityStatus.InternalError;
            bool gotRef = false;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                this.ContextHandle.DangerousAddRef(ref gotRef);
            }
            catch (Exception)
            {
                if (gotRef)
                {
                    this.ContextHandle.DangerousRelease();
                    gotRef = false;
                }

                throw;
            }
            finally
            {
                if (gotRef)
                {
                    status = ContextNativeMethods.QueryContextAttributes_Sizes(
                        ref this.ContextHandle.rawHandle,
                        ContextQueryAttrib.Sizes,
                        ref sizes
                        );
                    this.ContextHandle.DangerousRelease();
                }
            }

            if (status != SecurityStatus.OK)
            {
                throw new SSPIException("Failed to query context buffer size attributes", status);
            }

            return(sizes);
        }
Example #4
0
        private int ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
        {
            if (readBytes == 0)
            {
                throw new IOException(SR.GetString("net_io_eof"));
            }
            readBytes += this._SslState.HeaderSize;
            int            num       = 0;
            SecurityStatus errorCode = this._SslState.DecryptData(this.InternalBuffer, ref num, ref readBytes);

            if (errorCode != SecurityStatus.OK)
            {
                byte[] dst = null;
                if (readBytes != 0)
                {
                    dst = new byte[readBytes];
                    Buffer.BlockCopy(this.InternalBuffer, num, dst, 0, readBytes);
                }
                this.DecrementInternalBufferCount(this.InternalBufferCount);
                return(this.ProcessReadErrorCode(errorCode, buffer, offset, count, asyncRequest, dst));
            }
            if ((readBytes == 0) && (count != 0))
            {
                this.DecrementInternalBufferCount(this.InternalBufferCount);
                return(-1);
            }
            this.EnsureInternalBufferSize(0, num + readBytes);
            this.DecrementInternalBufferCount(num);
            if (readBytes > count)
            {
                readBytes = count;
            }
            Buffer.BlockCopy(this.InternalBuffer, this.InternalOffset, buffer, offset, readBytes);
            this.DecrementInternalBufferCount(readBytes);
            this._SslState.FinishRead(null);
            if (asyncRequest != null)
            {
                asyncRequest.CompleteUser(readBytes);
            }
            return(readBytes);
        }
        private void setNTLMToken()
        {
            initNTLMClientAuth();

            if (NTLMChallangeToken != "")
            {
                serverToken = Convert.FromBase64String(NTLMChallangeToken);
                Debug.WriteLine("NTLM Challange token detected. Setting server token: " + NTLMChallangeToken);
            }

            //while (true)
            //{
            NSSPIclientStatus = NSSPIclient.Init(serverToken, out NTLMClientToken);
            Debug.WriteLine("NSSPI ClientStatus: " + NSSPIclientStatus.ToString());
            //if (clientStatus != SecurityStatus.ContinueNeeded) { break; }
            //}

            //
            this.NTLMToken = Convert.ToBase64String(NTLMClientToken);
            Debug.WriteLine("NTLMToken: " + this.NTLMToken);
        }
Example #6
0
        internal static SecurityStatus InitializeSecurityContext(SSPIInterface SecModule, ref SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer)
        {
            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web,
                                  "InitializeSecurityContext(" +
                                  "credential = " + credential.ToString() + ", " +
                                  "context = " + Logging.ObjectToString(context) + ", " +
                                  "targetName = " + targetName);
            }


            SecurityStatus errorCode = SecModule.InitializeSecurityContext(ref credential, ref context, targetName, inputBuffer, outputBuffer);

            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web, SR.Format(SR.net_log_sspi_security_context_input_buffer, "InitializeSecurityContext", (inputBuffer == null ? 0 : inputBuffer.size), outputBuffer.size, (SecurityStatus)errorCode));
            }

            return(errorCode);
        }
Example #7
0
        private void Init(NativeAuthData authData, string secPackage, CredentialUse use)
        {
            string         packageName;
            TimeStamp      rawExpiry = new TimeStamp();
            SecurityStatus status    = SecurityStatus.InternalError;

            // -- Package --
            // Copy off for the call, since this.SecurityPackage is a property.
            packageName = this.SecurityPackage;

            this.Handle = new SafeCredentialHandle();


            // The finally clause is the actual constrained region. The VM pre-allocates any stack space,
            // performs any allocations it needs to prepare methods for execution, and postpones any
            // instances of the 'uncatchable' exceptions (ThreadAbort, StackOverflow, OutOfMemory).
            RuntimeHelpers.PrepareConstrainedRegions();
            try { }
            finally
            {
                status = CredentialNativeMethods.AcquireCredentialsHandle_AuthData(
                    null,
                    packageName,
                    use,
                    IntPtr.Zero,
                    ref authData,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    ref this.Handle.rawHandle,
                    ref rawExpiry
                    );
            }

            if (status != SecurityStatus.OK)
            {
                throw new SSPIException("Failed to call AcquireCredentialHandle", status);
            }

            this.Expiry = rawExpiry.ToDateTime();
        }
Example #8
0
        public SecurityStatus EncryptMessage(SafeDeleteContext securityContext, byte[] buffer, int size, int headerSize, int trailerSize, out int resultSize)
        {
            resultSize = 0;

            // Encryption using SCHANNEL requires 4 buffers: header, payload, trailer, empty.
            SecurityBuffer[] securityBuffer = new SecurityBuffer[4];

            securityBuffer[0] = new SecurityBuffer(buffer, 0, headerSize, SecurityBufferType.Header);
            securityBuffer[1] = new SecurityBuffer(buffer, headerSize, size, SecurityBufferType.Data);
            securityBuffer[2] = new SecurityBuffer(buffer, headerSize + size, trailerSize, SecurityBufferType.Trailer);
            securityBuffer[3] = new SecurityBuffer(null, SecurityBufferType.Empty);

            SecurityStatus secStatus = EncryptDecryptHelper(OP.Encrypt, securityContext, securityBuffer, 0);

            if (secStatus == 0)
            {
                // The full buffer may not be used.
                resultSize = securityBuffer[0].size + securityBuffer[1].size + securityBuffer[2].size;
                GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::Encrypt OK", "data size:" + resultSize.ToString());
            }

            return(secStatus);
        }
Example #9
0
        //
        // Only processing SEC_I_RENEGOTIATE.
        //
        private int ProcessReadErrorCode(SecurityStatus errorCode, byte[] buffer, int offset, int count, byte[] extraBuffer)
        {
            // ERROR - examine what kind
            ProtocolToken message = new ProtocolToken(null, errorCode);

            GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::***Processing an error Status = " + message.Status.ToString());

            if (message.Renegotiate)
            {
                _SslState.ReplyOnReAuthentication(extraBuffer);

                // Loop on read.
                return(-1);
            }

            if (message.CloseConnection)
            {
                _SslState.FinishRead(null);
                return(0);
            }

            throw new IOException(SR.net_io_decrypt, message.GetException());
        }
        private bool createNSSPIToken()
        {
            try
            {
                initNSSPI();

                if (ChallangeToken != "")
                {
                    NSSPIChallangeToken = Convert.FromBase64String(ChallangeToken);

                    Debug.WriteLine("[NSSPI] NTLM Challange token detected. Setting as server token: " + ChallangeToken);
                }

                NSSPIclientStatus = NSSPIclient.Init(NSSPIChallangeToken, out NSSPIClientToken);

                this.AuthToken = Convert.ToBase64String(NSSPIClientToken);

                return(true);
            } catch (Exception e)
            {
                OnException("Failed to perform NSSPI Authentication while connecting to proxy. " + e.ToString());
                return(false);
            }
        }
Example #11
0
 private void ProcessReceivedBlob(byte[] buffer, int count, AsyncProtocolRequest asyncRequest)
 {
     if (count == 0)
     {
         throw new AuthenticationException(SR.GetString("net_auth_eof"), null);
     }
     if (this._PendingReHandshake)
     {
         int            offset    = 0;
         SecurityStatus errorCode = this.PrivateDecryptData(buffer, ref offset, ref count);
         if (errorCode == SecurityStatus.OK)
         {
             Exception exception = this.EnqueueOldKeyDecryptedData(buffer, offset, count);
             if (exception != null)
             {
                 this.StartSendAuthResetSignal(null, asyncRequest, exception);
                 return;
             }
             this._Framing = Framing.None;
             this.StartReceiveBlob(buffer, asyncRequest);
             return;
         }
         if (errorCode != SecurityStatus.Renegotiate)
         {
             ProtocolToken token = new ProtocolToken(null, errorCode);
             this.StartSendAuthResetSignal(null, asyncRequest, new AuthenticationException(SR.GetString("net_auth_SSPI"), token.GetException()));
             return;
         }
         this._PendingReHandshake = false;
         if (offset != 0)
         {
             Buffer.BlockCopy(buffer, offset, buffer, 0, count);
         }
     }
     this.StartSendBlob(buffer, count, asyncRequest);
 }
Example #12
0
        private void StartSendBlob(byte[] incoming, int count, AsyncProtocolRequest asyncRequest)
        {
            ProtocolToken message = this.Context.NextMessage(incoming, 0, count);

            this._SecurityStatus = message.Status;
            if (message.Size != 0)
            {
                if (this.Context.IsServer && (this._CachedSession == CachedSessionStatus.Unknown))
                {
                    this._CachedSession = (message.Size < 200) ? CachedSessionStatus.IsCached : CachedSessionStatus.IsNotCached;
                }
                if (this._Framing == Framing.Unified)
                {
                    this._Framing = this.DetectFraming(message.Payload, message.Payload.Length);
                }
                if (((message.Done && this._ForceBufferingLastHandshakePayload) && ((this.InnerStream.GetType() == typeof(NetworkStream)) && !this._PendingReHandshake)) && !this.CheckWin9xCachedSession())
                {
                    this._LastPayload = message.Payload;
                }
                else if (asyncRequest == null)
                {
                    this.InnerStream.Write(message.Payload, 0, message.Size);
                }
                else
                {
                    asyncRequest.AsyncState = message;
                    IAsyncResult asyncResult = this.InnerStream.BeginWrite(message.Payload, 0, message.Size, _WriteCallback, asyncRequest);
                    if (!asyncResult.CompletedSynchronously)
                    {
                        return;
                    }
                    this.InnerStream.EndWrite(asyncResult);
                }
            }
            this.CheckCompletionBeforeNextReceive(message, asyncRequest);
        }
 public override int GetHashCode()
 {
     unchecked
     {
         int hashCode = (StockExchange != null
                                 ? StockExchange.GetHashCode()
                                 : 0);
         hashCode = (hashCode * 397) ^ (TradeSector != null
                                 ? TradeSector.GetHashCode()
                                 : 0);
         hashCode = (hashCode * 397) ^ (SecurityCode != null
                                 ? SecurityCode.GetHashCode()
                                 : 0);
         hashCode = (hashCode * 397) ^ (SecurityName != null
                                 ? SecurityName.GetHashCode()
                                 : 0);
         hashCode = (hashCode * 397) ^ (SecurityClass != null
                                 ? SecurityClass.GetHashCode()
                                 : 0);
         hashCode = (hashCode * 397) ^ HasOptions.GetHashCode();
         hashCode = (hashCode * 397) ^ (SecurityStatus != null
                                 ? SecurityStatus.GetHashCode()
                                 : 0);
         hashCode = (hashCode * 397) ^ (Currency != null
                                 ? Currency.GetHashCode()
                                 : 0);
         hashCode = (hashCode * 397) ^ LimitUpPrice.GetHashCode();
         hashCode = (hashCode * 397) ^ LimitDownPrice.GetHashCode();
         hashCode = (hashCode * 397) ^ LotSize.GetHashCode();
         hashCode = (hashCode * 397) ^ (LotFlag != null
                                 ? LotFlag.GetHashCode()
                                 : 0);
         hashCode = (hashCode * 397) ^ (SuspendedFlag != null
                                 ? SuspendedFlag.GetHashCode()
                                 : 0);
         hashCode = (hashCode * 397) ^ (SecuritySubClass != null
                                 ? SecuritySubClass.GetHashCode()
                                 : 0);
         hashCode = (hashCode * 397) ^ (UnderlyinSecurityCode != null
                                 ? UnderlyinSecurityCode.GetHashCode()
                                 : 0);
         hashCode = (hashCode * 397) ^ (SecurityLevel != null
                                 ? SecurityLevel.GetHashCode()
                                 : 0);
         hashCode = (hashCode * 397) ^ PreviousClose.GetHashCode();
         hashCode = (hashCode * 397) ^ OpenPrice.GetHashCode();
         hashCode = (hashCode * 397) ^ Turnover.GetHashCode();
         hashCode = (hashCode * 397) ^ HighPrice.GetHashCode();
         hashCode = (hashCode * 397) ^ LowPrice.GetHashCode();
         hashCode = (hashCode * 397) ^ LastPrice.GetHashCode();
         hashCode = (hashCode * 397) ^ CurrentBidPrice.GetHashCode();
         hashCode = (hashCode * 397) ^ CurrentAskPrice.GetHashCode();
         hashCode = (hashCode * 397) ^ Volume.GetHashCode();
         hashCode = (hashCode * 397) ^ PERatio.GetHashCode();
         hashCode = (hashCode * 397) ^ BuyVolume1.GetHashCode();
         hashCode = (hashCode * 397) ^ SellVolume1.GetHashCode();
         hashCode = (hashCode * 397) ^ BuyPrice2.GetHashCode();
         hashCode = (hashCode * 397) ^ BuyVolume2.GetHashCode();
         hashCode = (hashCode * 397) ^ SellPrice2.GetHashCode();
         hashCode = (hashCode * 397) ^ SellVolume2.GetHashCode();
         hashCode = (hashCode * 397) ^ BuyPrice3.GetHashCode();
         hashCode = (hashCode * 397) ^ BuyVolume3.GetHashCode();
         hashCode = (hashCode * 397) ^ SellPrice3.GetHashCode();
         hashCode = (hashCode * 397) ^ SellVolume3.GetHashCode();
         hashCode = (hashCode * 397) ^ BuyPrice4.GetHashCode();
         hashCode = (hashCode * 397) ^ BuyVolume4.GetHashCode();
         hashCode = (hashCode * 397) ^ SellPrice4.GetHashCode();
         hashCode = (hashCode * 397) ^ SellVolume4.GetHashCode();
         hashCode = (hashCode * 397) ^ BuyPrice5.GetHashCode();
         hashCode = (hashCode * 397) ^ BuyVolume5.GetHashCode();
         hashCode = (hashCode * 397) ^ SellPrice5.GetHashCode();
         hashCode = (hashCode * 397) ^ SellVolume5.GetHashCode();
         return(hashCode);
     }
 }
        //
        // Methods
        //


        // This will return an client token when conducted authentication on server side'
        // This token can be used ofr impersanation
        // We use it to create a WindowsIdentity and hand it out to the server app.
        internal SafeCloseHandle GetContextToken(out SecurityStatus status)
        {
            GlobalLog.Assert(IsCompleted && IsValidContext, "NTAuthentication#{0}::GetContextToken|Should be called only when completed with success, currently is not!", ValidationHelper.HashString(this));
            GlobalLog.Assert(IsServer, "NTAuthentication#{0}::GetContextToken|The method must not be called by the client side!", ValidationHelper.HashString(this));

            if (!IsValidContext) {
                throw new Win32Exception((int)SecurityStatus.InvalidHandle);
            }


            SafeCloseHandle token = null;
            status = (SecurityStatus) SSPIWrapper.QuerySecurityContextToken(
                GlobalSSPI.SSPIAuth,
                m_SecurityContext,
                out token);

            return token;
        }
        // for Server side (IIS 6.0) see: \\netindex\Sources\inetsrv\iis\iisrearc\iisplus\ulw3\digestprovider.cxx
        // for Client side (HTTP.SYS) see: \\netindex\Sources\net\http\sys\ucauth.c
        internal string GetOutgoingDigestBlob(string incomingBlob, string requestMethod, string requestedUri, string realm, bool isClientPreAuth, bool throwOnError, out SecurityStatus statusCode)
        {
            GlobalLog.Enter("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob", incomingBlob);

            // second time call with 3 incoming buffers to select HTTP client.
            // we should get back a SecurityStatus.OK and a non null outgoingBlob.
            SecurityBuffer[] inSecurityBuffers = null;
            SecurityBuffer outSecurityBuffer = new SecurityBuffer(m_TokenSize, isClientPreAuth ? BufferType.Parameters : BufferType.Token);

            bool firstTime = m_SecurityContext == null;
            try {
                if (!m_IsServer) {
                    // client session

                    if (!isClientPreAuth) {

                        if (incomingBlob != null) 
                        {
                            List<SecurityBuffer> list = new List<SecurityBuffer>(5);

                            list.Add(new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(incomingBlob), BufferType.Token));
                            list.Add(new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(requestMethod), BufferType.Parameters));
                            list.Add(new SecurityBuffer(null, BufferType.Parameters));
                            list.Add(new SecurityBuffer(Encoding.Unicode.GetBytes(m_Spn), BufferType.TargetHost));

                            if (m_ChannelBinding != null) {
                                list.Add(new SecurityBuffer(m_ChannelBinding));
                            }

                            inSecurityBuffers = list.ToArray();
                        }

                        statusCode = (SecurityStatus) SSPIWrapper.InitializeSecurityContext(
                            GlobalSSPI.SSPIAuth,
                            m_CredentialsHandle,
                            ref m_SecurityContext,
                            requestedUri, // this must match the Uri in the HTTP status line for the current request
                            m_RequestedContextFlags,
                            Endianness.Network,
                            inSecurityBuffers,
                            outSecurityBuffer,
                            ref m_ContextFlags );

                        GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob() SSPIWrapper.InitializeSecurityContext() returns statusCode:0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");
                    }
                    else {
#if WDIGEST_PREAUTH
                        inSecurityBuffers = new SecurityBuffer[] {
                            new SecurityBuffer(null, BufferType.Token),
                            new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(requestMethod), BufferType.Parameters),
                            new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(requestedUri), BufferType.Parameters),
                            new SecurityBuffer(null, BufferType.Parameters),
                            outSecurityBuffer,
                        };

                        statusCode = (SecurityStatus) SSPIWrapper.MakeSignature(GlobalSSPI.SSPIAuth, m_SecurityContext, inSecurityBuffers, 0);

                        GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob() SSPIWrapper.MakeSignature() returns statusCode:0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");
#else
                        statusCode = SecurityStatus.OK;
                        GlobalLog.Assert("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob()", "Invalid code path.");
#endif
                    }
                }
                else {
                    // server session
                    List<SecurityBuffer> list = new List<SecurityBuffer>(6);
                    
                    list.Add(incomingBlob == null ? new SecurityBuffer(0, BufferType.Token) : new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(incomingBlob), BufferType.Token));
                    list.Add(requestMethod == null ? new SecurityBuffer(0, BufferType.Parameters) : new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(requestMethod), BufferType.Parameters));
                    list.Add(requestedUri == null ? new SecurityBuffer(0, BufferType.Parameters) : new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(requestedUri), BufferType.Parameters));
                    list.Add(new SecurityBuffer(0, BufferType.Parameters));
                    list.Add(realm == null ? new SecurityBuffer(0, BufferType.Parameters) : new SecurityBuffer(Encoding.Unicode.GetBytes(realm), BufferType.Parameters));

                    if (m_ChannelBinding != null) {
                        list.Add(new SecurityBuffer(m_ChannelBinding));
                    }

                    inSecurityBuffers = list.ToArray();

                    statusCode = (SecurityStatus) SSPIWrapper.AcceptSecurityContext(
                        GlobalSSPI.SSPIAuth,
                        m_CredentialsHandle,
                        ref m_SecurityContext,
                        m_RequestedContextFlags,
                        Endianness.Network,
                        inSecurityBuffers,
                        outSecurityBuffer,
                        ref m_ContextFlags );

                    GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob() SSPIWrapper.AcceptSecurityContext() returns statusCode:0x" + ((int)statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");

                    if (statusCode == SecurityStatus.CompleteNeeded)
                    {
                        inSecurityBuffers[4] = outSecurityBuffer;

                        statusCode = (SecurityStatus) SSPIWrapper.CompleteAuthToken(
                                GlobalSSPI.SSPIAuth,
                                ref m_SecurityContext,
                                inSecurityBuffers );

                        GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob() SSPIWrapper.CompleteAuthToken() returns statusCode:0x" + ((int)statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");

                        outSecurityBuffer.token = null;
                    }
                }
            }
            finally {
                //
                // Assuming the ISC or ASC has referenced the credential on the first successful call,
                // we want to decrement the effective ref count by "disposing" it.
                // The real dispose will happen when the security context is closed.
                // Note if the first call was not successfull the handle is physically destroyed here
                //
              if (firstTime && m_CredentialsHandle != null)
                  m_CredentialsHandle.Close();
            }


            if (((int) statusCode & unchecked((int) 0x80000000)) != 0)
            {
                CloseContext();
                if (throwOnError) {
                    Win32Exception exception = new Win32Exception((int) statusCode);
                    GlobalLog.Leave("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob", "Win32Exception:" + exception);
                    throw exception;
                }
                GlobalLog.Leave("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob", "null statusCode:0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");
                return null;
            }
            else if (firstTime && m_CredentialsHandle != null)
            {
                // cache until it is pushed out by newly incoming handles
                SSPIHandleCache.CacheCredential(m_CredentialsHandle);
            }


            // the return value from SSPI will tell us correctly if the
            // handshake is over or not: http://msdn.microsoft.com/library/psdk/secspi/sspiref_67p0.htm
            if (statusCode == SecurityStatus.OK)
            {
                // we're done, cleanup
                m_IsCompleted = true;
            }
            else {
                // we need to continue
                GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob() need continue statusCode:[0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + "] (" + statusCode.ToString() + ") m_SecurityContext#" + ValidationHelper.HashString(m_SecurityContext) + "::Handle:" + ValidationHelper.ToString(m_SecurityContext) + "]");
            }
            GlobalLog.Print("out token = " + outSecurityBuffer.ToString());
            GlobalLog.Dump(outSecurityBuffer.token);
            GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob() IsCompleted:" + IsCompleted.ToString());

            byte[] decodedOutgoingBlob = outSecurityBuffer.token;
            string outgoingBlob = null;
            if (decodedOutgoingBlob!=null && decodedOutgoingBlob.Length>0) {
                outgoingBlob = WebHeaderCollection.HeaderEncoding.GetString(decodedOutgoingBlob, 0, outSecurityBuffer.size);
            }
            GlobalLog.Leave("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob", outgoingBlob);
            return outgoingBlob;
        }
 /// <summary>
 /// Initializes a new instance of the SSPIException class from serialization data.
 /// </summary>
 /// <param name="info"></param>
 /// <param name="context"></param>
 protected SSPIException(SerializationInfo info, StreamingContext context)
     : base(info, context)
 {
     this.message   = info.GetString("message");
     this.errorCode = (SecurityStatus)info.GetUInt32("errorCode");
 }
Example #17
0
        //
        // Codes we process (Anything else - fail)
        //
        // - SEC_I_RENEGOTIATE
        //
        private int ProcessReadErrorCode(SecurityStatus errorCode, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest, byte[] extraBuffer)
        {
            // ERROR - examine what kind
            ProtocolToken message = new ProtocolToken(null, errorCode);

            GlobalLog.Print("SecureChannel#" + ValidationHelper.HashString(this) + "::***Processing an error Status = " + message.Status.ToString());

            if (message.Renegotiate)
            {
                _SslState.ReplyOnReAuthentication(extraBuffer);
                // loop on read
                return -1;
            }
            if (message.CloseConnection) {
                _SslState.FinishRead(null);
                if (asyncRequest != null)
                {
                    asyncRequest.CompleteUser((object)0);
                }
                return 0;
            }
            // Otherwise bail out.
            throw new IOException(SR.GetString(SR.net_io_decrypt), message.GetException());
        }
Example #18
0
        /// <summary>
        /// Encrypts the byte array using the context's session key.
        /// </summary>
        /// <remarks>
        /// The structure of the returned data is as follows:
        ///  - 2 bytes, an unsigned big-endian integer indicating the length of the trailer buffer size
        ///  - 4 bytes, an unsigned big-endian integer indicating the length of the message buffer size.
        ///  - 2 bytes, an unsigned big-endian integer indicating the length of the encryption padding buffer size.
        ///  - The trailer buffer
        ///  - The message buffer
        ///  - The padding buffer.
        /// </remarks>
        /// <param name="input">The raw message to encrypt.</param>
        /// <returns>The packed and encrypted message.</returns>
        public byte[] Encrypt(byte[] input)
        {
            // The message is encrypted in place in the buffer we provide to Win32 EncryptMessage
            SecPkgContext_Sizes sizes;

            SecureBuffer        trailerBuffer;
            SecureBuffer        dataBuffer;
            SecureBuffer        paddingBuffer;
            SecureBufferAdapter adapter;

            SecurityStatus status = SecurityStatus.InvalidHandle;

            byte[] result;

            CheckLifecycle();

            sizes = QueryBufferSizes();

            trailerBuffer = new SecureBuffer(new byte[sizes.SecurityTrailer], BufferType.Token);
            dataBuffer    = new SecureBuffer(new byte[input.Length], BufferType.Data);
            paddingBuffer = new SecureBuffer(new byte[sizes.BlockSize], BufferType.Padding);

            Array.Copy(input, dataBuffer.Buffer, input.Length);

            using (adapter = new SecureBufferAdapter(new[] { trailerBuffer, dataBuffer, paddingBuffer }))
            {
                status = ContextNativeMethods.SafeEncryptMessage(
                    this.ContextHandle,
                    0,
                    adapter,
                    0
                    );
            }

            if (status != SecurityStatus.OK)
            {
                SSPIException exc = new SSPIException("Failed to encrypt message", status);
                throw new SecurityException(ErrorHandling.ErrorCodes.Security.SSPI_ERROR, new string[] { exc.Message });
            }

            int position = 0;

            // Enough room to fit:
            //  -- 2 bytes for the trailer buffer size
            //  -- 4 bytes for the message size
            //  -- 2 bytes for the padding size.
            //  -- The encrypted message
            result = new byte[2 + 4 + 2 + trailerBuffer.Length + dataBuffer.Length + paddingBuffer.Length];

            ByteWriter.WriteInt16_BE((short)trailerBuffer.Length, result, position);
            position += 2;

            ByteWriter.WriteInt32_BE(dataBuffer.Length, result, position);
            position += 4;

            ByteWriter.WriteInt16_BE((short)paddingBuffer.Length, result, position);
            position += 2;

            Array.Copy(trailerBuffer.Buffer, 0, result, position, trailerBuffer.Length);
            position += trailerBuffer.Length;

            Array.Copy(dataBuffer.Buffer, 0, result, position, dataBuffer.Length);
            position += dataBuffer.Length;

            Array.Copy(paddingBuffer.Buffer, 0, result, position, paddingBuffer.Length);
            position += paddingBuffer.Length;

            return(result);
        }
        /// <summary>
        /// Verifies the signature of a signed message
        /// </summary>
        /// <remarks>
        /// The expected structure of the signed message buffer is as follows:
        ///  - 4 bytes, unsigned integer in big endian format indicating the length of the plaintext message
        ///  - 2 bytes, unsigned integer in big endian format indicating the length of the signture
        ///  - The plaintext message
        ///  - The message's signature.
        /// </remarks>
        /// <param name="signedMessage">The packed signed message.</param>
        /// <param name="origMessage">The extracted original message.</param>
        /// <returns>True if the message has a valid signature, false otherwise.</returns>
        public bool VerifySignature(byte[] signedMessage, out byte[] origMessage)
        {
            SecurityStatus status = SecurityStatus.InternalError;

            SecPkgContext_Sizes sizes;
            SecureBuffer        dataBuffer;
            SecureBuffer        signatureBuffer;
            SecureBufferAdapter adapter;

            CheckLifecycle();

            sizes = QueryBufferSizes();

            if (signedMessage.Length < 2 + 4 + sizes.MaxSignature)
            {
                throw new ArgumentException("Input message is too small to possibly fit a valid message");
            }

            int position = 0;
            int messageLen;
            int sigLen;

            messageLen = ByteWriter.ReadInt32_BE(signedMessage, 0);
            position  += 4;

            sigLen    = ByteWriter.ReadInt16_BE(signedMessage, position);
            position += 2;

            if (messageLen + sigLen + 2 + 4 > signedMessage.Length)
            {
                throw new ArgumentException("The buffer contains invalid data - the embedded length data does not add up.");
            }

            dataBuffer = new SecureBuffer(new byte[messageLen], BufferType.Data);
            Array.Copy(signedMessage, position, dataBuffer.Buffer, 0, messageLen);
            position += messageLen;

            signatureBuffer = new SecureBuffer(new byte[sigLen], BufferType.Token);
            Array.Copy(signedMessage, position, signatureBuffer.Buffer, 0, sigLen);
            position += sigLen;

            using (adapter = new SecureBufferAdapter(new[] { dataBuffer, signatureBuffer }))
            {
                status = ContextNativeMethods.SafeVerifySignature(
                    this.ContextHandle,
                    0,
                    adapter,
                    0
                    );
            }

            if (status == SecurityStatus.OK)
            {
                origMessage = dataBuffer.Buffer;
                return(true);
            }
            else if (status == SecurityStatus.MessageAltered ||
                     status == SecurityStatus.OutOfSequence)
            {
                origMessage = null;
                return(false);
            }
            else
            {
                throw new SspiException("Failed to determine the veracity of a signed message.", status);
            }
        }
Example #20
0
 public Exception GetException(SecurityStatus status)
 {
     // TODO (Issue #3362) To be implemented
     return(new Exception("status = " + status));
 }
 internal ProtocolToken(byte[] data, SecurityStatus errorCode)
 {
     this.Status = errorCode;
     this.Payload = data;
     this.Size = (data != null) ? data.Length : 0;
 }
 private HttpStatusCode HttpStatusFromSecurityStatus(SecurityStatus status)
 {
     if (NclUtilities.IsCredentialFailure(status))
     {
         return HttpStatusCode.Unauthorized;
     }
     if (NclUtilities.IsClientFault(status))
     {
         return HttpStatusCode.BadRequest;
     }
     return HttpStatusCode.InternalServerError;
 }
Example #23
0
 internal static Exception GetException(SSPIInterface secModule, SecurityStatus status)
 {
     return secModule.GetException(status);
 }
 private int ProcessReadErrorCode(SecurityStatus errorCode, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest, byte[] extraBuffer)
 {
     ProtocolToken token = new ProtocolToken(null, errorCode);
     if (token.Renegotiate)
     {
         this._SslState.ReplyOnReAuthentication(extraBuffer);
         return -1;
     }
     if (!token.CloseConnection)
     {
         throw new IOException(SR.GetString("net_io_decrypt"), token.GetException());
     }
     this._SslState.FinishRead(null);
     if (asyncRequest != null)
     {
         asyncRequest.CompleteUser(0);
     }
     return 0;
 }
 internal static bool IsCredentialFailure(SecurityStatus error)
 {
     if ((((error != SecurityStatus.LogonDenied) && (error != SecurityStatus.UnknownCredentials)) && ((error != SecurityStatus.NoImpersonation) && (error != SecurityStatus.NoAuthenticatingAuthority))) && (((error != SecurityStatus.UntrustedRoot) && (error != SecurityStatus.CertExpired)) && (error != SecurityStatus.SmartcardLogonRequired)))
     {
         return (error == SecurityStatus.BadBinding);
     }
     return true;
 }
 internal static bool IsClientFault(SecurityStatus error)
 {
     if (((((error != SecurityStatus.InvalidToken) && (error != SecurityStatus.CannotPack)) && ((error != SecurityStatus.QopNotSupported) && (error != SecurityStatus.NoCredentials))) && (((error != SecurityStatus.MessageAltered) && (error != SecurityStatus.OutOfSequence)) && ((error != SecurityStatus.IncompleteMessage) && (error != SecurityStatus.IncompleteCredentials)))) && ((((error != SecurityStatus.WrongPrincipal) && (error != SecurityStatus.TimeSkew)) && ((error != SecurityStatus.IllegalMessage) && (error != SecurityStatus.CertUnknown))) && ((error != SecurityStatus.AlgorithmMismatch) && (error != SecurityStatus.SecurityQosFailed))))
     {
         return (error == SecurityStatus.UnsupportedPreauth);
     }
     return true;
 }
Example #27
0
        //
        // Client side starts here, but server also loops through this method.
        //
        private void StartSendBlob(byte[] incoming, int count, AsyncProtocolRequest asyncRequest)
        {
            ProtocolToken message = Context.NextMessage(incoming, 0, count);
            _securityStatus = message.Status;

            if (message.Size != 0)
            {
                if (Context.IsServer && _CachedSession == CachedSessionStatus.Unknown)
                {
                    //
                    //[Schannel] If the first call to ASC returns a token less than 200 bytes,
                    //           then it's a reconnect (a handshake based on a cache entry).
                    //
                    _CachedSession = message.Size < 200 ? CachedSessionStatus.IsCached : CachedSessionStatus.IsNotCached;
                }

                if (_Framing == Framing.Unified)
                {
                    _Framing = DetectFraming(message.Payload, message.Payload.Length);
                }

                if (asyncRequest == null)
                {
                    InnerStream.Write(message.Payload, 0, message.Size);
                }
                else
                {
                    asyncRequest.AsyncState = message;
                    IAsyncResult ar = InnerStreamAPM.BeginWrite(message.Payload, 0, message.Size, s_writeCallback, asyncRequest);
                    if (!ar.CompletedSynchronously)
                    {
#if DEBUG
                        asyncRequest._DebugAsyncChain = ar;
#endif
                        return;
                    }

                    InnerStreamAPM.EndWrite(ar);
                }
            }

            CheckCompletionBeforeNextReceive(message, asyncRequest);
        }
 public Exception GetException(SecurityStatus status)
 {
     // TODO (Issue #3362) To be implemented
     return new Exception("status = " + status);
 }
 private void StartSendBlob(byte[] incoming, int count, AsyncProtocolRequest asyncRequest)
 {
     ProtocolToken message = this.Context.NextMessage(incoming, 0, count);
     this._SecurityStatus = message.Status;
     if (message.Size != 0)
     {
         if (this.Context.IsServer && (this._CachedSession == CachedSessionStatus.Unknown))
         {
             this._CachedSession = (message.Size < 200) ? CachedSessionStatus.IsCached : CachedSessionStatus.IsNotCached;
         }
         if (this._Framing == Framing.Unified)
         {
             this._Framing = this.DetectFraming(message.Payload, message.Payload.Length);
         }
         if (((message.Done && this._ForceBufferingLastHandshakePayload) && ((this.InnerStream.GetType() == typeof(NetworkStream)) && !this._PendingReHandshake)) && !this.CheckWin9xCachedSession())
         {
             this._LastPayload = message.Payload;
         }
         else if (asyncRequest == null)
         {
             this.InnerStream.Write(message.Payload, 0, message.Size);
         }
         else
         {
             asyncRequest.AsyncState = message;
             IAsyncResult asyncResult = this.InnerStream.BeginWrite(message.Payload, 0, message.Size, _WriteCallback, asyncRequest);
             if (!asyncResult.CompletedSynchronously)
             {
                 return;
             }
             this.InnerStream.EndWrite(asyncResult);
         }
     }
     this.CheckCompletionBeforeNextReceive(message, asyncRequest);
 }
 public Exception GetException(SecurityStatus status)
 {
     return new Interop.OpenSsl.SslException((int)status);
 }
 public Exception GetException(SecurityStatus status)
 {
     return new Win32Exception((int)status);
 }
 // Token: 0x06000020 RID: 32 RVA: 0x00002DC0 File Offset: 0x00000FC0
 internal Stream GetCommandParameterStream(string targetHost, string responseLine, out Exception failureException)
 {
     failureException = null;
     if (this.CommandType == ImapCommandType.Append)
     {
         return(this.CommandParameters[2] as Stream);
     }
     if (this.CommandType == ImapCommandType.Authenticate)
     {
         byte[]       inputBuffer = null;
         MemoryStream result      = null;
         ImapAuthenticationMechanism imapAuthenticationMechanism = (ImapAuthenticationMechanism)this.CommandParameters[0];
         string                text     = (string)this.CommandParameters[1];
         SecureString          password = (SecureString)this.CommandParameters[2];
         AuthenticationContext authenticationContext = (AuthenticationContext)this.CommandParameters[3];
         string                text2 = null;
         if (responseLine != null && responseLine.Length > 2)
         {
             inputBuffer = Encoding.ASCII.GetBytes(responseLine.Substring(2));
         }
         byte[] buffer = null;
         ImapAuthenticationMechanism imapAuthenticationMechanism2 = imapAuthenticationMechanism;
         if (imapAuthenticationMechanism2 != ImapAuthenticationMechanism.Basic)
         {
             if (imapAuthenticationMechanism2 == ImapAuthenticationMechanism.Ntlm)
             {
                 SecurityStatus securityStatus;
                 if (authenticationContext == null)
                 {
                     authenticationContext     = new AuthenticationContext();
                     this.CommandParameters[3] = authenticationContext;
                     string spn = "IMAP/" + targetHost;
                     securityStatus = authenticationContext.InitializeForOutboundNegotiate(AuthenticationMechanism.Ntlm, spn, text, password);
                     if (securityStatus != SecurityStatus.OK)
                     {
                         failureException = new ImapAuthenticationException(targetHost, imapAuthenticationMechanism.ToString(), RetryPolicy.Backoff);
                         return(null);
                     }
                 }
                 securityStatus = authenticationContext.NegotiateSecurityContext(inputBuffer, out buffer);
                 SecurityStatus securityStatus2 = securityStatus;
                 if (securityStatus2 != SecurityStatus.OK && securityStatus2 != SecurityStatus.ContinueNeeded)
                 {
                     failureException = new ImapAuthenticationException(targetHost, imapAuthenticationMechanism.ToString(), RetryPolicy.Backoff);
                     return(null);
                 }
                 result = new MemoryStream(buffer);
             }
             else
             {
                 failureException = new ImapUnsupportedAuthenticationException(targetHost, imapAuthenticationMechanism.ToString(), RetryPolicy.Backoff);
             }
         }
         else
         {
             SecurityStatus securityStatus;
             if (authenticationContext == null)
             {
                 authenticationContext     = new AuthenticationContext();
                 this.CommandParameters[3] = authenticationContext;
                 Match match = ImapCommand.UserNameWithAuthorizationId.Match(text);
                 if (match != null && match.Success && match.Groups.Count == 3)
                 {
                     text2 = match.Groups[1].Value;
                     text  = match.Groups[2].Value;
                 }
                 securityStatus = authenticationContext.InitializeForOutboundNegotiate(AuthenticationMechanism.Plain, null, text, password);
                 if (securityStatus != SecurityStatus.OK)
                 {
                     failureException = new ImapAuthenticationException(targetHost, imapAuthenticationMechanism.ToString(), RetryPolicy.Backoff);
                     return(null);
                 }
                 if (text2 != null)
                 {
                     authenticationContext.AuthorizationIdentity = Encoding.ASCII.GetBytes(text2);
                 }
             }
             securityStatus = authenticationContext.NegotiateSecurityContext(inputBuffer, out buffer);
             SecurityStatus securityStatus3 = securityStatus;
             if (securityStatus3 != SecurityStatus.OK)
             {
                 failureException = new ImapAuthenticationException(targetHost, imapAuthenticationMechanism.ToString(), RetryPolicy.Backoff);
                 return(null);
             }
             result = new MemoryStream(buffer);
         }
         return(result);
     }
     return(null);
 }
Example #33
0
 private void UpdateMarketState(string secturityId, SecurityStatus securityStatus)
 {
     if (secturityId != null)
     {
         this.marketStateToolStripStatusLabel.Text = string.Format("SecurityId={0}, Status={1}", secturityId, securityStatus);
     }
     else
     {
         this.marketStateToolStripStatusLabel.Text = string.Format("SecurityId=, Status={0}", securityStatus);
     }
 }
Example #34
0
        //
        // Client side starts here, but server also loops through this method
        //
        private void StartSendBlob(byte[] incoming, int count, AsyncProtocolRequest asyncRequest)
        {
            ProtocolToken message = Context.NextMessage(incoming, 0, count);
            _SecurityStatus = message.Status;

            if (message.Size != 0)
            {
                if (Context.IsServer && _CachedSession == CachedSessionStatus.Unknown)
                {
                    //
                    //[Schannel] If the first call to ASC returns a token less than 200 bytes,
                    //           then it's a reconnect (a handshake based on a cache entry)
                    //
                    _CachedSession = message.Size < 200? CachedSessionStatus.IsCached: CachedSessionStatus.IsNotCached;
                }

                if (_Framing == Framing.Unified)
                {
                    _Framing = DetectFraming(message.Payload, message.Payload.Length);
                }

                // Even if we are comleted, there could be a blob for sending.
                // ONLY for TlsStream we want to delay it if the underlined stream is a NetworkStream that is subject to Nagle algorithm
                // 
                if ( message.Done && _ForceBufferingLastHandshakePayload && InnerStream.GetType() == typeof(NetworkStream) && !_PendingReHandshake)
                {
                    _LastPayload = message.Payload;
                }
                else
                {
                    if (asyncRequest == null)
                    {
                        InnerStream.Write(message.Payload, 0, message.Size);
                    }
                    else
                    {
                        asyncRequest.AsyncState = message;
                        IAsyncResult ar = InnerStream.BeginWrite(message.Payload, 0, message.Size, _WriteCallback, asyncRequest);
                        if (!ar.CompletedSynchronously)
                        {
#if DEBUG
                            asyncRequest._DebugAsyncChain = ar;
#endif
                            return;
                        }
                        InnerStream.EndWrite(ar);
                    }
                }
            }
            CheckCompletionBeforeNextReceive(message, asyncRequest);
        }
 /// <summary>
 /// Initializes a new instance of the SSPIException class with the given message and status.
 /// </summary>
 /// <param name="message">A message explaining what part of the system failed.</param>
 /// <param name="errorCode">The error code observed during the failure.</param>
 public SSPIException(string message, SecurityStatus errorCode)
 {
     this.message   = message;
     this.errorCode = errorCode;
 }
		public bool ProcessHandshakeMessage (HandshakeType type, TlsBuffer incoming, out SecurityStatus status)
		{
			if (HasPendingOutput && type != HandshakeType.HelloRequest)
				throw new TlsException (AlertDescription.InternalError);
			if (!VerifyMessage (type)) {
				if (type == HandshakeType.HelloRequest) {
					status = SecurityStatus.ContinueNeeded;
					return false;
				}
				throw new TlsException (AlertDescription.UnexpectedMessage);
			}

			var incomingBuffer = new BufferOffsetSize (incoming.Buffer, incoming.Position - 4, incoming.Remaining + 4);

			var startPosition = incoming.Position - 4;
			var message = CreateMessage (type, incoming);
			incoming.Position = startPosition;

			#if DEBUG_FULL
			if (Context.EnableDebugging)
				DebugHelper.WriteLine ("ProcessMessage: {0} {1} {2}", GetType ().Name, Context.IsServer, type);
			#endif

			#if INSTRUMENTATION
			if (State == NegotiationState.InitialServerConnection && Context.HasInstrument (HandshakeInstrumentType.CloseServerConnection)) {
				DebugHelper.WriteLine ("Instrumentation requested to close server connection.");
				status = SecurityStatus.InvalidHandle;
				return true;
			}
			#endif

 			var result = HandleMessage (message);

			switch (result) {
			case MessageStatus.CredentialsNeeded:
				status = SecurityStatus.CredentialsNeeded;
				return false;

			case MessageStatus.Finished:
				hasPendingOutput = true;
				if (Context.IsServer)
					Context.HandshakeParameters.HandshakeMessages.Add (message, incomingBuffer);
				status = SecurityStatus.OK;
				return true;

			case MessageStatus.IgnoreMessage:
				status = SecurityStatus.ContinueNeeded;
				return false;

			case MessageStatus.Renegotiate:
				hasPendingOutput = true;
				if (message.Type != HandshakeType.HelloRequest)
					Context.HandshakeParameters.HandshakeMessages.Add (message, incomingBuffer);
				status = SecurityStatus.ContinueNeeded;
				return true;

			case MessageStatus.GenerateOutput:
				hasPendingOutput = true;
				Context.HandshakeParameters.HandshakeMessages.Add (message, incomingBuffer);
				status = SecurityStatus.ContinueNeeded;
				return true;

			case MessageStatus.ContinueNeeded:
				Context.HandshakeParameters.HandshakeMessages.Add (message, incomingBuffer);
				status = SecurityStatus.ContinueNeeded;
				return false;

			default:
				throw new InvalidOperationException ();
			}
		}
Example #37
0
 public void Deserialize(Serialization.IO.CompactReader reader)
 {
     Token  = reader.ReadObject() as Byte[];
     Status = (SecurityStatus)reader.ReadObject();
 }
Example #38
0
 internal static Exception GetException(SSPIInterface secModule, SecurityStatus status)
 {
     return(secModule.GetException(status));
 }
Example #39
0
 internal ProtocolToken(byte[] data, SecurityStatus errorCode) {
     Status = errorCode;
     Payload = data;
     Size = data!=null ? data.Length : 0;
 }
Example #40
0
 // This only works for context-destroying errors.
 internal static bool IsClientFault(SecurityStatus error)
 {
     return error == SecurityStatus.InvalidToken ||
         error == SecurityStatus.CannotPack ||
         error == SecurityStatus.QopNotSupported ||
         error == SecurityStatus.NoCredentials ||
         error == SecurityStatus.MessageAltered ||
         error == SecurityStatus.OutOfSequence ||
         error == SecurityStatus.IncompleteMessage ||
         error == SecurityStatus.IncompleteCredentials ||
         error == SecurityStatus.WrongPrincipal ||
         error == SecurityStatus.TimeSkew ||
         error == SecurityStatus.IllegalMessage ||
         error == SecurityStatus.CertUnknown ||
         error == SecurityStatus.AlgorithmMismatch ||
         error == SecurityStatus.SecurityQosFailed ||
         error == SecurityStatus.UnsupportedPreauth;
 }
        // NTAuth::GetOutgoingBlob()
        // Created:   12-01-1999: L.M.
        // Description:
        // Accepts an incoming binary security blob  and returns
        // an outgoing binary security blob
        internal byte[] GetOutgoingBlob(byte[] incomingBlob, bool throwOnError, out SecurityStatus statusCode)
        {
            GlobalLog.Enter("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob", ((incomingBlob == null) ? "0" : incomingBlob.Length.ToString(NumberFormatInfo.InvariantInfo)) + " bytes");

            List<SecurityBuffer> list = new List<SecurityBuffer>(2);
            
            if (incomingBlob != null) {
                list.Add(new SecurityBuffer(incomingBlob, BufferType.Token));
            }
            if (m_ChannelBinding != null) {
                list.Add(new SecurityBuffer(m_ChannelBinding));
            }

            SecurityBuffer[] inSecurityBufferArray = null;
            if (list.Count > 0)
            {
                inSecurityBufferArray = list.ToArray();
            }

            SecurityBuffer outSecurityBuffer = new SecurityBuffer(m_TokenSize, BufferType.Token);

            bool firstTime = m_SecurityContext == null;
            try {
                if (!m_IsServer) {
                    // client session
                    statusCode = (SecurityStatus)SSPIWrapper.InitializeSecurityContext(
                        GlobalSSPI.SSPIAuth,
                        m_CredentialsHandle,
                        ref m_SecurityContext,
                        m_Spn,
                        m_RequestedContextFlags,
                        Endianness.Network,
                        inSecurityBufferArray,
                        outSecurityBuffer,
                        ref m_ContextFlags);

                    GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob() SSPIWrapper.InitializeSecurityContext() returns statusCode:0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");

                    if (statusCode == SecurityStatus.CompleteNeeded)
                    {
                        SecurityBuffer[] inSecurityBuffers = new SecurityBuffer[1];
                        inSecurityBuffers[0] = outSecurityBuffer;

                        statusCode = (SecurityStatus) SSPIWrapper.CompleteAuthToken(
                            GlobalSSPI.SSPIAuth,
                            ref m_SecurityContext,
                            inSecurityBuffers );

                        GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob() SSPIWrapper.CompleteAuthToken() returns statusCode:0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");
                        outSecurityBuffer.token = null;
                    }
                }
                else {
                    // server session
                    statusCode = (SecurityStatus)SSPIWrapper.AcceptSecurityContext(
                        GlobalSSPI.SSPIAuth,
                        m_CredentialsHandle,
                        ref m_SecurityContext,
                        m_RequestedContextFlags,
                        Endianness.Network,
                        inSecurityBufferArray,
                        outSecurityBuffer,
                        ref m_ContextFlags);

                    GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob() SSPIWrapper.AcceptSecurityContext() returns statusCode:0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");
                }
            }
            finally {
                //
                // Assuming the ISC or ASC has referenced the credential on the first successful call,
                // we want to decrement the effective ref count by "disposing" it.
                // The real dispose will happen when the security context is closed.
                // Note if the first call was not successfull the handle is physically destroyed here
                //
              if (firstTime && m_CredentialsHandle != null)
                  m_CredentialsHandle.Close();
            }


          if (((int) statusCode & unchecked((int) 0x80000000)) != 0)
          {
                CloseContext();
                m_IsCompleted = true;
                if (throwOnError) {
                    Win32Exception exception = new Win32Exception((int) statusCode);
                    GlobalLog.Leave("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob", "Win32Exception:" + exception);
                    throw exception;
                }
                GlobalLog.Leave("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob", "null statusCode:0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");
                return null;
            }
            else if (firstTime && m_CredentialsHandle != null)
            {
                // cache until it is pushed out by newly incoming handles
                SSPIHandleCache.CacheCredential(m_CredentialsHandle);
            }

            // the return value from SSPI will tell us correctly if the
            // handshake is over or not: http://msdn.microsoft.com/library/psdk/secspi/sspiref_67p0.htm
            // we also have to consider the case in which SSPI formed a new context, in this case we're done as well.
            if (statusCode == SecurityStatus.OK)
            {
                // we're sucessfully done
                GlobalLog.Assert(statusCode == SecurityStatus.OK, "NTAuthentication#{0}::GetOutgoingBlob()|statusCode:[0x{1:x8}] ({2}) m_SecurityContext#{3}::Handle:[{4}] [STATUS != OK]", ValidationHelper.HashString(this), (int)statusCode, statusCode, ValidationHelper.HashString(m_SecurityContext), ValidationHelper.ToString(m_SecurityContext));
                m_IsCompleted = true;
            }
            else {
                // we need to continue
                GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob() need continue statusCode:[0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + "] (" + statusCode.ToString() + ") m_SecurityContext#" + ValidationHelper.HashString(m_SecurityContext) + "::Handle:" + ValidationHelper.ToString(m_SecurityContext) + "]");
            }
//            GlobalLog.Print("out token = " + outSecurityBuffer.ToString());
//            GlobalLog.Dump(outSecurityBuffer.token);
            GlobalLog.Leave("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob", "IsCompleted:" + IsCompleted.ToString());
            return outSecurityBuffer.token;
        }
 internal byte[] GetOutgoingBlob(byte[] incomingBlob, bool throwOnError, out SecurityStatus statusCode)
 {
     List<SecurityBuffer> list = new List<SecurityBuffer>(2);
     if (incomingBlob != null)
     {
         list.Add(new SecurityBuffer(incomingBlob, BufferType.Token));
     }
     if (this.m_ChannelBinding != null)
     {
         list.Add(new SecurityBuffer(this.m_ChannelBinding));
     }
     SecurityBuffer[] inputBuffers = null;
     if (list.Count > 0)
     {
         inputBuffers = list.ToArray();
     }
     SecurityBuffer outputBuffer = new SecurityBuffer(this.m_TokenSize, BufferType.Token);
     bool flag = this.m_SecurityContext == null;
     try
     {
         if (!this.m_IsServer)
         {
             statusCode = (SecurityStatus) SSPIWrapper.InitializeSecurityContext(GlobalSSPI.SSPIAuth, this.m_CredentialsHandle, ref this.m_SecurityContext, this.m_Spn, this.m_RequestedContextFlags, Endianness.Network, inputBuffers, outputBuffer, ref this.m_ContextFlags);
             if (statusCode == SecurityStatus.CompleteNeeded)
             {
                 SecurityBuffer[] bufferArray2 = new SecurityBuffer[] { outputBuffer };
                 statusCode = (SecurityStatus) SSPIWrapper.CompleteAuthToken(GlobalSSPI.SSPIAuth, ref this.m_SecurityContext, bufferArray2);
                 outputBuffer.token = null;
             }
         }
         else
         {
             statusCode = (SecurityStatus) SSPIWrapper.AcceptSecurityContext(GlobalSSPI.SSPIAuth, this.m_CredentialsHandle, ref this.m_SecurityContext, this.m_RequestedContextFlags, Endianness.Network, inputBuffers, outputBuffer, ref this.m_ContextFlags);
         }
     }
     finally
     {
         if (flag && (this.m_CredentialsHandle != null))
         {
             this.m_CredentialsHandle.Close();
         }
     }
     if ((statusCode & ((SecurityStatus) (-2147483648))) != SecurityStatus.OK)
     {
         this.CloseContext();
         this.m_IsCompleted = true;
         if (throwOnError)
         {
             Win32Exception exception = new Win32Exception((int) statusCode);
             throw exception;
         }
         return null;
     }
     if (flag && (this.m_CredentialsHandle != null))
     {
         SSPIHandleCache.CacheCredential(this.m_CredentialsHandle);
     }
     if (statusCode == SecurityStatus.OK)
     {
         this.m_IsCompleted = true;
     }
     return outputBuffer.token;
 }
        /// <summary>
        /// Changes the current thread's security context to impersonate the user of the client.
        /// </summary>
        /// <remarks>
        /// Requires that the security package provided with the server's credentials, as well as the
        /// client's credentials, support impersonation.
        ///
        /// Currently, only one thread may initiate impersonation per security context. Impersonation may
        /// follow threads created by the initial impersonation thread, however.
        /// </remarks>
        /// <returns>A handle to capture the lifetime of the impersonation. Dispose the handle to revert
        /// impersonation. If the handle is leaked, the impersonation will automatically revert at a
        /// non-deterministic time when the handle is finalized by the Garbage Collector.</returns>
        public ImpersonationHandle ImpersonateClient()
        {
            ImpersonationHandle handle;
            SecurityStatus      status = SecurityStatus.InternalError;
            bool gotRef = false;

            if (this.Disposed)
            {
                throw new ObjectDisposedException("ServerContext");
            }
            else if (this.Initialized == false)
            {
                throw new InvalidOperationException(
                          "The server context has not been completely initialized."
                          );
            }
            else if (impersonating)
            {
                throw new InvalidOperationException("Cannot impersonate again while already impersonating.");
            }
            else if (this.SupportsImpersonate == false)
            {
                throw new InvalidOperationException(
                          "The ServerContext is using a security package that does not support impersonation."
                          );
            }

            handle = new ImpersonationHandle(this);
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                this.ContextHandle.DangerousAddRef(ref gotRef);
            }
            catch (Exception)
            {
                if (gotRef)
                {
                    this.ContextHandle.DangerousRelease();
                    gotRef = false;
                }

                throw;
            }
            finally
            {
                if (gotRef)
                {
                    status = ContextNativeMethods.ImpersonateSecurityContext(
                        ref this.ContextHandle.rawHandle
                        );

                    this.ContextHandle.DangerousRelease();

                    this.impersonating = status == SecurityStatus.OK;
                }
            }

            if (status == SecurityStatus.NoImpersonation)
            {
                throw new SSPIException("Impersonation could not be performed.", status);
            }
            else if (status == SecurityStatus.Unsupported)
            {
                throw new SSPIException("Impersonation is not supported by the security context's Security Support Provider.", status);
            }
            else if (status != SecurityStatus.OK)
            {
                throw new SSPIException("Failed to impersonate the client", status);
            }

            if (this.impersonating && this.impersonationSetsThreadPrinciple)
            {
                SetThreadPrinciple();
            }

            return(handle);
        }
Example #44
0
		bool ProcessHandshakeMessage (TlsBuffer incoming, out SecurityStatus status)
		{
			var handshakeType = (HandshakeType)incoming.ReadByte ();
			#if DEBUG_FULL
			if (EnableDebugging) {
				DebugHelper.WriteLine (">>>> Processing Handshake record ({0})", handshakeType);
				DebugHelper.WriteRemaining ("HANDSHAKE", incoming);
			}
			#endif

			// Read message length
			int length = incoming.ReadInt24 ();
			if (incoming.Remaining < length) {
				cachedFragment = new TlsBuffer (length + 4);
				cachedFragment.Position = incoming.Remaining + 4;
				Buffer.BlockCopy (incoming.Buffer, incoming.Position - 4, cachedFragment.Buffer, 0, cachedFragment.Position);
				incoming.Position += incoming.Remaining;
				status = SecurityStatus.ContinueNeeded;
				return false;
			}

			var buffer = incoming.ReadBuffer (length);
			return negotiationHandler.ProcessHandshakeMessage (handshakeType, buffer, out status);
		}
 internal SafeCloseHandle GetContextToken(out SecurityStatus status)
 {
     if (!this.IsValidContext)
     {
         throw new Win32Exception(-2146893055);
     }
     SafeCloseHandle token = null;
     status = (SecurityStatus) SSPIWrapper.QuerySecurityContextToken(GlobalSSPI.SSPIAuth, this.m_SecurityContext, out token);
     return token;
 }
Example #46
0
        //
        // Performs encryption of an array of buffers, proceeds buffer by buffer, if the individual
        // buffer size exceeds a SSL limit of SecureChannel.MaxDataSize,the buffers are then split into smaller ones.
        // Returns the same array that is encrypted or a new array of encrypted buffers.
        //
        private BufferOffsetSize[] EncryptBuffers(BufferOffsetSize[] buffers, byte[] lastHandshakePayload)
        {
            List <BufferOffsetSize> arrayList = null;
            SecurityStatus          status    = SecurityStatus.OK;

            foreach (BufferOffsetSize buffer in buffers)
            {
                int chunkBytes = Math.Min(buffer.Size, _SslState.MaxDataSize);

                byte[] outBuffer = null;
                int    outSize;

                status = _SslState.EncryptData(buffer.Buffer, buffer.Offset, chunkBytes, ref outBuffer, out outSize);
                if (status != SecurityStatus.OK)
                {
                    break;
                }

                if (chunkBytes != buffer.Size || arrayList != null)
                {
                    if (arrayList == null)
                    {
                        arrayList = new List <BufferOffsetSize>(buffers.Length * (buffer.Size / chunkBytes + 1));
                        if (lastHandshakePayload != null)
                        {
                            arrayList.Add(new BufferOffsetSize(lastHandshakePayload, false));
                        }

                        foreach (BufferOffsetSize oldBuffer in buffers)
                        {
                            if (oldBuffer == buffer)
                            {
                                break;
                            }
                            arrayList.Add(oldBuffer);
                        }
                    }
                    arrayList.Add(new BufferOffsetSize(outBuffer, 0, outSize, false));
                    while ((buffer.Size -= chunkBytes) != 0)
                    {
                        buffer.Offset += chunkBytes;
                        chunkBytes     = Math.Min(buffer.Size, _SslState.MaxDataSize);
                        outBuffer      = null;
                        status         = _SslState.EncryptData(buffer.Buffer, buffer.Offset, chunkBytes, ref outBuffer, out outSize);
                        if (status != SecurityStatus.OK)
                        {
                            break;
                        }
                        arrayList.Add(new BufferOffsetSize(outBuffer, 0, outSize, false));
                    }
                }
                else
                {
                    buffer.Buffer = outBuffer;
                    buffer.Offset = 0;
                    buffer.Size   = outSize;
                }
                if (status != SecurityStatus.OK)
                {
                    break;
                }
            }

            if (status != SecurityStatus.OK)
            {
                //
                ProtocolToken message = new ProtocolToken(null, status);
                throw new IOException(SR.GetString(SR.net_io_encrypt), message.GetException());
            }

            if (arrayList != null)
            {
                buffers = arrayList.ToArray();
            }
            else if (lastHandshakePayload != null)
            {
                BufferOffsetSize[] result = new BufferOffsetSize[buffers.Length + 1];
                Array.Copy(buffers, 0, result, 1, buffers.Length);
                result[0] = new BufferOffsetSize(lastHandshakePayload, false);
                buffers   = result;
            }

            return(buffers);
        }
Example #47
0
 public virtual void onMessage(SecurityStatus message, QuickFix.SessionID session)
 {
     throw new QuickFix.UnsupportedMessageType();
 }
 internal string GetOutgoingDigestBlob(string incomingBlob, string requestMethod, string requestedUri, string realm, bool isClientPreAuth, bool throwOnError, out SecurityStatus statusCode)
 {
     SecurityBuffer[] inputBuffers = null;
     SecurityBuffer outputBuffer = new SecurityBuffer(this.m_TokenSize, isClientPreAuth ? BufferType.Parameters : BufferType.Token);
     bool flag = this.m_SecurityContext == null;
     try
     {
         if (!this.m_IsServer)
         {
             if (!isClientPreAuth)
             {
                 if (incomingBlob != null)
                 {
                     List<SecurityBuffer> list = new List<SecurityBuffer>(5) {
                         new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(incomingBlob), 2),
                         new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(requestMethod), 3),
                         new SecurityBuffer(null, 3),
                         new SecurityBuffer(Encoding.Unicode.GetBytes(this.m_Spn), 0x10)
                     };
                     if (this.m_ChannelBinding != null)
                     {
                         list.Add(new SecurityBuffer(this.m_ChannelBinding));
                     }
                     inputBuffers = list.ToArray();
                 }
                 statusCode = (SecurityStatus) SSPIWrapper.InitializeSecurityContext(GlobalSSPI.SSPIAuth, this.m_CredentialsHandle, ref this.m_SecurityContext, requestedUri, this.m_RequestedContextFlags, Endianness.Network, inputBuffers, outputBuffer, ref this.m_ContextFlags);
             }
             else
             {
                 statusCode = SecurityStatus.OK;
             }
         }
         else
         {
             List<SecurityBuffer> list2 = new List<SecurityBuffer>(6) {
                 (incomingBlob == null) ? new SecurityBuffer(0, BufferType.Token) : new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(incomingBlob), BufferType.Token),
                 (requestMethod == null) ? new SecurityBuffer(0, BufferType.Parameters) : new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(requestMethod), BufferType.Parameters),
                 (requestedUri == null) ? new SecurityBuffer(0, BufferType.Parameters) : new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(requestedUri), BufferType.Parameters),
                 new SecurityBuffer(0, BufferType.Parameters),
                 (realm == null) ? new SecurityBuffer(0, BufferType.Parameters) : new SecurityBuffer(Encoding.Unicode.GetBytes(realm), BufferType.Parameters)
             };
             if (this.m_ChannelBinding != null)
             {
                 list2.Add(new SecurityBuffer(this.m_ChannelBinding));
             }
             inputBuffers = list2.ToArray();
             statusCode = (SecurityStatus) SSPIWrapper.AcceptSecurityContext(GlobalSSPI.SSPIAuth, this.m_CredentialsHandle, ref this.m_SecurityContext, this.m_RequestedContextFlags, Endianness.Network, inputBuffers, outputBuffer, ref this.m_ContextFlags);
             if (statusCode == SecurityStatus.CompleteNeeded)
             {
                 inputBuffers[4] = outputBuffer;
                 statusCode = (SecurityStatus) SSPIWrapper.CompleteAuthToken(GlobalSSPI.SSPIAuth, ref this.m_SecurityContext, inputBuffers);
                 outputBuffer.token = null;
             }
         }
     }
     finally
     {
         if (flag && (this.m_CredentialsHandle != null))
         {
             this.m_CredentialsHandle.Close();
         }
     }
     if ((statusCode & ((SecurityStatus) (-2147483648))) != SecurityStatus.OK)
     {
         this.CloseContext();
         if (throwOnError)
         {
             Win32Exception exception = new Win32Exception((int) statusCode);
             throw exception;
         }
         return null;
     }
     if (flag && (this.m_CredentialsHandle != null))
     {
         SSPIHandleCache.CacheCredential(this.m_CredentialsHandle);
     }
     if (statusCode == SecurityStatus.OK)
     {
         this.m_IsCompleted = true;
     }
     byte[] token = outputBuffer.token;
     string str = null;
     if ((token != null) && (token.Length > 0))
     {
         str = WebHeaderCollection.HeaderEncoding.GetString(token, 0, outputBuffer.size);
     }
     return str;
 }
Example #49
0
 /// <summary>
 /// Returns whether or not the status represents an error.
 /// </summary>
 /// <param name="status"></param>
 /// <returns>True if the status represents an error condition.</returns>
 public static bool IsError(this SecurityStatus status)
 {
     return((uint)status > 0x80000000u);
 }
 /// <summary>
 /// Initializes a new instance of the SSPIException class with the given message and status.
 /// </summary>
 /// <param name="message">A message explaining what part of the system failed.</param>
 /// <param name="errorCode">The error code observed during the failure.</param>
 internal SspiException( string message, SecurityStatus errorCode )
 {
     this.message = message;
     this.errorCode = errorCode;
 }
Example #51
0
 // This only works for context-destroying errors.
 internal static bool IsCredentialFailure(SecurityStatus error)
 {
     return error == SecurityStatus.LogonDenied ||
         error == SecurityStatus.UnknownCredentials ||
         error == SecurityStatus.NoImpersonation ||
         error == SecurityStatus.NoAuthenticatingAuthority ||
         error == SecurityStatus.UntrustedRoot ||
         error == SecurityStatus.CertExpired ||
         error == SecurityStatus.SmartcardLogonRequired ||
         error == SecurityStatus.BadBinding;
 }
Example #52
0
        //
        // Only processing SEC_I_RENEGOTIATE.
        //
        private int ProcessReadErrorCode(SecurityStatus errorCode, byte[] buffer, int offset, int count, byte[] extraBuffer)
        {
            // ERROR - examine what kind
            ProtocolToken message = new ProtocolToken(null, errorCode);

            GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::***Processing an error Status = " + message.Status.ToString());

            if (message.Renegotiate)
            {
                _SslState.ReplyOnReAuthentication(extraBuffer);

                // Loop on read.
                return -1;
            }

            if (message.CloseConnection)
            {
                _SslState.FinishRead(null);
                return 0;
            }

            throw new IOException(SR.net_io_decrypt, message.GetException());
        }
Example #53
0
 public Exception GetException(SecurityStatus status)
 {
     return(new Win32Exception((int)status));
 }
Example #54
0
 /// <summary>
 /// Initializes a new instance of the SSPIException class with the given message and status.
 /// </summary>
 /// <param name="message">A message explaining what part of the system failed.</param>
 /// <param name="errorCode">The error code observed during the failure.</param>
 public SSPIException( string message, SecurityStatus errorCode )
 {
     this.message = message;
     this.errorCode = errorCode;
 }
Example #55
0
        internal static SecurityStatus SafeQueryContextAttribute(
            SafeContextHandle handle,
            ContextQueryAttrib attribute,
            ref byte[] buffer
            )
        {
            bool gotRef = false;

            SecurityStatus status = SecurityStatus.InternalError;

            RuntimeHelpers.PrepareConstrainedRegions();

            int    pointerSize  = System.Environment.Is64BitOperatingSystem ? 8 : 4; //NOTE: update this when 128 bit processors exist
            IntPtr alloc_buffer = Marshal.AllocHGlobal(sizeof(uint) + pointerSize);  //NOTE: this is at most 4 + sizeof(void*) bytes

            //see struct SecPkgContext_SessionKey
            // https://msdn.microsoft.com/en-us/library/windows/desktop/aa380096(v=vs.85).aspx
            try
            {
                handle.DangerousAddRef(ref gotRef);
            }
            catch (Exception)
            {
                if (gotRef)
                {
                    handle.DangerousRelease();
                    gotRef = false;
                    buffer = null;
                }

                throw;
            }
            finally
            {
                if (gotRef)
                {
                    status = ContextNativeMethods.QueryContextAttributes(
                        ref handle.rawHandle,
                        attribute,
                        alloc_buffer
                        );
                    if (status == SecurityStatus.OK)
                    {
                        KeyStruct key = new KeyStruct();

                        Marshal.PtrToStructure(alloc_buffer, key);   // fit to the proper size, read a byte[]

                        byte[] sizedBuffer = new byte[key.size];

                        for (int i = 0; i < key.size; i++)
                        {
                            sizedBuffer[i] = Marshal.ReadByte(key.data, i);
                        }

                        buffer = sizedBuffer;
                    }
                    handle.DangerousRelease();
                }
            }
            Marshal.FreeHGlobal(alloc_buffer);
            return(status);
        }
Example #56
0
 /// <summary>
 /// Initializes a new instance of the SSPIException class from serialization data.
 /// </summary>
 /// <param name="info"></param>
 /// <param name="context"></param>
 protected SSPIException( SerializationInfo info, StreamingContext context )
     : base(info, context)
 {
     this.message = info.GetString( "messsage" );
     this.errorCode = (SecurityStatus)info.GetUInt32( "errorCode" );
 }
Example #57
0
        public bool ProcessHandshakeMessage(HandshakeType type, TlsBuffer incoming, out SecurityStatus status)
        {
            if (HasPendingOutput && type != HandshakeType.HelloRequest)
            {
                throw new TlsException(AlertDescription.InternalError);
            }
            if (!VerifyMessage(type))
            {
                throw new TlsException(AlertDescription.UnexpectedMessage);
            }

            var incomingBuffer = new BufferOffsetSize(incoming.Buffer, incoming.Position - 4, incoming.Remaining + 4);

            var startPosition = incoming.Position - 4;
            var message       = CreateMessage(type, incoming);

            incoming.Position = startPosition;
                        #if FIXME
            incoming.Offset = incoming.Position;
                        #endif

                        #if DEBUG_FULL
            if (Context.EnableDebugging)
            {
                DebugHelper.WriteLine("ProcessMessage: {0} {1} {2}", GetType().Name, Context.IsServer, type);
            }
                        #endif

            var result = HandleMessage(message);

            switch (result)
            {
            case MessageStatus.CredentialsNeeded:
                status = SecurityStatus.CredentialsNeeded;
                return(false);

            case MessageStatus.Finished:
                hasPendingOutput = true;
                if (Context.IsServer)
                {
                    Context.HandshakeParameters.HandshakeMessages.Add(message, incomingBuffer);
                }
                status = SecurityStatus.OK;
                return(true);

            case MessageStatus.IgnoreMessage:
                status = SecurityStatus.ContinueNeeded;
                return(false);

            case MessageStatus.Renegotiate:
                hasPendingOutput = true;
                if (message.Type != HandshakeType.HelloRequest)
                {
                    Context.HandshakeParameters.HandshakeMessages.Add(message, incomingBuffer);
                }
                status = SecurityStatus.Renegotiate;
                return(true);

            case MessageStatus.GenerateOutput:
                hasPendingOutput = true;
                Context.HandshakeParameters.HandshakeMessages.Add(message, incomingBuffer);
                status = SecurityStatus.ContinueNeeded;
                return(true);

            case MessageStatus.ContinueNeeded:
                Context.HandshakeParameters.HandshakeMessages.Add(message, incomingBuffer);
                status = SecurityStatus.ContinueNeeded;
                return(false);

            default:
                throw new InvalidOperationException();
            }
        }
 public Exception GetException(SecurityStatus status)
 {
     // TODO: To be implemented
     throw new Exception("status = " + status);
 }
Example #59
0
        //
        private void StartWriting(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
        {
            if (asyncRequest != null)
            {
                asyncRequest.SetNextRequest(buffer, offset, count, _ResumeAsyncWriteCallback);
            }

            // We loop to this method from the callback
            // If the last chunk was just completed from async callback (count < 0), we complete user request
            if (count >= 0)
            {
                byte[] outBuffer = null;
                if (_PinnableOutputBufferInUse == null)               // The output buffer is not in use
                {
                    if (_PinnableOutputBuffer == null)                // Create one if needed
                    {
                        _PinnableOutputBuffer = s_PinnableWriteBufferCache.AllocateBuffer();
                    }
                    _PinnableOutputBufferInUse = buffer;        // put it in use
                    outBuffer = _PinnableOutputBuffer;
                    if (PinnableBufferCacheEventSource.Log.IsEnabled())
                    {
                        PinnableBufferCacheEventSource.Log.DebugMessage3("In System.Net._SslStream.StartWriting Trying Pinnable", this.GetHashCode(), count, PinnableBufferCacheEventSource.AddressOfByteArray(outBuffer));
                    }
                }
                else
                {
                    if (PinnableBufferCacheEventSource.Log.IsEnabled())
                    {
                        PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.StartWriting BufferInUse", this.GetHashCode(), count);
                    }
                }

                do
                {
                    // request a write IO slot
                    if (_SslState.CheckEnqueueWrite(asyncRequest))
                    {
                        // operation is async and has been queued, return.
                        return;
                    }

                    int            chunkBytes = Math.Min(count, _SslState.MaxDataSize);
                    int            encryptedBytes;
                    SecurityStatus errorCode = _SslState.EncryptData(buffer, offset, chunkBytes, ref outBuffer, out encryptedBytes);
                    if (errorCode != SecurityStatus.OK)
                    {
                        //
                        ProtocolToken message = new ProtocolToken(null, errorCode);
                        throw new IOException(SR.GetString(SR.net_io_encrypt), message.GetException());
                    }

                    if (PinnableBufferCacheEventSource.Log.IsEnabled())
                    {
                        PinnableBufferCacheEventSource.Log.DebugMessage3("In System.Net._SslStream.StartWriting Got Encrypted Buffer",
                                                                         this.GetHashCode(), encryptedBytes, PinnableBufferCacheEventSource.AddressOfByteArray(outBuffer));
                    }
                    if (asyncRequest != null)
                    {
                        // prepare for the next request
                        asyncRequest.SetNextRequest(buffer, offset + chunkBytes, count - chunkBytes, _ResumeAsyncWriteCallback);
                        IAsyncResult ar = _SslState.InnerStream.BeginWrite(outBuffer, 0, encryptedBytes, _WriteCallback, asyncRequest);
                        if (!ar.CompletedSynchronously)
                        {
                            return;
                        }
                        _SslState.InnerStream.EndWrite(ar);
                    }
                    else
                    {
                        _SslState.InnerStream.Write(outBuffer, 0, encryptedBytes);
                    }
                    offset += chunkBytes;
                    count  -= chunkBytes;

                    // release write IO slot
                    _SslState.FinishWrite();
                } while (count != 0);
            }

            if (asyncRequest != null)
            {
                asyncRequest.CompleteUser();
            }

            if (buffer == _PinnableOutputBufferInUse)                // Did we put it in use?
            {
                // Then free it
                _PinnableOutputBufferInUse = null;
                if (PinnableBufferCacheEventSource.Log.IsEnabled())
                {
                    PinnableBufferCacheEventSource.Log.DebugMessage1("In System.Net._SslStream.StartWriting Freeing buffer.", this.GetHashCode());
                }
            }
        }
        // Token: 0x0600074D RID: 1869 RVA: 0x00027EFC File Offset: 0x000260FC
        public void Execute()
        {
            AirSyncDiagnostics.TraceDebug(ExTraceGlobals.RequestsTracer, this, "DocumentLibrary Fetch command received. Processing request...");
            Uri uri = null;

            try
            {
                uri = new Uri(this.linkId);
            }
            catch (UriFormatException innerException)
            {
                AirSyncDiagnostics.TraceDebug(ExTraceGlobals.RequestsTracer, this, string.Format(CultureInfo.InvariantCulture, "ItemOperationsFetchProvider: Bad document Uri {0} was specified!", new object[]
                {
                    this.linkId
                }));
                this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "BadLinkInDocFetch");
                throw new AirSyncPermanentException(StatusCode.Sync_ProtocolError, innerException, false);
            }
            AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, this, "Processing Fetch command with Uri {0}.", uri.AbsoluteUri);
            if (!DocumentLibraryUtility.IsTrustedProtocol(uri.Scheme))
            {
                AirSyncDiagnostics.TraceDebug(ExTraceGlobals.RequestsTracer, this, string.Format(CultureInfo.InvariantCulture, "ItemOperationsFetchProvider: untrusted protocol: {0}!", new object[]
                {
                    uri.Scheme
                }));
                this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "BadProtocolInDocFetch");
                throw new AirSyncPermanentException(StatusCode.Sync_Retry, false);
            }
            if (!DocumentLibraryUtility.IsInternalUri(uri))
            {
                AirSyncDiagnostics.TraceDebug(ExTraceGlobals.RequestsTracer, this, string.Format(CultureInfo.InvariantCulture, "ItemOperationsFetchProvider: Uri must be internal: {0}!", new object[]
                {
                    uri.Host
                }));
                this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "ExternalProtocolInDocFetch");
                throw new AirSyncPermanentException(StatusCode.Sync_Retry, false);
            }
            AuthenticationContext authenticationContext = new AuthenticationContext();

            try
            {
                IPrincipal principal;
                if (this.userPassword == null)
                {
                    principal = this.user.WindowsPrincipal;
                    if (principal == null)
                    {
                        if (GlobalSettings.EnableCredentialRequest && this.user.Context.Request.Version >= 121)
                        {
                            this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "NeedPromptForCredsToProxy2");
                            throw new AirSyncPermanentException(StatusCode.ItemOperations_CredentialsRequired, false);
                        }
                        this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "NeedCredsToProxy2");
                        throw new AirSyncPermanentException(HttpStatusCode.Forbidden, StatusCode.AccessDenied, null, false);
                    }
                }
                else
                {
                    SecurityStatus securityStatus = authenticationContext.LogonUser(this.userName, this.userPassword);
                    this.userPassword.Dispose();
                    this.userPassword = null;
                    if (securityStatus != SecurityStatus.OK)
                    {
                        AirSyncDiagnostics.TraceDebug(ExTraceGlobals.RequestsTracer, this, string.Format(CultureInfo.InvariantCulture, "ItemOperationsFetchProvider: Authentication failed with status {0}.", new object[]
                        {
                            securityStatus
                        }));
                        this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, string.Format(CultureInfo.InvariantCulture, "AuthenticationErrorStatus{0}", new object[]
                        {
                            securityStatus
                        }));
                        throw new AirSyncPermanentException(HttpStatusCode.OK, StatusCode.Sync_ServerError, null, false);
                    }
                    principal = new WindowsPrincipal(authenticationContext.Identity);
                }
                ClassifyResult classifyResult = LinkClassifier.ClassifyLinks(principal, new Uri[]
                {
                    uri
                })[0];
                if (classifyResult.Error != ClassificationError.None)
                {
                    AirSyncDiagnostics.TraceDebug <string, ClassificationError>(ExTraceGlobals.RequestsTracer, this, "The LinkClassifier failed to classify the link {0}, returned {1}", this.linkId, classifyResult.Error);
                    switch (classifyResult.Error)
                    {
                    case ClassificationError.ConnectionFailed:
                        this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "LinkClassConnFailedInDocFetch");
                        throw new AirSyncPermanentException(HttpStatusCode.OK, StatusCode.Sync_Conflict, null, false);

                    case ClassificationError.AccessDenied:
                        this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "LinkClassDeniedInDocFetch");
                        throw new AirSyncPermanentException(HttpStatusCode.OK, StatusCode.Sync_ServerError, null, false);

                    case ClassificationError.ObjectNotFound:
                        this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "LinkClassNotFoundInDocFetch");
                        throw new AirSyncPermanentException(HttpStatusCode.OK, StatusCode.Sync_ClientServerConversion, null, false);

                    case ClassificationError.UriTypeNotSupported:
                    case ClassificationError.InvalidUri:
                        this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "LinkClassBadUriInDocFetch");
                        throw new AirSyncPermanentException(HttpStatusCode.OK, StatusCode.Sync_ProtocolError, null, false);
                    }
                    this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "LinkClassFailureInDocFetch");
                    throw new AirSyncPermanentException(StatusCode.Sync_InvalidSyncKey, false);
                }
                IDocument         document          = null;
                UncSession        uncSession        = null;
                SharepointSession sharepointSession = null;
                if ((classifyResult.UriFlags & UriFlags.UncDocument) == UriFlags.UncDocument)
                {
                    if (!DocumentLibraryUtility.IsUncAccessEnabled(this.user))
                    {
                        this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "AccessDeniedInDocFetch");
                        throw new AirSyncPermanentException(StatusCode.Sync_Retry, false);
                    }
                    if (DocumentLibraryUtility.IsBlockedHostName(uri.Host))
                    {
                        this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "HostBlockedInDocFetch");
                        throw new AirSyncPermanentException(StatusCode.Sync_Retry, false);
                    }
                    uncSession = UncSession.Open(classifyResult.ObjectId, principal);
                }
                else
                {
                    if ((classifyResult.UriFlags & UriFlags.SharepointDocument) != UriFlags.SharepointDocument)
                    {
                        AirSyncDiagnostics.TraceDebug <string, UriFlags>(ExTraceGlobals.RequestsTracer, this, "The Uri {0} of type {1} is not supported for Fetch", this.linkId, classifyResult.UriFlags);
                        this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "BadLinkInDocFetch2");
                        throw new AirSyncPermanentException(StatusCode.Sync_ProtocolError, false);
                    }
                    if (!DocumentLibraryUtility.IsWssAccessEnabled(this.user))
                    {
                        this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "WssDeniedInDocFetch");
                        throw new AirSyncPermanentException(StatusCode.Sync_Retry, false);
                    }
                    if (DocumentLibraryUtility.IsBlockedHostName(uri.Host))
                    {
                        this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "HostBlockedInDocFetch2");
                        throw new AirSyncPermanentException(StatusCode.Sync_Retry, false);
                    }
                    this.user.Context.ProtocolLogger.IncrementValue(ProtocolLoggerData.SharePointDocs);
                    sharepointSession = SharepointSession.Open(classifyResult.ObjectId, principal);
                }
                try
                {
                    if (uncSession != null)
                    {
                        AirSyncDiagnostics.TraceDebug(ExTraceGlobals.RequestsTracer, this, "Reading UNC document...");
                        document = UncDocument.Read(uncSession, classifyResult.ObjectId);
                    }
                    else
                    {
                        AirSyncDiagnostics.TraceDebug(ExTraceGlobals.RequestsTracer, this, "Reading Sharepoint document...");
                        AirSyncDiagnostics.Assert(sharepointSession != null);
                        document = SharepointDocument.Read(sharepointSession, classifyResult.ObjectId);
                    }
                }
                catch (ObjectNotFoundException innerException2)
                {
                    this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "NotFoundInDocFetch");
                    throw new AirSyncPermanentException(StatusCode.Sync_ClientServerConversion, innerException2, false);
                }
                catch (AccessDeniedException innerException3)
                {
                    this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "AccessDeniedInDocFetch2");
                    throw new AirSyncPermanentException(StatusCode.Sync_ServerError, innerException3, false);
                }
                this.documentSize = (int)document.Size;
                if (this.documentSize == 0)
                {
                    AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, this, "The file {0} was found to be empty!", this.linkId);
                    this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "EmptyDocInDocFetch");
                    throw new AirSyncPermanentException(HttpStatusCode.OK, StatusCode.Sync_NotificationGUID, null, false);
                }
                object obj = document.TryGetProperty(DocumentLibraryItemSchema.LastModifiedDate);
                if (obj is PropertyError)
                {
                    this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "GeneralErrorInDocFetch");
                    throw new AirSyncPermanentException(StatusCode.Sync_InvalidSyncKey, false);
                }
                ExDateTime exDateTime;
                if (obj is DateTime)
                {
                    exDateTime = new ExDateTime(ExTimeZone.UtcTimeZone, (DateTime)obj);
                }
                else
                {
                    exDateTime = (ExDateTime)obj;
                }
                this.version = exDateTime.ToString("yyyy-MM-dd\\THH:mm:ss.fff\\Z", CultureInfo.InvariantCulture);
                if (this.rangeSpecified && this.minRange >= this.documentSize)
                {
                    AirSyncDiagnostics.TraceDebug <int, int>(ExTraceGlobals.RequestsTracer, this, "The minimum range specified {0} is greater than the document size {1}", this.minRange, this.documentSize);
                    this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "BadMinSizeInDocFetch");
                    throw new AirSyncPermanentException(HttpStatusCode.OK, StatusCode.Sync_ObjectNotFound, null, false);
                }
                using (Stream document2 = document.GetDocument())
                {
                    int num;
                    if (this.rangeSpecified)
                    {
                        num = this.maxRange - this.minRange + 1;
                    }
                    else
                    {
                        num = this.documentSize;
                    }
                    if (uncSession != null)
                    {
                        this.user.Context.ProtocolLogger.IncrementValue(ProtocolLoggerData.UNCFiles);
                        this.user.Context.ProtocolLogger.IncrementValueBy(ProtocolLoggerData.UNCBytes, num);
                    }
                    if (sharepointSession != null)
                    {
                        this.user.Context.ProtocolLogger.IncrementValue(ProtocolLoggerData.SharePointDocs);
                        this.user.Context.ProtocolLogger.IncrementValueBy(ProtocolLoggerData.SharePointBytes, num);
                    }
                    this.outStream = new MemoryStream(num);
                    if (num > GlobalSettings.MaxDocumentDataSize)
                    {
                        this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "DocTooBigInDocFetch");
                        throw new AirSyncPermanentException(StatusCode.Sync_NotificationsNotProvisioned, false);
                    }
                    try
                    {
                        StreamHelper.CopyStream(document2, this.outStream, this.minRange, num);
                    }
                    catch (IOException innerException4)
                    {
                        this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "IOErrorInDocFetch");
                        throw new AirSyncPermanentException(StatusCode.Sync_FolderHierarchyRequired, innerException4, false);
                    }
                }
            }
            catch (UnknownErrorException innerException5)
            {
                this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "IOErrorInDocFetch2");
                throw new AirSyncPermanentException(StatusCode.Sync_FolderHierarchyRequired, innerException5, false);
            }
            catch (DocumentModifiedException innerException6)
            {
                this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "IOErrorInDocFetch3");
                throw new AirSyncPermanentException(StatusCode.Sync_FolderHierarchyRequired, innerException6, false);
            }
            catch (DocumentStreamAccessDeniedException innerException7)
            {
                this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "AccessDeniedInDocFetch3");
                throw new AirSyncPermanentException(StatusCode.Sync_ServerError, innerException7, false);
            }
            catch (ObjectMovedOrDeletedException innerException8)
            {
                this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "NotFoundInDocFetch2");
                throw new AirSyncPermanentException(StatusCode.Sync_ClientServerConversion, innerException8, false);
            }
            catch (DocumentLibraryException innerException9)
            {
                this.user.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "GeneralErrorInDocFetch2");
                throw new AirSyncPermanentException(StatusCode.Sync_InvalidSyncKey, innerException9, false);
            }
            finally
            {
                if (authenticationContext != null)
                {
                    authenticationContext.Dispose();
                    authenticationContext = null;
                }
            }
        }