// this method is only called as part of an assert internal bool IsEqualTo(object compObject) { if ((object)compObject == null) { return(false); } if ((object)this == (object)compObject) { return(true); } NetworkCredential compCred = compObject as NetworkCredential; if ((object)compCred == null) { return(false); } #if FEATURE_PAL return(InternalGetUserName() == compCred.InternalGetUserName() && InternalGetPassword() == compCred.InternalGetPassword() && InternalGetDomain() == compCred.InternalGetDomain()); #else //!FEATURE_PAL return(InternalGetUserName() == compCred.InternalGetUserName() && InternalGetDomain() == compCred.InternalGetDomain() && UnsafeNclNativeMethods.SecureStringHelper.AreEqualValues(InternalGetSecurePassword(), compCred.InternalGetSecurePassword())); #endif //!FEATURE_PAL }
internal bool IsEqualTo(object compObject) { if ((object)compObject == null) { return(false); } if ((object)this == (object)compObject) { return(true); } NetworkCredential compCred = compObject as NetworkCredential; if ((object)compCred == null) { return(false); } return(InternalGetUserName() == compCred.InternalGetUserName() && InternalGetPassword() == compCred.InternalGetPassword() && InternalGetDomain() == compCred.InternalGetDomain()); }
private Authorization Lookup(HttpWebRequest httpWebRequest, ICredentials credentials) { GlobalLog.Print("BasicClient::Lookup(): ChallengedUri:" + httpWebRequest.ChallengedUri.ToString()); NetworkCredential NC = credentials.GetCredential(httpWebRequest.ChallengedUri, Signature); GlobalLog.Print("BasicClient::Lookup() GetCredential() returns:" + ValidationHelper.ToString(NC)); if (NC == null) { return(null); } ICredentialPolicy policy = AuthenticationManager.CredentialPolicy; if (policy != null && !policy.ShouldSendCredential(httpWebRequest.ChallengedUri, httpWebRequest, NC, this)) { return(null); } string username = NC.InternalGetUserName(); string domain = NC.InternalGetDomain(); if (ValidationHelper.IsBlankString(username)) { return(null); } string rawString = ((!ValidationHelper.IsBlankString(domain)) ? (domain + "\\") : "") + username + ":" + NC.InternalGetPassword(); // The response is an "Authorization:" header where the value is // the text "Basic" followed by BASE64 encoded (as defined by RFC1341) value byte[] bytes = EncodingRightGetBytes(rawString); string responseHeader = BasicClient.AuthType + " " + Convert.ToBase64String(bytes); return(new Authorization(responseHeader, true)); }
private void Initialize(bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, System.Security.Authentication.ExtendedProtection.ChannelBinding channelBinding) { this.m_TokenSize = SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPIAuth, package, true).MaxToken; this.m_IsServer = isServer; this.m_Spn = spn; this.m_SecurityContext = null; this.m_RequestedContextFlags = requestedContextFlags; this.m_Package = package; this.m_ChannelBinding = channelBinding; if (credential is SystemNetworkCredential) { this.m_CredentialsHandle = SSPIWrapper.AcquireDefaultCredential(GlobalSSPI.SSPIAuth, package, this.m_IsServer ? CredentialUse.Inbound : CredentialUse.Outbound); this.m_UniqueUserId = "/S"; } else { string userName = credential.InternalGetUserName(); string domain = credential.InternalGetDomain(); AuthIdentity authdata = new AuthIdentity(userName, credential.InternalGetPassword(), ((package == "WDigest") && ((domain == null) || (domain.Length == 0))) ? null : domain); this.m_UniqueUserId = domain + "/" + userName + "/U"; this.m_CredentialsHandle = SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPIAuth, package, this.m_IsServer ? CredentialUse.Inbound : CredentialUse.Outbound, ref authdata); } }
// This method is only called as part of an assert internal bool IsEqualTo(object compObject) { if ((object)compObject == null) { return(false); } if ((object)this == (object)compObject) { return(true); } NetworkCredential compCred = compObject as NetworkCredential; if ((object)compCred == null) { return(false); } return(InternalGetUserName() == compCred.InternalGetUserName() && InternalGetDomain() == compCred.InternalGetDomain() && string.Equals(_password, compCred._password, StringComparison.Ordinal)); }
private Authorization Lookup(HttpWebRequest httpWebRequest, ICredentials credentials) { NetworkCredential credential = credentials.GetCredential(httpWebRequest.ChallengedUri, Signature); if (credential == null) { return(null); } ICredentialPolicy credentialPolicy = AuthenticationManager.CredentialPolicy; if ((credentialPolicy != null) && !credentialPolicy.ShouldSendCredential(httpWebRequest.ChallengedUri, httpWebRequest, credential, this)) { return(null); } string userName = credential.InternalGetUserName(); string domain = credential.InternalGetDomain(); if (ValidationHelper.IsBlankString(userName)) { return(null); } byte[] inArray = EncodingRightGetBytes((!ValidationHelper.IsBlankString(domain) ? (domain + @"\") : "") + userName + ":" + credential.InternalGetPassword()); return(new Authorization("Basic " + Convert.ToBase64String(inArray), true)); }
// private void Initialize(bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, ChannelBinding channelBinding) { GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::.ctor() package:" + ValidationHelper.ToString(package) + " spn:" + ValidationHelper.ToString(spn) + " flags :" + requestedContextFlags.ToString()); m_TokenSize = SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPIAuth, package, true).MaxToken; m_IsServer = isServer; m_Spn = spn; m_SecurityContext = null; m_RequestedContextFlags = requestedContextFlags; m_Package = package; m_ChannelBinding = channelBinding; GlobalLog.Print("Peer SPN-> '" + m_Spn + "'"); // // check if we're using DefaultCredentials // if (credential is SystemNetworkCredential) { GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::.ctor(): using DefaultCredentials"); m_CredentialsHandle = SSPIWrapper.AcquireDefaultCredential( GlobalSSPI.SSPIAuth, package, (m_IsServer? CredentialUse.Inbound: CredentialUse.Outbound)); m_UniqueUserId = "/S"; // save off for unique connection marking ONLY used by HTTP client } else if (ComNetOS.IsWin7orLater) { unsafe { SafeSspiAuthDataHandle authData = null; try { SecurityStatus result = UnsafeNclNativeMethods.SspiHelper.SspiEncodeStringsAsAuthIdentity( credential.InternalGetUserName(), credential.InternalGetDomain(), credential.InternalGetPassword(), out authData); if (result != SecurityStatus.OK) { if (Logging.On) Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_operation_failed_with_error, "SspiEncodeStringsAsAuthIdentity()", String.Format(CultureInfo.CurrentCulture, "0x{0:X}", (int)result))); throw new Win32Exception((int)result); } m_CredentialsHandle = SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPIAuth, package, (m_IsServer ? CredentialUse.Inbound : CredentialUse.Outbound), ref authData); } finally { if (authData != null) { authData.Close(); } } } } else { // // we're not using DefaultCredentials, we need a // AuthIdentity struct to contain credentials // SECREVIEW: // we'll save username/domain in temp strings, to avoid decrypting multiple times. // password is only used once // string username = credential.InternalGetUserName(); string domain = credential.InternalGetDomain(); // ATTN: // NetworkCredential class does not differentiate between null and "" but SSPI packages treat these cases differently // For NTLM we want to keep "" for Wdigest.Dll we should use null. AuthIdentity authIdentity = new AuthIdentity(username, credential.InternalGetPassword(), (object)package == (object)NegotiationInfoClass.WDigest && (domain == null || domain.Length == 0)? null: domain); m_UniqueUserId = domain + "/" + username + "/U"; // save off for unique connection marking ONLY used by HTTP client GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::.ctor(): using authIdentity:" + authIdentity.ToString()); m_CredentialsHandle = SSPIWrapper.AcquireCredentialsHandle( GlobalSSPI.SSPIAuth, package, (m_IsServer? CredentialUse.Inbound: CredentialUse.Outbound), ref authIdentity ); } }
// // CONSIDER V.NEXT // creating a static hashtable for server nonces and keep track of nonce count // internal static Authorization Authenticate(HttpDigestChallenge digestChallenge, NetworkCredential NC, string spn, ChannelBinding binding) { string username = NC.InternalGetUserName(); if (ValidationHelper.IsBlankString(username)) { return null; } string password = NC.InternalGetPassword(); bool upgraded = IsUpgraded(digestChallenge.Nonce, binding); if (upgraded) { digestChallenge.ServiceName = spn; digestChallenge.ChannelBinding = hashChannelBinding(binding, digestChallenge.MD5provider); } if (digestChallenge.QopPresent) { if (digestChallenge.ClientNonce==null || digestChallenge.Stale) { GlobalLog.Print("HttpDigest::Authenticate() QopPresent:True, need new nonce. digestChallenge.ClientNonce:" + ValidationHelper.ToString(digestChallenge.ClientNonce) + " digestChallenge.Stale:" + digestChallenge.Stale.ToString()); if (upgraded) { digestChallenge.ClientNonce = createUpgradedNonce(digestChallenge); } else { digestChallenge.ClientNonce = createNonce(32); } digestChallenge.NonceCount = 1; } else { GlobalLog.Print("HttpDigest::Authenticate() QopPresent:True, reusing nonce. digestChallenge.NonceCount:" + digestChallenge.NonceCount.ToString()); digestChallenge.NonceCount++; } } StringBuilder authorization = new StringBuilder(); // // look at username & password, if it's not ASCII we need to attempt some // kind of encoding because we need to calculate the hash on byte[] // Charset usernameCharset = DetectCharset(username); if (!digestChallenge.UTF8Charset && usernameCharset==Charset.UTF8) { GlobalLog.Print("HttpDigest::Authenticate() can't authenticate with UNICODE username. failing auth."); return null; } Charset passwordCharset = DetectCharset(password); if (!digestChallenge.UTF8Charset && passwordCharset==Charset.UTF8) { GlobalLog.Print("HttpDigest::Authenticate() can't authenticate with UNICODE password. failing auth."); return null; } if (digestChallenge.UTF8Charset) { // on the wire always use UTF8 when the server supports it authorization.Append(pair(DA_charset, "utf-8", false)); authorization.Append(","); if (usernameCharset==Charset.UTF8) { username = CharsetEncode(username, Charset.UTF8); authorization.Append(pair(DA_username, username, true)); authorization.Append(","); } else { authorization.Append(pair(DA_username, CharsetEncode(username, Charset.UTF8), true)); authorization.Append(","); username = CharsetEncode(username, usernameCharset); } } else { // otherwise UTF8 is not required username = CharsetEncode(username, usernameCharset); authorization.Append(pair(DA_username, username, true)); authorization.Append(","); } password = CharsetEncode(password, passwordCharset); // no special encoding for the realm since we're just going to echo it back (encoding must have happened on the server). authorization.Append(pair(DA_realm, digestChallenge.Realm, true)); authorization.Append(","); authorization.Append(pair(DA_nonce, digestChallenge.Nonce, true)); authorization.Append(","); authorization.Append(pair(DA_uri, digestChallenge.Uri, true)); if (digestChallenge.QopPresent) { if (digestChallenge.Algorithm!=null) { // consider: should we default to "MD5" here? IE does authorization.Append(","); authorization.Append(pair(DA_algorithm, digestChallenge.Algorithm, true)); // IE sends quotes - IIS needs them } authorization.Append(","); authorization.Append(pair(DA_cnonce, digestChallenge.ClientNonce, true)); authorization.Append(","); authorization.Append(pair(DA_nc, digestChallenge.NonceCount.ToString("x8", NumberFormatInfo.InvariantInfo), false)); // RAID#47397 // send only the QualityOfProtection we're using // since we support only "auth" that's what we will send out authorization.Append(","); authorization.Append(pair(DA_qop, SupportedQuality, true)); // IE sends quotes - IIS needs them if (upgraded) { authorization.Append(","); authorization.Append(pair(DA_hasheddirs, HashedDirs, true)); authorization.Append(","); authorization.Append(pair(DA_servicename, digestChallenge.ServiceName, true)); authorization.Append(","); authorization.Append(pair(DA_channelbinding, digestChallenge.ChannelBinding, true)); } } // warning: this must be computed here string responseValue = HttpDigest.responseValue(digestChallenge, username, password); if (responseValue==null) { return null; } authorization.Append(","); authorization.Append(pair(DA_response, responseValue, true)); // IE sends quotes - IIS needs them if (digestChallenge.Opaque!=null) { authorization.Append(","); authorization.Append(pair(DA_opaque, digestChallenge.Opaque, true)); } GlobalLog.Print("HttpDigest::Authenticate() digestChallenge.Stale:" + digestChallenge.Stale.ToString()); // completion is decided in Update() Authorization finalAuthorization = new Authorization(DigestClient.AuthType + " " + authorization.ToString(), false); return finalAuthorization; }
private Authorization DoAuthenticate(string challenge, WebRequest webRequest, ICredentials credentials, bool preAuthenticate) { GlobalLog.Print("KerberosClient::DoAuthenticate() challenge:[" + ValidationHelper.ToString(challenge) + "] webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " preAuthenticate:" + preAuthenticate.ToString()); GlobalLog.Assert(credentials != null, "KerberosClient::DoAuthenticate()|credentials == null"); if (credentials == null) { return(null); } HttpWebRequest httpWebRequest = webRequest as HttpWebRequest; GlobalLog.Assert(httpWebRequest != null, "KerberosClient::DoAuthenticate()|httpWebRequest == null"); GlobalLog.Assert(httpWebRequest.ChallengedUri != null, "KerberosClient::DoAuthenticate()|httpWebRequest.ChallengedUri == null"); NTAuthentication authSession = null; string incoming = null; if (!preAuthenticate) { int index = AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature); if (index < 0) { return(null); } int blobBegin = index + SignatureSize; // // there may be multiple challenges. If the next character after the // package name is not a comma then it is challenge data // if (challenge.Length > blobBegin && challenge[blobBegin] != ',') { ++blobBegin; } else { index = -1; } if (index >= 0 && challenge.Length > blobBegin) { // Strip other modules information in case of multiple challenges // i.e do not take ", NTLM" as part of the following Negotiate blob // Negotiate TlRMTVNTUAACAAAADgAOADgAAAA1wo ... MAbwBmAHQALgBjAG8AbQAAAAAA,NTLM index = challenge.IndexOf(',', blobBegin); if (index != -1) { incoming = challenge.Substring(blobBegin, index - blobBegin); } else { incoming = challenge.Substring(blobBegin); } } authSession = httpWebRequest.CurrentAuthenticationState.GetSecurityContext(this); GlobalLog.Print("KerberosClient::DoAuthenticate() key:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " retrieved authSession:" + ValidationHelper.HashString(authSession)); } if (authSession == null) { NetworkCredential NC = credentials.GetCredential(httpWebRequest.ChallengedUri, Signature); GlobalLog.Print("KerberosClient::DoAuthenticate() GetCredential() returns:" + ValidationHelper.ToString(NC)); if (NC == null || (!(NC is SystemNetworkCredential) && NC.InternalGetUserName().Length == 0)) { return(null); } ICredentialPolicy policy = AuthenticationManager.CredentialPolicy; if (policy != null && !policy.ShouldSendCredential(httpWebRequest.ChallengedUri, httpWebRequest, NC, this)) { return(null); } SpnToken spn = httpWebRequest.CurrentAuthenticationState.GetComputeSpn(httpWebRequest); GlobalLog.Print("KerberosClient::Authenticate() ChallengedSpn:" + ValidationHelper.ToString(spn)); ChannelBinding binding = null; if (httpWebRequest.CurrentAuthenticationState.TransportContext != null) { binding = httpWebRequest.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint); } authSession = new NTAuthentication( AuthType, NC, spn, httpWebRequest, binding); GlobalLog.Print("KerberosClient::DoAuthenticate() setting SecurityContext for:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " to authSession:" + ValidationHelper.HashString(authSession)); httpWebRequest.CurrentAuthenticationState.SetSecurityContext(authSession, this); } string clientResponse = authSession.GetOutgoingBlob(incoming); if (clientResponse == null) { return(null); } return(new Authorization(AuthType + " " + clientResponse, authSession.IsCompleted, string.Empty, authSession.IsMutualAuthFlag)); }
private Authorization DoAuthenticate(string challenge, WebRequest webRequest, ICredentials credentials, bool preAuthenticate) { if (credentials == null) { return(null); } HttpWebRequest request = webRequest as HttpWebRequest; NTAuthentication securityContext = null; string incomingBlob = null; if (!preAuthenticate) { int index = AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature); if (index < 0) { return(null); } int startIndex = index + SignatureSize; if ((challenge.Length > startIndex) && (challenge[startIndex] != ',')) { startIndex++; } else { index = -1; } if ((index >= 0) && (challenge.Length > startIndex)) { index = challenge.IndexOf(',', startIndex); if (index != -1) { incomingBlob = challenge.Substring(startIndex, index - startIndex); } else { incomingBlob = challenge.Substring(startIndex); } } securityContext = request.CurrentAuthenticationState.GetSecurityContext(this); } if (securityContext == null) { NetworkCredential credential = credentials.GetCredential(request.ChallengedUri, Signature); string str2 = string.Empty; if ((credential == null) || (!(credential is SystemNetworkCredential) && ((str2 = credential.InternalGetUserName()).Length == 0))) { return(null); } if (((str2.Length + credential.InternalGetPassword().Length) + credential.InternalGetDomain().Length) > 0x20f) { return(null); } ICredentialPolicy credentialPolicy = AuthenticationManager.CredentialPolicy; if ((credentialPolicy != null) && !credentialPolicy.ShouldSendCredential(request.ChallengedUri, request, credential, this)) { return(null); } string computeSpn = request.CurrentAuthenticationState.GetComputeSpn(request); ChannelBinding channelBinding = null; if (request.CurrentAuthenticationState.TransportContext != null) { channelBinding = request.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint); } securityContext = new NTAuthentication("NTLM", credential, computeSpn, request, channelBinding); request.CurrentAuthenticationState.SetSecurityContext(securityContext, this); } string outgoingBlob = securityContext.GetOutgoingBlob(incomingBlob); if (outgoingBlob == null) { return(null); } bool unsafeOrProxyAuthenticatedConnectionSharing = request.UnsafeOrProxyAuthenticatedConnectionSharing; if (unsafeOrProxyAuthenticatedConnectionSharing) { request.LockConnection = true; } request.NtlmKeepAlive = incomingBlob == null; return(AuthenticationManager.GetGroupAuthorization(this, "NTLM " + outgoingBlob, securityContext.IsCompleted, securityContext, unsafeOrProxyAuthenticatedConnectionSharing, false)); }
private Authorization DoAuthenticate(string challenge, WebRequest webRequest, ICredentials credentials, bool preAuthenticate) { GlobalLog.Print("NegotiateClient::DoAuthenticate() challenge:[" + ValidationHelper.ToString(challenge) + "] webRequest#" + ValidationHelper.HashString(webRequest) + " credentials#" + ValidationHelper.HashString(credentials) + " preAuthenticate:" + preAuthenticate.ToString()); GlobalLog.Assert(credentials != null, "NegotiateClient::DoAuthenticate()|credentials == null"); if (credentials == null) { return(null); } HttpWebRequest httpWebRequest = webRequest as HttpWebRequest; GlobalLog.Assert(httpWebRequest != null, "NegotiateClient::DoAuthenticate()|httpWebRequest == null"); GlobalLog.Assert(httpWebRequest.ChallengedUri != null, "NegotiateClient::DoAuthenticate()|httpWebRequest.ChallengedUri == null"); NTAuthentication authSession = null; string incoming = null; bool useNego2 = false; // In case of pre-auth we always use "Negotiate", never "Nego2". if (!preAuthenticate) { int index = GetSignatureIndex(challenge, out useNego2); if (index < 0) { return(null); } int blobBegin = index + (useNego2 ? nego2Signature.Length : negotiateSignature.Length); // // there may be multiple challenges. If the next character after the // package name is not a comma then it is challenge data // if (challenge.Length > blobBegin && challenge[blobBegin] != ',') { ++blobBegin; } else { index = -1; } if (index >= 0 && challenge.Length > blobBegin) { // Strip other modules information in case of multiple challenges // i.e do not take ", NTLM" as part of the following Negotiate blob // Negotiate TlRMTVNTUAACAAAADgAOADgAAAA1wo ... MAbwBmAHQALgBjAG8AbQAAAAAA,NTLM index = challenge.IndexOf(',', blobBegin); if (index != -1) { incoming = challenge.Substring(blobBegin, index - blobBegin); } else { incoming = challenge.Substring(blobBegin); } } authSession = httpWebRequest.CurrentAuthenticationState.GetSecurityContext(this); GlobalLog.Print("NegotiateClient::DoAuthenticate() key:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " retrieved authSession:" + ValidationHelper.HashString(authSession)); } if (authSession == null) { // Credentials are always set for "Negotiate", never for "Nego2". A customer shouldn't even know // about "Nego2". NetworkCredential NC = credentials.GetCredential(httpWebRequest.ChallengedUri, negotiateSignature); GlobalLog.Print("NegotiateClient::DoAuthenticate() GetCredential() returns:" + ValidationHelper.ToString(NC)); string username = string.Empty; if (NC == null || (!(NC is SystemNetworkCredential) && (username = NC.InternalGetUserName()).Length == 0)) { return(null); } ICredentialPolicy policy = AuthenticationManager.CredentialPolicy; if (policy != null && !policy.ShouldSendCredential(httpWebRequest.ChallengedUri, httpWebRequest, NC, this)) { return(null); } SpnToken spn = httpWebRequest.CurrentAuthenticationState.GetComputeSpn(httpWebRequest); GlobalLog.Print("NegotiateClient::Authenticate() ChallengedSpn:" + ValidationHelper.ToString(spn)); ChannelBinding binding = null; if (httpWebRequest.CurrentAuthenticationState.TransportContext != null) { binding = httpWebRequest.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint); } authSession = new NTAuthentication( AuthType, NC, spn, httpWebRequest, binding); GlobalLog.Print("NegotiateClient::DoAuthenticate() setting SecurityContext for:" + ValidationHelper.HashString(httpWebRequest.CurrentAuthenticationState) + " to authSession:" + ValidationHelper.HashString(authSession)); httpWebRequest.CurrentAuthenticationState.SetSecurityContext(authSession, this); } string clientResponse = authSession.GetOutgoingBlob(incoming); if (clientResponse == null) { return(null); } bool canShareConnection = httpWebRequest.UnsafeOrProxyAuthenticatedConnectionSharing; if (canShareConnection) { httpWebRequest.LockConnection = true; } // this is the first leg of an NTLM handshake, // set the NtlmKeepAlive override *STRICTLY* only in this case. httpWebRequest.NtlmKeepAlive = incoming == null && authSession.IsValidContext && !authSession.IsKerberos; // If we received a "Nego2" header value from the server, we'll respond with "Nego2" in the "Authorization" // header. If the server sent a "Negotiate" header value or if pre-authenticate is used (i.e. the auth blob // is sent with the first request), we send "Negotiate" in the "Authorization" header. return(AuthenticationManager.GetGroupAuthorization(this, (useNego2 ? nego2Header : negotiateHeader) + " " + clientResponse, authSession.IsCompleted, authSession, canShareConnection, authSession.IsKerberos)); }
private Authorization DoAuthenticate(string challenge, WebRequest webRequest, ICredentials credentials, bool preAuthenticate) { if (credentials == null) { return(null); } HttpWebRequest request = webRequest as HttpWebRequest; NTAuthentication securityContext = null; string incomingBlob = null; bool flag = false; if (!preAuthenticate) { int signatureIndex = GetSignatureIndex(challenge, out flag); if (signatureIndex < 0) { return(null); } int startIndex = signatureIndex + (flag ? "nego2".Length : "negotiate".Length); if ((challenge.Length > startIndex) && (challenge[startIndex] != ',')) { startIndex++; } else { signatureIndex = -1; } if ((signatureIndex >= 0) && (challenge.Length > startIndex)) { signatureIndex = challenge.IndexOf(',', startIndex); if (signatureIndex != -1) { incomingBlob = challenge.Substring(startIndex, signatureIndex - startIndex); } else { incomingBlob = challenge.Substring(startIndex); } } securityContext = request.CurrentAuthenticationState.GetSecurityContext(this); } if (securityContext == null) { NetworkCredential credential = credentials.GetCredential(request.ChallengedUri, "negotiate"); if ((credential == null) || (!(credential is SystemNetworkCredential) && (credential.InternalGetUserName().Length == 0))) { return(null); } ICredentialPolicy credentialPolicy = AuthenticationManager.CredentialPolicy; if ((credentialPolicy != null) && !credentialPolicy.ShouldSendCredential(request.ChallengedUri, request, credential, this)) { return(null); } string computeSpn = request.CurrentAuthenticationState.GetComputeSpn(request); ChannelBinding channelBinding = null; if (request.CurrentAuthenticationState.TransportContext != null) { channelBinding = request.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint); } securityContext = new NTAuthentication("Negotiate", credential, computeSpn, request, channelBinding); request.CurrentAuthenticationState.SetSecurityContext(securityContext, this); } string outgoingBlob = securityContext.GetOutgoingBlob(incomingBlob); if (outgoingBlob == null) { return(null); } bool unsafeOrProxyAuthenticatedConnectionSharing = request.UnsafeOrProxyAuthenticatedConnectionSharing; if (unsafeOrProxyAuthenticatedConnectionSharing) { request.LockConnection = true; } request.NtlmKeepAlive = ((incomingBlob == null) && securityContext.IsValidContext) && !securityContext.IsKerberos; return(AuthenticationManager.GetGroupAuthorization(this, (flag ? "Nego2" : "Negotiate") + " " + outgoingBlob, securityContext.IsCompleted, securityContext, unsafeOrProxyAuthenticatedConnectionSharing, securityContext.IsKerberos)); }
private Authorization XPDoAuthenticate(string challenge, HttpWebRequest httpWebRequest, ICredentials credentials, bool preAuthenticate) { NTAuthentication securityContext = null; string incomingBlob = null; SecurityStatus status; if (!preAuthenticate) { int index = AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature); if (index < 0) { return(null); } securityContext = httpWebRequest.CurrentAuthenticationState.GetSecurityContext(this); incomingBlob = RefineDigestChallenge(challenge, index); } else { HttpDigestChallenge challenge2 = challengeCache.Lookup(httpWebRequest.ChallengedUri.AbsoluteUri) as HttpDigestChallenge; if (challenge2 == null) { return(null); } challenge2 = challenge2.CopyAndIncrementNonce(); challenge2.SetFromRequest(httpWebRequest); incomingBlob = challenge2.ToBlob(); } UriComponents uriParts = 0; if (httpWebRequest.CurrentMethod.ConnectRequest) { uriParts = UriComponents.HostAndPort; } else if (httpWebRequest.UsesProxySemantics) { uriParts = UriComponents.HttpRequestUrl; } else { uriParts = UriComponents.PathAndQuery; } string parts = httpWebRequest.GetRemoteResourceUri().GetParts(uriParts, UriFormat.UriEscaped); if (securityContext == null) { NetworkCredential credential = credentials.GetCredential(httpWebRequest.ChallengedUri, Signature); if ((credential == null) || (!(credential is SystemNetworkCredential) && (credential.InternalGetUserName().Length == 0))) { return(null); } ICredentialPolicy credentialPolicy = AuthenticationManager.CredentialPolicy; if ((credentialPolicy != null) && !credentialPolicy.ShouldSendCredential(httpWebRequest.ChallengedUri, httpWebRequest, credential, this)) { return(null); } string computeSpn = httpWebRequest.CurrentAuthenticationState.GetComputeSpn(httpWebRequest); ChannelBinding channelBinding = null; if (httpWebRequest.CurrentAuthenticationState.TransportContext != null) { channelBinding = httpWebRequest.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint); } securityContext = new NTAuthentication("WDigest", credential, computeSpn, httpWebRequest, channelBinding); httpWebRequest.CurrentAuthenticationState.SetSecurityContext(securityContext, this); } string str4 = securityContext.GetOutgoingDigestBlob(incomingBlob, httpWebRequest.CurrentMethod.Name, parts, null, false, false, out status); if (str4 == null) { return(null); } Authorization authorization = new Authorization("Digest " + str4, securityContext.IsCompleted, string.Empty, securityContext.IsMutualAuthFlag); if (!preAuthenticate && httpWebRequest.PreAuthenticate) { HttpDigestChallenge challenge3 = HttpDigest.Interpret(incomingBlob, -1, httpWebRequest); string[] strArray = (challenge3.Domain == null) ? new string[] { httpWebRequest.ChallengedUri.GetParts(UriComponents.SchemeAndServer, UriFormat.UriEscaped) } : challenge3.Domain.Split(singleSpaceArray); authorization.ProtectionRealm = (challenge3.Domain == null) ? null : strArray; for (int i = 0; i < strArray.Length; i++) { challengeCache.Add(strArray[i], challenge3); } } return(authorization); }
private Authorization DoAuthenticate(string challenge, WebRequest webRequest, ICredentials credentials, bool preAuthenticate) { if (credentials == null) { return(null); } HttpWebRequest request = webRequest as HttpWebRequest; NTAuthentication securityContext = null; string incomingBlob = null; if (!preAuthenticate) { int index = AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature); if (index < 0) { return(null); } int startIndex = index + SignatureSize; if ((challenge.Length > startIndex) && (challenge[startIndex] != ',')) { startIndex++; } else { index = -1; } if ((index >= 0) && (challenge.Length > startIndex)) { index = challenge.IndexOf(',', startIndex); if (index != -1) { incomingBlob = challenge.Substring(startIndex, index - startIndex); } else { incomingBlob = challenge.Substring(startIndex); } } securityContext = request.CurrentAuthenticationState.GetSecurityContext(this); } if (securityContext == null) { NetworkCredential credential = credentials.GetCredential(request.ChallengedUri, Signature); if ((credential == null) || (!(credential is SystemNetworkCredential) && (credential.InternalGetUserName().Length == 0))) { return(null); } ICredentialPolicy credentialPolicy = AuthenticationManager.CredentialPolicy; if ((credentialPolicy != null) && !credentialPolicy.ShouldSendCredential(request.ChallengedUri, request, credential, this)) { return(null); } string computeSpn = request.CurrentAuthenticationState.GetComputeSpn(request); ChannelBinding channelBinding = null; if (request.CurrentAuthenticationState.TransportContext != null) { channelBinding = request.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint); } securityContext = new NTAuthentication("Kerberos", credential, computeSpn, request, channelBinding); request.CurrentAuthenticationState.SetSecurityContext(securityContext, this); } string outgoingBlob = securityContext.GetOutgoingBlob(incomingBlob); if (outgoingBlob == null) { return(null); } return(new Authorization("Kerberos " + outgoingBlob, securityContext.IsCompleted, string.Empty, securityContext.IsMutualAuthFlag)); }
internal static Authorization Authenticate(HttpDigestChallenge digestChallenge, NetworkCredential NC, string spn, ChannelBinding binding) { string userName = NC.InternalGetUserName(); if (ValidationHelper.IsBlankString(userName)) { return(null); } string password = NC.InternalGetPassword(); bool flag = IsUpgraded(digestChallenge.Nonce, binding); if (flag) { digestChallenge.ServiceName = spn; digestChallenge.ChannelBinding = hashChannelBinding(binding, digestChallenge.MD5provider); } if (digestChallenge.QopPresent) { if ((digestChallenge.ClientNonce == null) || digestChallenge.Stale) { if (flag) { digestChallenge.ClientNonce = createUpgradedNonce(digestChallenge); } else { digestChallenge.ClientNonce = createNonce(0x20); } digestChallenge.NonceCount = 1; } else { digestChallenge.NonceCount++; } } StringBuilder builder = new StringBuilder(); Charset charset = DetectCharset(userName); if (!digestChallenge.UTF8Charset && (charset == Charset.UTF8)) { return(null); } Charset charset2 = DetectCharset(password); if (!digestChallenge.UTF8Charset && (charset2 == Charset.UTF8)) { return(null); } if (digestChallenge.UTF8Charset) { builder.Append(pair("charset", "utf-8", false)); builder.Append(","); if (charset == Charset.UTF8) { userName = CharsetEncode(userName, Charset.UTF8); builder.Append(pair("username", userName, true)); builder.Append(","); } else { builder.Append(pair("username", CharsetEncode(userName, Charset.UTF8), true)); builder.Append(","); userName = CharsetEncode(userName, charset); } } else { userName = CharsetEncode(userName, charset); builder.Append(pair("username", userName, true)); builder.Append(","); } password = CharsetEncode(password, charset2); builder.Append(pair("realm", digestChallenge.Realm, true)); builder.Append(","); builder.Append(pair("nonce", digestChallenge.Nonce, true)); builder.Append(","); builder.Append(pair("uri", digestChallenge.Uri, true)); if (digestChallenge.QopPresent) { if (digestChallenge.Algorithm != null) { builder.Append(","); builder.Append(pair("algorithm", digestChallenge.Algorithm, true)); } builder.Append(","); builder.Append(pair("cnonce", digestChallenge.ClientNonce, true)); builder.Append(","); builder.Append(pair("nc", digestChallenge.NonceCount.ToString("x8", NumberFormatInfo.InvariantInfo), false)); builder.Append(","); builder.Append(pair("qop", "auth", true)); if (flag) { builder.Append(","); builder.Append(pair("hashed-dirs", "service-name,channel-binding", true)); builder.Append(","); builder.Append(pair("service-name", digestChallenge.ServiceName, true)); builder.Append(","); builder.Append(pair("channel-binding", digestChallenge.ChannelBinding, true)); } } string str3 = responseValue(digestChallenge, userName, password); if (str3 == null) { return(null); } builder.Append(","); builder.Append(pair("response", str3, true)); if (digestChallenge.Opaque != null) { builder.Append(","); builder.Append(pair("opaque", digestChallenge.Opaque, true)); } return(new Authorization("Digest " + builder.ToString(), false)); }