예제 #1
0
        private bool Test(ICredentials credentials, HttpUrl url, string expectedUserName, string expectedPassword)
        {
            Uri uri = new Uri(String.Format("{0}://{1}/", url.Scheme, url.Host));

            return((credentials.GetCredential(uri, AuthenticationScheme).UserName == expectedUserName) &&
                   (credentials.GetCredential(uri, AuthenticationScheme).Password == expectedPassword));
        }
        public Authorization Authenticate(string challenge, WebRequest request, ICredentials credentials)
        {
            int index = challenge.ToLower ().IndexOf (auth_type.ToLower ());
            if (index == -1)
            {
                index = challenge.ToLower ().IndexOf (hackish_auth_type.ToLower ());
                if (index == -1)
                    return null;
            }
            if (GoogleClient.auth_token != null)
            {
                return new Authorization(auth_type + " auth=" + GoogleClient.auth_token);
            }

            string username = credentials.GetCredential (request.RequestUri, auth_type).UserName;
            string password = credentials.GetCredential (request.RequestUri, auth_type).Password;

            byte[] login_data = Encoding.ASCII.GetBytes (String.Format (
                    "Email={0}&Passwd={1}&source=Tomboy-Blogposter-0.4.4&service=blogger",
                    HttpUtility.UrlEncode (username), HttpUtility.UrlEncode (password)));
            HttpWebRequest login_request = (HttpWebRequest) WebRequest.Create("https://www.google.com/accounts/ClientLogin");
            ServicePointManager.Expect100Continue = false;
            login_request.Method = "POST";
            login_request.ContentType = "application/x-www-form-urlencoded";
            login_request.ContentLength = login_data.Length;
            Stream login_request_stream = login_request.GetRequestStream ();
            login_request_stream.Write (login_data, 0, login_data.Length);
            try
            {
                HttpWebResponse login_response = (HttpWebResponse) login_request.GetResponse ();
                Stream login_response_stream = login_response.GetResponseStream ();
                StreamReader login_response_stream_reader = new StreamReader (login_response_stream);
                string lines = login_response_stream_reader.ReadToEnd ();
                login_response.Close ();
                login_response_stream.Close ();
                login_response_stream_reader.Close ();
                foreach (string line in lines.Split ('\n'))
                {
                    if (line.StartsWith ("Auth="))
                    {
                        GoogleClient.auth_token = line.Substring (5);
                        break;
                    }
                }
            }
            catch (WebException exception)
            {
                Logger.Log(((HttpWebResponse) exception.Response).StatusCode.ToString());
                GoogleClient.auth_token = null;
                exception.Response.Close ();
            }
            login_request_stream.Close ();

            if (GoogleClient.auth_token != null)
                return new Authorization(auth_type + " auth=" + GoogleClient.auth_token);
            else
                return null;
        }
예제 #3
0
        private static 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);
            }

            string username = NC.UserName;
            string domain   = NC.Domain;

            if (ValidationHelper.IsBlankString(username))
            {
                return(null);
            }

            string rawString = ((!ValidationHelper.IsBlankString(domain)) ? (domain + "\\") : "") + username + ":" + NC.Password;

            // 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));
        }
예제 #4
0
        static string GetBasicAuthenticationHeader(Uri requestUri, ICredentials credentials)
        {
            var foundCredential = credentials.GetCredential(requestUri, "basic");

            if (foundCredential == null)
            {
                return(null);
            }

            string userName = foundCredential.UserName;

            if (string.IsNullOrEmpty(userName))
            {
                return(null);
            }

            string password = foundCredential.Password;
            string domain   = foundCredential.Domain;

            byte [] bytes;

            // If domain is set, MS sends "domain\user:password".
            if (string.IsNullOrEmpty(domain) || domain.Trim() == "")
            {
                bytes = GetBytes(userName + ":" + password);
            }
            else
            {
                bytes = GetBytes(domain + "\\" + userName + ":" + password);
            }

            return(Convert.ToBase64String(bytes));
        }
        private static void PrepareSharingNtlm(WebConnection cnc, HttpWebRequest request)
        {
            if (!cnc.NtlmAuthenticated)
            {
                return;
            }

            bool needs_reset           = false;
            NetworkCredential cnc_cred = cnc.NtlmCredential;

            bool              isProxy    = (request.Proxy != null && !request.Proxy.IsBypassed(request.RequestUri));
            ICredentials      req_icreds = (!isProxy) ? request.Credentials : request.Proxy.Credentials;
            NetworkCredential req_cred   = (req_icreds != null) ? req_icreds.GetCredential(request.RequestUri, "NTLM") : null;

            if (cnc_cred == null || req_cred == null || cnc_cred.Domain != req_cred.Domain || cnc_cred.UserName != req_cred.UserName ||
                cnc_cred.Password != req_cred.Password)
            {
                needs_reset = true;
            }

            if (!needs_reset)
            {
                bool req_sharing = request.UnsafeAuthenticatedConnectionSharing;
                bool cnc_sharing = cnc.UnsafeAuthenticatedConnectionSharing;
                needs_reset = (req_sharing == false || req_sharing != cnc_sharing);
            }
            if (needs_reset)
            {
                cnc.Close(false);                  // closes the authenticated connection
                cnc.ResetNtlm();
            }
        }
예제 #6
0
        public Authorization Authenticate(WebRequest webRequest, ICredentials credentials)
        {
            if (parser == null)
            {
                throw new InvalidOperationException();
            }
            HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;

            if (httpWebRequest == null)
            {
                return(null);
            }
            lastUse = DateTime.Now;
            NetworkCredential credential = credentials.GetCredential(httpWebRequest.RequestUri, "digest");

            if (credential == null)
            {
                return(null);
            }
            string userName = credential.UserName;

            if (userName == null || userName == string.Empty)
            {
                return(null);
            }
            string        password      = credential.Password;
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.AppendFormat("Digest username=\"{0}\", ", userName);
            stringBuilder.AppendFormat("realm=\"{0}\", ", Realm);
            stringBuilder.AppendFormat("nonce=\"{0}\", ", Nonce);
            stringBuilder.AppendFormat("uri=\"{0}\", ", httpWebRequest.Address.PathAndQuery);
            if (Algorithm != null)
            {
                stringBuilder.AppendFormat("algorithm=\"{0}\", ", Algorithm);
            }
            stringBuilder.AppendFormat("response=\"{0}\", ", Response(userName, password, httpWebRequest));
            if (QOP != null)
            {
                stringBuilder.AppendFormat("qop=\"{0}\", ", QOP);
            }
            lock (this)
            {
                if (QOP != null)
                {
                    stringBuilder.AppendFormat("nc={0:X8}, ", _nc);
                    _nc++;
                }
            }
            if (CNonce != null)
            {
                stringBuilder.AppendFormat("cnonce=\"{0}\", ", CNonce);
            }
            if (Opaque != null)
            {
                stringBuilder.AppendFormat("opaque=\"{0}\", ", Opaque);
            }
            stringBuilder.Length -= 2;
            return(new Authorization(stringBuilder.ToString()));
        }
예제 #7
0
        private static bool TryGetValidAuthenticationChallengeForScheme(string scheme, AuthenticationType authenticationType, Uri uri, ICredentials credentials,
                                                                        HttpHeaderValueCollection <AuthenticationHeaderValue> authenticationHeaderValues, out AuthenticationChallenge challenge)
        {
            challenge = default;

            if (!TryGetChallengeDataForScheme(scheme, authenticationHeaderValues, out string?challengeData))
            {
                return(false);
            }

            NetworkCredential?credential = credentials.GetCredential(uri, scheme);

            if (credential == null)
            {
                // We have no credential for this auth type, so we can't respond to the challenge.
                // We'll continue to look for a different auth type that we do have a credential for.
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.AuthenticationInfo(uri, $"Authentication scheme '{scheme}' supported by server, but not by client.");
                }
                return(false);
            }

            challenge = new AuthenticationChallenge(authenticationType, scheme, credential, challengeData);
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.AuthenticationInfo(uri, $"Authentication scheme '{scheme}' selected. Client username={challenge.Credential.UserName}");
            }
            return(true);
        }
예제 #8
0
        /// <summary>
        /// Given a URI and credentials which failed to authenticate, returns
        /// the username which failed to authenticate, in DOMAIN\user form.
        /// </summary>
        /// <param name="uri">Uri to which the credentials failed to authenticate</param>
        /// <param name="failedCredentials">Credentials which failed to authenticate</param>
        /// <returns>DOMAIN\user which failed to authenticate, or String.Empty</returns>
        public static String FailedUserName(Uri uri, ICredentials failedCredentials)
        {
            String userName = String.Empty;

            if (failedCredentials != null)
            {
                NetworkCredential cred = failedCredentials.GetCredential(uri, null);

                if (cred != null)
                {
                    if (cred.Domain.Length > 0 && cred.UserName.Length > 0)
                    {
                        userName = String.Concat(cred.Domain, "\\", cred.UserName);
                    }
                    else
                    {
                        userName = cred.UserName;
                    }

                    // Don't return a username that exceeds CREDUI_MAX_USERNAME_LENGTH.
                    if (userName.Length > NativeMethods.CREDUI_MAX_USERNAME_LENGTH)
                    {
                        userName = userName.Substring(0, NativeMethods.CREDUI_MAX_USERNAME_LENGTH);
                    }
                }
            }

            return(userName);
        }
예제 #9
0
        private AmazonS3Client GetClient(ICredentials credentials, RegionEndpoint region)
        {
            var basicCredential = credentials.GetCredential(this.Uri, "basic");
            var client          = new AmazonS3Client(new BasicAWSCredentials(basicCredential.UserName, basicCredential.Password), region);

            return(client);
        }
예제 #10
0
        private ICredentials HttpUnauthorizedHandler(Uri requestUri, string authenticationType, Dictionary <string, string> authenticationAttributes, NetworkCredential usedCredentials)
        {
            lock (authenticationRequestSynchronizer)
            {
                ICredentials credentials = this.RequestCredentials;
                if (credentials == null || usedCredentials == credentials.GetCredential(requestUri, authenticationType))
                {
                    using (ManualResetEvent handler = new ManualResetEvent(false))
                    {
                        requestUri = new Uri(requestUri.AbsoluteUri);
                        this.Dispatcher.BeginInvoke(new Action <Uri, string, Dictionary <string, string>, ManualResetEvent>((uri, type, attributes, resetEvent) =>
                        {
                            this.OnHttpAuthenticationRequired(uri, type, attributes);
                            resetEvent.Set();
                        }),
                                                    requestUri,
                                                    authenticationType,
                                                    authenticationAttributes,
                                                    handler);

                        handler.WaitOne();
                    }
                }

                return(this.RequestCredentials);
            }
        }
        public override Stream CreateUploadStream(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry, long uploadSize)
        {
            // build the url
            string url = GetResourceUrl(session, fileSystemEntry, null);

            // get the session creds
            ICredentials creds = session.SessionToken as ICredentials;

            // Build the service
            DavService svc = new DavService();

            // get the service config
            WebDavConfiguration conf = (WebDavConfiguration)session.ServiceConfiguration;

            // build the webrequest
            WebRequest networkRequest = svc.CreateWebRequestPUT(url, creds.GetCredential(null, null), conf.UploadDataStreambuffered);

            // get the request stream
            WebRequestStream requestStream = svc.GetRequestStream(networkRequest, uploadSize);

            // add disposal opp
            requestStream.PushPostDisposeOperation(CommitUploadStream, svc, networkRequest, fileSystemEntry, requestStream);

            // go ahead
            return(requestStream);
        }
예제 #12
0
    public Authorization Authenticate(string challenge, WebRequest request, ICredentials credentials)
    {
        Authorization result = null;

        if (request == null || credentials == null)
        {
            result = null;
        }
        else
        {
            NetworkCredential creds = credentials.GetCredential(LoginServerUrl, TheAuthenticationType);
            if (creds == null)
            {
                return(null);
            }
            ICredentialPolicy policy = AuthenticationManager.CredentialPolicy;
            if (policy != null && !policy.ShouldSendCredential(LoginServerUrl, request, creds, this))
            {
                return(null);
            }
            string token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", creds.UserName, creds.Password)));
            result = new Authorization(string.Format("Basic {0}", token));
        }
        return(result);
    }
예제 #13
0
        private HttpWebRequest CreateWebRequest(Uri uri)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.UnsafeAuthenticatedConnectionSharing = !this.proxyInfo.RequiresImpersonation;
            if (!this.proxyInfo.RequiresImpersonation)
            {
                httpWebRequest.ServicePoint.ConnectionLimit = GlobalSettings.ProxyConnectionPoolConnectionLimit;
            }
            httpWebRequest.ServicePoint.SetTcpKeepAlive(true, 240000, 5000);
            httpWebRequest.PreAuthenticate   = true;
            httpWebRequest.AllowAutoRedirect = false;
            httpWebRequest.KeepAlive         = !this.proxyInfo.RequiresImpersonation;
            CertificateValidationManager.SetComponentId(httpWebRequest, "AirSync");
            if (this.proxyInfo.CanImpersonate)
            {
                ICredentials defaultCredentials = CredentialCache.DefaultCredentials;
                httpWebRequest.Credentials = defaultCredentials.GetCredential(this.proxyInfo.RemoteUri, "Kerberos");
                if (httpWebRequest.Credentials == null)
                {
                    this.protocolLogger.SetValue(ProtocolLoggerData.Error, "NoKerberosCredentials");
                    throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerError, null, false);
                }
            }
            return(httpWebRequest);
        }
예제 #14
0
        public async static Task <bool> TrySetDigestAuthToken(HttpRequestMessage request, ICredentials credentials, DigestResponse digestResponse, string authHeader)
        {
            NetworkCredential credential = credentials.GetCredential(request.RequestUri, Digest);

            if (credential == null)
            {
                return(false);
            }

            string parameter = await GetDigestTokenForCredential(credential, request, digestResponse).ConfigureAwait(false);

            // Any errors in obtaining parameter return false
            if (string.IsNullOrEmpty(parameter))
            {
                return(false);
            }

            if (authHeader == HttpKnownHeaderNames.Authorization)
            {
                request.Headers.Authorization = new AuthenticationHeaderValue(Digest, parameter);
            }
            else if (authHeader == HttpKnownHeaderNames.ProxyAuthorization)
            {
                request.Headers.ProxyAuthorization = new AuthenticationHeaderValue(Digest, parameter);
            }

            return(true);
        }
예제 #15
0
        private static uint ChooseAuthScheme(uint supportedSchemes, Uri uri, ICredentials credentials)
        {
            if (credentials == null)
            {
                return(0);
            }

            if (uri == null && !(credentials is NetworkCredential))
            {
                // https://github.com/dotnet/runtime/issues/16737.
                // If the credentials are a NetworkCredential, the uri isn't used when calling .GetCredential() since
                // it will work against all uri's. Otherwise, credentials is probably a CredentialCache and passing in
                // null for a uri is invalid.
                return(0);
            }

            foreach (uint authScheme in s_authSchemePriorityOrder)
            {
                if ((supportedSchemes & authScheme) != 0 && credentials.GetCredential(uri, s_authSchemeStringMapping[authScheme]) != null)
                {
                    return(authScheme);
                }
            }

            return(0);
        }
예제 #16
0
        internal bool CanReuseConnection(WebOperation operation)
        {
            lock (this) {
                if (Closed || currentOperation != null)
                {
                    return(false);
                }
                if (!NtlmAuthenticated)
                {
                    return(true);
                }

                NetworkCredential cnc_cred = NtlmCredential;
                var request = operation.Request;

                bool              isProxy    = (request.Proxy != null && !request.Proxy.IsBypassed(request.RequestUri));
                ICredentials      req_icreds = (!isProxy) ? request.Credentials : request.Proxy.Credentials;
                NetworkCredential req_cred   = (req_icreds != null) ? req_icreds.GetCredential(request.RequestUri, "NTLM") : null;

                if (cnc_cred == null || req_cred == null ||
                    cnc_cred.Domain != req_cred.Domain || cnc_cred.UserName != req_cred.UserName ||
                    cnc_cred.Password != req_cred.Password)
                {
                    return(false);
                }

                bool req_sharing = request.UnsafeAuthenticatedConnectionSharing;
                bool cnc_sharing = UnsafeAuthenticatedConnectionSharing;
                return(!(req_sharing == false || req_sharing != cnc_sharing));
            }
        }
예제 #17
0
        bool PrepareSharingNtlm(WebOperation operation)
        {
            if (operation == null || !NtlmAuthenticated)
            {
                return(true);
            }

            bool needs_reset           = false;
            NetworkCredential cnc_cred = NtlmCredential;
            var request = operation.Request;

            bool              isProxy    = (request.Proxy != null && !request.Proxy.IsBypassed(request.RequestUri));
            ICredentials      req_icreds = (!isProxy) ? request.Credentials : request.Proxy.Credentials;
            NetworkCredential req_cred   = (req_icreds != null) ? req_icreds.GetCredential(request.RequestUri, "NTLM") : null;

            if (cnc_cred == null || req_cred == null ||
                cnc_cred.Domain != req_cred.Domain || cnc_cred.UserName != req_cred.UserName ||
                cnc_cred.Password != req_cred.Password)
            {
                needs_reset = true;
            }

            if (!needs_reset)
            {
                bool req_sharing = request.UnsafeAuthenticatedConnectionSharing;
                bool cnc_sharing = UnsafeAuthenticatedConnectionSharing;
                needs_reset = (req_sharing == false || req_sharing != cnc_sharing);
            }

            return(needs_reset);
        }
        /// <summary>
        /// Modifies the request to ensure that the authentication requirements are met.
        /// </summary>
        /// <param name="client">Client executing this request</param>
        /// <param name="request">Request to authenticate</param>
        /// <param name="credentials">The credentials used for the authentication</param>
        /// <returns>The task the authentication is performed on</returns>
        public Task PreAuthenticate(IRestClient client, IRestRequest request, ICredentials credentials)
        {
            if (credentials == null)
            {
                throw new InvalidOperationException("The credentials must be set using the IRestClient.Credential property.");
            }

            var cred = credentials.GetCredential(client.BuildUri(request, false), AuthenticationMethod);

            if (cred == null)
            {
                throw new InvalidOperationException($"No credentials provided for the {AuthenticationMethod} authentication type.");
            }

            request.Parameters.AddOrUpdate(new Parameter {
                Type = _parameterType, Name = _usernameKey, Value = cred.UserName, ValidateOnAdd = false
            });
            request.Parameters.AddOrUpdate(new Parameter {
                Type = _parameterType, Name = _passwordKey, Value = cred.Password, ValidateOnAdd = false
            });

#if USE_TASKEX
            return(TaskEx.FromResult(0));
#else
            return(Task.FromResult(0));
#endif
        }
예제 #19
0
        public static void DownloadPackage(string packageId, NuGetVersion version, Uri feedUri, ICredentials feedCredentials, string targetFilePath)
        {
            ILogger logger           = new NugetLogger();
            var     sourceRepository = Repository.Factory.GetCoreV3(feedUri.AbsoluteUri);

            if (feedCredentials != null)
            {
                var cred = feedCredentials.GetCredential(feedUri, "basic");
                sourceRepository.PackageSource.Credentials = new PackageSourceCredential("octopus", cred.UserName, cred.Password, true);
            }

            var providers       = new SourceRepositoryDependencyProvider(sourceRepository, logger, new SourceCacheContext());
            var libraryIdentity = new LibraryIdentity(packageId, version, LibraryType.Package);

            var targetPath = Directory.GetParent(targetFilePath).FullName;

            if (!Directory.Exists(targetPath))
            {
                Directory.CreateDirectory(targetPath);
            }

            string targetTempNupkg = Path.Combine(targetPath, Path.GetRandomFileName());

            using (var nupkgStream = new FileStream(targetTempNupkg, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete, 4096, true))
            {
                providers.CopyToAsync(libraryIdentity, nupkgStream, CancellationToken.None)
                .GetAwaiter()
                .GetResult();
            }

            File.Move(targetTempNupkg, targetFilePath);
        }
예제 #20
0
        public static async ValueTask EstablishSocksTunnelAsync(Stream stream, string host, int port, Uri proxyUri, ICredentials?proxyCredentials, bool async, CancellationToken cancellationToken)
        {
            using (cancellationToken.Register(s => ((Stream)s !).Dispose(), stream))
            {
                try
                {
                    NetworkCredential?credentials = proxyCredentials?.GetCredential(proxyUri, proxyUri.Scheme);

                    if (string.Equals(proxyUri.Scheme, "socks5", StringComparison.OrdinalIgnoreCase))
                    {
                        await EstablishSocks5TunnelAsync(stream, host, port, proxyUri, credentials, async).ConfigureAwait(false);
                    }
                    else if (string.Equals(proxyUri.Scheme, "socks4a", StringComparison.OrdinalIgnoreCase))
                    {
                        await EstablishSocks4TunnelAsync(stream, isVersion4a : true, host, port, proxyUri, credentials, async, cancellationToken).ConfigureAwait(false);
                    }
                    else if (string.Equals(proxyUri.Scheme, "socks4", StringComparison.OrdinalIgnoreCase))
                    {
                        await EstablishSocks4TunnelAsync(stream, isVersion4a : false, host, port, proxyUri, credentials, async, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        Debug.Fail("Bad socks version.");
                    }
                }
                catch
                {
                    stream.Dispose();
                    throw;
                }
            }
        }
예제 #21
0
        private bool HttpUnauthorizedResponse(HttpWebResponse response)
        {
            this.authenticationType = string.Empty;
            this.requestCredentials = null;

            string authenticationHeader = response.GetResponseHeader("WWW-Authenticate");

            if (!string.IsNullOrEmpty(authenticationHeader))
            {
                Regex authTypeRegex = new Regex(@"^([^\s]+)");
                Match authTypeMatch = authTypeRegex.Match(authenticationHeader);
                if (authTypeMatch.Success)
                {
                    this.authenticationType = authTypeMatch.Groups[1].Value;

                    Dictionary <string, string> authenticationAttributes = new Dictionary <string, string>();
                    Regex           authRealmRegex = new Regex(@"(\s+|\s*,\s*)(?<token>[^\s]+)\=""(?<value>[^""]+)""");
                    MatchCollection matches        = authRealmRegex.Matches(authenticationHeader);
                    foreach (Match match in matches)
                    {
                        authenticationAttributes.Add(match.Groups["token"].Value, match.Groups["value"].Value);
                    }

                    ICredentials credentials = this.httpAuthenticationHandler(this.uri, this.authenticationType, authenticationAttributes, this.usedCredentials);
                    if (credentials != null)
                    {
                        this.requestCredentials = credentials;
                        NetworkCredential newCredential = credentials.GetCredential(this.uri, this.authenticationType);
                        return(newCredential == null || newCredential == this.usedCredentials);
                    }
                }
            }

            return(true);
        }
예제 #22
0
        public static HttpClientHandler CreateClientHandler(string serviceUrl, ICredentials credentials, bool useCookies = false)
        {
            if (serviceUrl == null)
            {
                throw new ArgumentNullException("serviceUrl");
            }

            // Set up our own HttpClientHandler and configure it
            HttpClientHandler clientHandler = new HttpClientHandler();

            if (credentials != null)
            {
                // Set up credentials cache which will handle basic authentication
                CredentialCache credentialCache = new CredentialCache();

                // Get base address without terminating slash
                string credentialAddress = new Uri(serviceUrl).GetLeftPart(UriPartial.Authority).TrimEnd(uriPathSeparator);

                // Add credentials to cache and associate with handler
                NetworkCredential networkCredentials = credentials.GetCredential(new Uri(credentialAddress), "Basic");
                credentialCache.Add(new Uri(credentialAddress), "Basic", networkCredentials);
                clientHandler.Credentials     = credentialCache;
                clientHandler.PreAuthenticate = true;
            }

            // HttpClient's default UseCookies is true (meaning always roundtripping cookie back)
            // However, our api will default to false to cover multiple instance scenarios
            clientHandler.UseCookies = useCookies;

            // Our handler is ready
            return(clientHandler);
        }
예제 #23
0
        private static KeyValuePair <NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri, ICredentials credentials, KeyValuePair <string, CURLAUTH>[] validAuthTypes)
        {
            NetworkCredential nc             = null;
            CURLAUTH          curlAuthScheme = CURLAUTH.None;

            if (credentials != null)
            {
                // For each auth type we consider valid, try to get a credential for it.
                // Union together the auth types for which we could get credentials, but validate
                // that the found credentials are all the same, as libcurl doesn't support differentiating
                // by auth type.
                for (int i = 0; i < validAuthTypes.Length; i++)
                {
                    NetworkCredential networkCredential = credentials.GetCredential(requestUri, validAuthTypes[i].Key);
                    if (networkCredential != null)
                    {
                        curlAuthScheme |= validAuthTypes[i].Value;
                        if (nc == null)
                        {
                            nc = networkCredential;
                        }
                        else if (!AreEqualNetworkCredentials(nc, networkCredential))
                        {
                            throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_invalid_credential, CurlVersionDescription));
                        }
                    }
                }
            }

            EventSourceTrace("Authentication scheme: {0}", curlAuthScheme);
            return(new KeyValuePair <NetworkCredential, CURLAUTH>(nc, curlAuthScheme));;
        }
예제 #24
0
        public static HttpClientHandler CreateClientHandler(string serviceUrl, ICredentials credentials, bool useCookies = false)
        {
            if (serviceUrl == null)
            {
                throw new ArgumentNullException("serviceUrl");
            }

            // Set up our own HttpClientHandler and configure it
            HttpClientHandler clientHandler = new HttpClientHandler();

            if (credentials != null)
            {
                // Set up credentials cache which will handle basic authentication
                CredentialCache credentialCache = new CredentialCache();

                // Get base address without terminating slash
                string credentialAddress = new Uri(serviceUrl).GetLeftPart(UriPartial.Authority).TrimEnd(uriPathSeparator);

                // Add credentials to cache and associate with handler
                NetworkCredential networkCredentials = credentials.GetCredential(new Uri(credentialAddress), "Basic");
                credentialCache.Add(new Uri(credentialAddress), "Basic", networkCredentials);
                clientHandler.Credentials = credentialCache;
                clientHandler.PreAuthenticate = true;
            }

            // HttpClient's default UseCookies is true (meaning always roundtripping cookie back)
            // However, our api will default to false to cover multiple instance scenarios
            clientHandler.UseCookies = useCookies;

            // Our handler is ready
            return clientHandler;
        }
        /// <summary>
        /// Determines if the authentication module can handle the challenge sent with the response.
        /// </summary>
        /// <param name="client">The REST client the response is assigned to</param>
        /// <param name="request">The REST request the response is assigned to</param>
        /// <param name="credentials">The credentials to be used for the authentication</param>
        /// <param name="response">The response that returned the authentication challenge</param>
        /// <returns>true when the authenticator can handle the sent challenge</returns>
        public virtual bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
        {
            // No credentials defined?
            if (credentials == null)
            {
                return(false);
            }

            // No challenge header found?
            var authModeInfo = response.GetAuthenticationMethodValue(_authHeader, AuthenticationMethod);

            if (authModeInfo == null)
            {
                return(false);
            }

            // Search for credential for request URI
            var responseUri = client.GetRequestUri(request, response);
            var credential  = credentials.GetCredential(responseUri, AuthenticationMethod);

            if (credential == null)
            {
                return(false);
            }

            // Did we already try to use the found credentials?
            if (ReferenceEquals(credential, _authCredential))
            {
                // Yes, so we don't retry the authentication.
                return(false);
            }

            return(true);
        }
예제 #26
0
		static Authorization InternalAuthenticate (WebRequest webRequest, ICredentials credentials)
		{
			HttpWebRequest request = webRequest as HttpWebRequest;
			if (request == null || credentials == null)
				return null;

			NetworkCredential cred = credentials.GetCredential (request.AuthUri, "basic");
			if (cred == null)
				return null;

			string userName = cred.UserName;
			if (userName == null || userName == "")
				return null;

			string password = cred.Password;
			string domain = cred.Domain;
			byte [] bytes;

			// If domain is set, MS sends "domain\user:password". 
			if (domain == null || domain == "" || domain.Trim () == "")
				bytes = GetBytes (userName + ":" + password);
			else
				bytes = GetBytes (domain + "\\" + userName + ":" + password);

			string auth = "Basic " + Convert.ToBase64String (bytes);
			return new Authorization (auth);
		}
예제 #27
0
        PackagePhysicalFileMetadata DownloadChart(string packageId, IVersion version, Uri feedUri,
                                                  ICredentials feedCredentials, string cacheDirectory)
        {
            var cred = feedCredentials.GetCredential(feedUri, "basic");

            var tempDirectory = fileSystem.CreateTemporaryDirectory();

            using (new TemporaryDirectory(tempDirectory))
            {
                var homeDir = Path.Combine(tempDirectory, "helm");
                if (!Directory.Exists(homeDir))
                {
                    Directory.CreateDirectory(homeDir);
                }
                var stagingDir = Path.Combine(tempDirectory, "staging");
                if (!Directory.Exists(stagingDir))
                {
                    Directory.CreateDirectory(stagingDir);
                }

                var log = new LogWrapper();
                Invoke($"init --home \"{homeDir}\" --client-only", tempDirectory, log);
                Invoke($"repo add --home \"{homeDir}\" {(string.IsNullOrEmpty(cred.UserName) ? "" : $"--username \"{cred.UserName}\" --password \"{cred.Password}\"")} {TempRepoName} {feedUri.ToString()}", tempDirectory, log);
                Invoke($"fetch --home \"{homeDir}\"  --version \"{version}\" --destination \"{stagingDir}\" {TempRepoName}/{packageId}", tempDirectory, log);

                var localDownloadName =
                    Path.Combine(cacheDirectory, PackageName.ToCachedFileName(packageId, version, Extension));

                fileSystem.MoveFile(Directory.GetFiles(stagingDir)[0], localDownloadName);
                return(PackagePhysicalFileMetadata.Build(localDownloadName));
            }
예제 #28
0
        /// <summary>
        /// Authenticates the user with the specified AD FS endpoint and
        /// yields the SAML response data for subsequent parsing.
        /// </summary>
        /// <param name="identityProvider">
        /// The https endpoint of the federated identity provider.
        /// </param>
        /// <param name="credentials">
        /// Credentials for the call. If null, the user's default network credentials
        /// will be used in a temporary impersonation context.
        /// </param>
        /// <param name="authenticationType">
        /// The authentication type to be used with the endpoint. Valid values are 'NTLM',
        /// 'Digest', 'Kerberos' and 'Negotiate'.
        /// </param>
        /// <param name="proxySettings">Null or configured proxy settings for the HTTPS call.</param>
        /// <returns>The response data from a successful authentication request.</returns>
        public string Authenticate(Uri identityProvider, ICredentials credentials, string authenticationType, WebProxy proxySettings)
        {
            string             responseStreamData = null;
            ImpersonationState impersonationState = null;

            try
            {
                if (credentials != null)
                {
                    var networkCredentials = credentials.GetCredential(identityProvider, authenticationType);
                    impersonationState = ImpersonationState.Impersonate(networkCredentials);
                }

                using (var response = QueryProvider(identityProvider, authenticationType, proxySettings))
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        responseStreamData = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception e)
            {
                throw new AdfsAuthenticationControllerException(e.ToString(), e);
            }
            finally
            {
                if (impersonationState != null)
                {
                    impersonationState.Dispose();
                }
            }

            return(responseStreamData);
        }
예제 #29
0
        private static Authorization InternalAuthenticate(WebRequest webRequest, ICredentials credentials)
        {
            HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;

            if (httpWebRequest == null || credentials == null)
            {
                return(null);
            }
            NetworkCredential credential = credentials.GetCredential(httpWebRequest.AuthUri, "basic");

            if (credential == null)
            {
                return(null);
            }
            string userName = credential.UserName;

            if (userName == null || userName == string.Empty)
            {
                return(null);
            }
            string password = credential.Password;
            string domain   = credential.Domain;

            byte[] inArray = (domain != null && !(domain == string.Empty) && !(domain.Trim() == string.Empty)) ? GetBytes(domain + "\\" + userName + ":" + password) : GetBytes(userName + ":" + password);
            string token   = "Basic " + Convert.ToBase64String(inArray);

            return(new Authorization(token));
        }
예제 #30
0
        public void Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds)
        {
            int port;
            Task <LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
                out port,
                requireAuth: creds != null && creds != CredentialCache.DefaultCredentials,
                expectCreds: true);
            Uri proxyUrl = new Uri($"http://localhost:{port}");

            using (var handler = new HttpClientHandler()
            {
                Proxy = new UseSpecifiedUriWebProxy(proxyUrl, creds)
            })
                using (var client = new HttpClient(handler))
                {
                    Task <HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer);
                    Task <string> responseStringTask        = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
                    Task.WaitAll(proxyTask, responseTask, responseStringTask);

                    TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
                    Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result);

                    NetworkCredential nc = creds != null?creds.GetCredential(proxyUrl, "Basic") : null;

                    string expectedAuth =
                        nc == null || nc == CredentialCache.DefaultCredentials ? null :
                        string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" :
                        $"{nc.Domain}\\{nc.UserName}:{nc.Password}";
                    Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue);
                }
        }
예제 #31
0
        public static HttpClientHandler CreateClientHandler(string serviceUrl, ICredentials credentials)
        {
            if (serviceUrl == null)
            {
                throw new ArgumentNullException("serviceUrl");
            }

            // Set up our own HttpClientHandler and configure it
            HttpClientHandler clientHandler = new HttpClientHandler();

            if (credentials != null)
            {
                // Set up credentials cache which will handle basic authentication
                CredentialCache credentialCache = new CredentialCache();

                // Get base address without terminating slash
                string credentialAddress = new Uri(serviceUrl).GetLeftPart(UriPartial.Authority).TrimEnd(uriPathSeparator);

                // Add credentials to cache and associate with handler
                NetworkCredential networkCredentials = credentials.GetCredential(new Uri(credentialAddress), "Basic");
                credentialCache.Add(new Uri(credentialAddress), "Basic", networkCredentials);
                clientHandler.Credentials = credentialCache;
                clientHandler.PreAuthenticate = true;
            }

            // Our handler is ready
            return clientHandler;
        }
예제 #32
0
        private static KeyValuePair <NetworkCredential, CURLAUTH> GetCredentials(ICredentials credentials, Uri requestUri)
        {
            NetworkCredential nc             = null;
            CURLAUTH          curlAuthScheme = CURLAUTH.None;

            if (credentials != null)
            {
                // we collect all the schemes that are accepted by libcurl for which there is a non-null network credential.
                // But CurlHandler works under following assumption:
                //           for a given server, the credentials do not vary across authentication schemes.
                for (int i = 0; i < s_authSchemePriorityOrder.Length; i++)
                {
                    NetworkCredential networkCredential = credentials.GetCredential(requestUri, s_authenticationSchemes[i]);
                    if (networkCredential != null)
                    {
                        curlAuthScheme |= s_authSchemePriorityOrder[i];
                        if (nc == null)
                        {
                            nc = networkCredential;
                        }
                        else if (!AreEqualNetworkCredentials(nc, networkCredential))
                        {
                            throw new PlatformNotSupportedException(SR.net_http_unix_invalid_credential);
                        }
                    }
                }
            }

            VerboseTrace("curlAuthScheme = " + curlAuthScheme);
            return(new KeyValuePair <NetworkCredential, CURLAUTH>(nc, curlAuthScheme));;
        }
예제 #33
0
        public static HttpClientHandler CreateHttpClientHandler(string endpoint, ICredentials credentials)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }

            // Set up our own HttpClientHandler and configure it
            HttpClientHandler clientHandler = new HttpClientHandler();

            if (credentials != null)
            {
                // Set up credentials cache which will handle basic authentication
                CredentialCache credentialCache = new CredentialCache();

                // Get base address without terminating slash
                string credentialAddress = new Uri(endpoint).GetLeftPart(UriPartial.Authority).TrimEnd(uriPathSeparator);

                // Add credentials to cache and associate with handler
                NetworkCredential networkCredentials = credentials.GetCredential(new Uri(credentialAddress), "Basic");
                credentialCache.Add(new Uri(credentialAddress), "Basic", networkCredentials);
                clientHandler.Credentials     = credentialCache;
                clientHandler.PreAuthenticate = true;
            }

            // Our handler is ready
            return(clientHandler);
        }
예제 #34
0
        Authorization InternalAuthenticate(HttpURLConnection request, ICredentials credentials)
        {
            if (request == null || credentials == null)
            {
                return(null);
            }

            NetworkCredential cred = credentials.GetCredential(new Uri(request.URL.ToString()), AuthenticationType.ToLowerInvariant());

            if (cred == null)
            {
                return(null);
            }

            if (String.IsNullOrEmpty(cred.UserName))
            {
                return(null);
            }

            string domain   = cred.Domain?.Trim();
            string response = String.Empty;

            // If domain is set, MS sends "domain\user:password".
            if (!String.IsNullOrEmpty(domain))
            {
                response = domain + "\\";
            }
            response += cred.UserName + ":" + cred.Password;

            return(new Authorization($"{AuthenticationType} {Convert.ToBase64String (Encoding.ASCII.GetBytes (response))}"));
        }
 /// <summary>
 /// Does the authentication module supports pre-authentication?
 /// </summary>
 /// <param name="client">Client executing this request</param>
 /// <param name="request">Request to authenticate</param>
 /// <param name="credentials">The credentials to be used for the authentication</param>
 /// <returns>true when the authentication module supports pre-authentication</returns>
 public bool CanPreAuthenticate(IRestClient client, IRestRequest request, ICredentials credentials)
 {
     if (credentials == null)
         return false;
     var cred = credentials.GetCredential(client.BuildUri(request, false), AuthenticationMethod);
     if (cred == null)
         return false;
     return true;
 }
예제 #36
0
		public Authorization Authenticate (string challenge, WebRequest webRequest, ICredentials credentials) 
		{
			HttpWebRequest request = webRequest as HttpWebRequest;
			if (request == null)
				return null;
	
			NetworkCredential cred = credentials.GetCredential (request.RequestUri, "NTLM");
			if (cred == null)
				return null;

			string userName = cred.UserName;
			string domain = cred.Domain;
			string password = cred.Password;
			if (userName == null || userName == "")
				return null;
			domain = domain != null && domain.Length > 0 ? domain : request.Headers ["Host"];

			bool completed = false;
			if (message == null) {
				Type1Message type1 = new Type1Message ();
				type1.Domain = domain;
				message = type1;
			} else if (message.Type == 1) {
				// Should I check the credentials?
				if (challenge == null) {
					message = null;
					return null;
				}

				Type2Message type2 = new Type2Message (Convert.FromBase64String (challenge));
				if (password == null)
					password = "";

				Type3Message type3 = new Type3Message ();
				type3.Domain = domain;
				type3.Username = userName;
				type3.Challenge = type2.Nonce;
				type3.Password = password;
				message = type3;
				completed = true;
			} else {
				// Should I check the credentials?
				// type must be 3 here
				if (challenge == null || challenge == String.Empty) {
					Type1Message type1 = new Type1Message ();
					type1.Domain = domain;
					message = type1;
				} else {
					completed = true;
				}
			}
			
			string token = "NTLM " + Convert.ToBase64String (message.GetBytes ());
			return new Authorization (token, completed);
		}
 /// <summary>
 /// Modifies the request to ensure that the authentication requirements are met.
 /// </summary>
 /// <param name="client">Client executing this request</param>
 /// <param name="request">Request to authenticate</param>
 /// <param name="credentials">The credentials used for the authentication</param>
 /// <returns>The task the authentication is performed on</returns>
 public Task PreAuthenticate(IRestClient client, IRestRequest request, ICredentials credentials)
 {
     return Task.Factory.StartNew(() =>
     {
         if (credentials == null)
             throw new InvalidOperationException("The credentials must be set using the IRestClient.Credential property.");
         var cred = credentials.GetCredential(client.BuildUri(request, false), AuthenticationMethod);
         if (cred == null)
             throw new InvalidOperationException($"No credentials provided for the {AuthenticationMethod} authentication type.");
         request.AddParameter(_usernameKey, cred.UserName, _parameterType);
         request.AddParameter(_passwordKey, cred.Password, _parameterType);
     });
 }
		private Authorization Lookup(HttpWebRequest httpWebRequest, ICredentials credentials) {
			//NetworkCredential credential = credentials.GetCredential(httpWebRequest.ChallengedUri, BasicClient.Signature);
			var net_cred = credentials.GetCredential(httpWebRequest.RequestUri, "Basic");
			if (net_cred == null) {
				return null;
			}
			ICredentialPolicy credentialPolicy = AuthenticationManager.CredentialPolicy;
			if (credentialPolicy != null && !credentialPolicy.ShouldSendCredential(httpWebRequest.RequestUri, httpWebRequest, net_cred, this)) {
				return null;
			}
			var user_pass = String.Join(":", net_cred.UserName, net_cred.Password).ToUtf8();
			string authToken = "Basic " + user_pass.ToBase64();
			return new Authorization(authToken, true);
		}
예제 #39
0
		public static NetworkCredential GetCredentialsForUriFromICredentials (Uri uri, ICredentials credentials)
		{
			if (credentials == null)
				return null;

			NetworkCredential cred = null;
			foreach (var scheme in AuthenticationSchemes) {
				cred = credentials.GetCredential (uri, scheme);
				if (cred != null)
					break;
			}

			return cred;
		}
예제 #40
0
	private Authorization AuthenticateInternal(WebRequest request, 
			ICredentials credentials)
	{
		String user,password,domain;
		NetworkCredential netcredentials=credentials.GetCredential(
					request.RequestUri, "Basic");
		user=netcredentials.UserName;
		password=netcredentials.Password;
		domain=netcredentials.Domain;
		String response=((domain==null || domain=="") ? "" : 
					(domain + "\\"))
					+ user + ":" + password;
		byte[] buf=Encoding.Default.GetBytes(response);
		
		return new Authorization("Basic "+ToBase64String(buf));
	}
예제 #41
0
        private static HttpClient BuildHttpClient(Uri uri, ICredentials credentials = null)
        {
            var handler = new HttpClientHandler();
            var client = new HttpClient(handler);

            if (credentials != null)
            {
                handler.PreAuthenticate = true;
                handler.Credentials = credentials;

                var basicCredentials = credentials.GetCredential(uri, authType: "Basic");
                if (basicCredentials != null)
                    SetBasicAuthHeader(client, basicCredentials);
            }

            return client;
        }
        public Authorization PreAuthenticate(WebRequest request, ICredentials credentials)
        {
            NetworkCredential credential = credentials.GetCredential(request.RequestUri, AuthenticationType);
            string username = credential.UserName;
            string password = credential.Password;

            string created, nonce;
            string passwordDigest = GeneratePasswordDigest(password, out created, out nonce);

            request.Headers.Add("X-WSSE", string.Format(
                                              CultureInfo.InvariantCulture,
                                              "UsernameToken Username=\"{0}\", PasswordDigest=\"{1}\", Created=\"{2}\", Nonce=\"{3}\"",
                                              username,
                                              passwordDigest,
                                              created,
                                              nonce));

            return new Authorization("WSSE profile=\"UsernameToken\"", true);
        }
 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);
 }
        /// <summary>
        /// Authenticates the user with the specified AD FS endpoint and 
        /// yields the SAML response data for subsequent parsing.
        /// </summary>
        /// <param name="identityProvider">
        /// The https endpoint of the federated identity provider.
        /// </param>
        /// <param name="credentials">
        /// Credentials for the call. If null, the user's default network credentials 
        /// will be used in a temporary impersonation context.
        /// </param>
        /// <param name="authenticationType">
        /// The authentication type to be used with the endpoint. Valid values are 'NTLM',
        /// 'Digest', 'Kerberos' and 'Negotiate'.
        /// </param>
        /// <returns>The response data from a successful authentication request.</returns>
        public string Authenticate(Uri identityProvider, ICredentials credentials, string authenticationType)
        {
            string responseStreamData = null;
            ImpersonationState impersonationState = null;

            try
            {
                if (credentials != null)
                {
                    var networkCredentials = credentials.GetCredential(identityProvider, authenticationType);
                    impersonationState = ImpersonationState.Impersonate(networkCredentials);
                }

                using (var response = QueryProvider(identityProvider, authenticationType))
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        responseStreamData = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception e)
            {
                var sb = new StringBuilder(e.Message);
                if (e.InnerException != null)
                    sb.AppendFormat("(Inner exception '{0}')", e.InnerException.Message);
                throw new AdfsAuthenticationControllerException(sb.ToString(), e);
            }
            finally
            {
                if (impersonationState != null)
                    impersonationState.Dispose();
            }

            return responseStreamData;
        }
예제 #45
0
        private void SaveServerCredentialsToCache(Uri uri, uint authScheme, ICredentials serverCredentials)
        {
            string authType = s_authSchemeStringMapping[authScheme];
            Debug.Assert(!string.IsNullOrEmpty(authType));

            NetworkCredential cred = serverCredentials.GetCredential(uri, authType);
            if (cred != null)
            {
                lock (_credentialCacheLock)
                {
                    try
                    {
                        _credentialCache.Add(uri, authType, cred);
                    }
                    catch (ArgumentException)
                    {
                        // The credential was already added.
                    }
                }
            }
        }
예제 #46
0
        /// <summary>
        /// Authenticates using the supplied credentials.
        /// </summary>
        /// <remarks>
        /// <para>If the server supports one or more SASL authentication mechanisms, then
        /// the SASL mechanisms that both the client and server support are tried
        /// in order of greatest security to weakest security. Once a SASL
        /// authentication mechanism is found that both client and server support,
        /// the credentials are used to authenticate.</para>
        /// <para>If the server does not support SASL or if no common SASL mechanisms
        /// can be found, then LOGIN command is used as a fallback.</para>
        /// </remarks>
        /// <param name="credentials">The user's credentials.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="credentials"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ObjectDisposedException">
        /// The <see cref="ImapClient"/> has been disposed.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// The <see cref="ImapClient"/> is not connected or is already authenticated.
        /// </exception>
        /// <exception cref="System.OperationCanceledException">
        /// The operation was canceled via the cancellation token.
        /// </exception>
        /// <exception cref="MailKit.Security.AuthenticationException">
        /// Authentication using the supplied credentials has failed.
        /// </exception>
        /// <exception cref="MailKit.Security.SaslException">
        /// A SASL authentication error occurred.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        /// <exception cref="ImapProtocolException">
        /// An IMAP protocol error occurred.
        /// </exception>
        public void Authenticate(ICredentials credentials, CancellationToken cancellationToken)
        {
            CheckDisposed ();

            if (!IsConnected)
                throw new InvalidOperationException ("The ImapClient must be connected before you can authenticate.");

            if (engine.State >= ImapEngineState.Authenticated)
                throw new InvalidOperationException ("The ImapClient is already authenticated.");

            if (credentials == null)
                throw new ArgumentNullException ("credentials");

            int capabilitiesVersion = engine.CapabilitiesVersion;
            var uri = new Uri ("imap://" + host);
            NetworkCredential cred;
            ImapCommand ic;

            foreach (var authmech in SaslMechanism.AuthMechanismRank) {
                if (!engine.AuthenticationMechanisms.Contains (authmech))
                    continue;

                var sasl = SaslMechanism.Create (authmech, uri, credentials);

                cancellationToken.ThrowIfCancellationRequested ();

                var command = string.Format ("AUTHENTICATE {0}", sasl.MechanismName);
                var ir = sasl.Challenge (null);

                if ((engine.Capabilities & ImapCapabilities.SaslIR) != 0 && ir != null) {
                    command += " " + ir + "\r\n";
                } else {
                    command += "\r\n";
                    sasl.Reset ();
                }

                ic = engine.QueueCommand (cancellationToken, null, command);
                ic.ContinuationHandler = (imap, cmd, text) => {
                    string challenge;

                    if (sasl.IsAuthenticated) {
                        // the server claims we aren't done authenticating, but our SASL mechanism thinks we are...
                        // FIXME: will sending an empty string abort the AUTHENTICATE command?
                        challenge = string.Empty;
                    } else {
                        challenge = sasl.Challenge (text);
                    }

                    cmd.CancellationToken.ThrowIfCancellationRequested ();

                    var buf = Encoding.ASCII.GetBytes (challenge + "\r\n");
                    imap.Stream.Write (buf, 0, buf.Length);
                    imap.Stream.Flush ();
                };

                engine.Wait (ic);

                if (ic.Result != ImapCommandResult.Ok)
                    continue;

                engine.State = ImapEngineState.Authenticated;

                // Query the CAPABILITIES again if the server did not include an
                // untagged CAPABILITIES response to the AUTHENTICATE command.
                if (engine.CapabilitiesVersion == capabilitiesVersion)
                    engine.QueryCapabilities (cancellationToken);

                engine.QueryNamespaces (cancellationToken);
                engine.QuerySpecialFolders (cancellationToken);
                return;
            }

            if ((Capabilities & ImapCapabilities.LoginDisabled) != 0)
                throw new AuthenticationException ();

            // fall back to the classic LOGIN command...
            cred = credentials.GetCredential (uri, "LOGIN");

            ic = engine.QueueCommand (cancellationToken, null, "LOGIN %S %S\r\n", cred.UserName, cred.Password);

            engine.Wait (ic);

            if (ic.Result != ImapCommandResult.Ok)
                throw new AuthenticationException ();

            engine.State = ImapEngineState.Authenticated;

            // Query the CAPABILITIES again if the server did not include an
            // untagged CAPABILITIES response to the LOGIN command.
            if (engine.CapabilitiesVersion == capabilitiesVersion)
                engine.QueryCapabilities (cancellationToken);

            engine.QueryNamespaces (cancellationToken);
            engine.QuerySpecialFolders (cancellationToken);
        }
예제 #47
0
        private void SetWinHttpCredential(
            SafeWinHttpHandle requestHandle,
            ICredentials credentials,
            Uri uri,
            uint authScheme,
            uint authTarget)
        {
            Debug.Assert(credentials != null);
            Debug.Assert(authScheme != 0);
            Debug.Assert(authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_PROXY || 
                         authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER);

            NetworkCredential networkCredential = credentials.GetCredential(uri, s_authSchemeStringMapping[authScheme]);

            // Skip if no credentials or this is the default credential.
            if (networkCredential == null || networkCredential == CredentialCache.DefaultNetworkCredentials)
            {
                return;
            }

            string userName = networkCredential.UserName;
            string password = networkCredential.Password;
            string domain = networkCredential.Domain;

            // WinHTTP does not support a blank username.  So, we will throw an exception.
            if (string.IsNullOrEmpty(userName))
            {
                // TODO: Add error message.
                throw new InvalidOperationException();
            }

            if (!string.IsNullOrEmpty(domain))
            {
                userName = domain + "\\" + userName;
            }

            if (!Interop.WinHttp.WinHttpSetCredentials(
                requestHandle,
                authTarget,
                authScheme,
                userName,
                password,
                IntPtr.Zero))
            {
                WinHttpException.ThrowExceptionUsingLastError();
            }
        }
예제 #48
0
		private static NetworkCredential GetCredentials(ICredentials credentials, Uri requestUri)
        {
            if (credentials == null)
            {
                return null;
            }

            foreach (var authScheme in s_authenticationSchemes)
            {
                NetworkCredential networkCredential = credentials.GetCredential(requestUri, authScheme);
                if (networkCredential != null)
                {
                    return networkCredential;
                }
            }
            return null;
        }
예제 #49
0
파일: DigestClient.cs 프로젝트: GirlD/mono
		public Authorization Authenticate (WebRequest webRequest, ICredentials credentials) 
		{
			if (parser == null)
				throw new InvalidOperationException ();

			HttpWebRequest request = webRequest as HttpWebRequest;
			if (request == null)
				return null;
	
			lastUse = DateTime.Now;
			NetworkCredential cred = credentials.GetCredential (request.RequestUri, "digest");
			if (cred == null)
				return null;

			string userName = cred.UserName;
			if (userName == null || userName == "")
				return null;

			string password = cred.Password;
	
			StringBuilder auth = new StringBuilder ();
			auth.AppendFormat ("Digest username=\"{0}\", ", userName);
			auth.AppendFormat ("realm=\"{0}\", ", Realm);
			auth.AppendFormat ("nonce=\"{0}\", ", Nonce);
			auth.AppendFormat ("uri=\"{0}\", ", request.Address.PathAndQuery);

			if (Algorithm != null) { // hash algorithm (only MD5 in RFC2617)
				auth.AppendFormat ("algorithm=\"{0}\", ", Algorithm);
			}

			auth.AppendFormat ("response=\"{0}\", ", Response (userName, password, request));

			if (QOP != null) { // quality of protection (server decision)
				auth.AppendFormat ("qop=\"{0}\", ", QOP);
			}

			lock (this) {
				// _nc MUST NOT change from here...
				// number of request using this nonce
				if (QOP != null) {
					auth.AppendFormat ("nc={0:X8}, ", _nc);
					_nc++;
				}
				// until here, now _nc can change
			}

			if (CNonce != null) // opaque value from the client
				auth.AppendFormat ("cnonce=\"{0}\", ", CNonce);

			if (Opaque != null) // exact same opaque value as received from server
				auth.AppendFormat ("opaque=\"{0}\", ", Opaque);

			auth.Length -= 2; // remove ", "
			return new Authorization (auth.ToString ());
		}
 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);
 }
        /// <summary>
        /// Modifies the request to ensure that the authentication requirements are met.
        /// </summary>
        /// <param name="client">Client executing this request</param>
        /// <param name="request">Request to authenticate</param>
        /// <param name="credentials">The credentials used for the authentication</param>
        /// <returns>The task the authentication is performed on</returns>
        public Task PreAuthenticate(IRestClient client, IRestRequest request, ICredentials credentials)
        {
            if (credentials == null)
            {
                throw new InvalidOperationException("The credentials must be set using the IRestClient.Credential property.");
            }

            var cred = credentials.GetCredential(client.BuildUri(request, false), AuthenticationMethod);
            if (cred == null)
            {
                throw new InvalidOperationException($"No credentials provided for the {AuthenticationMethod} authentication type.");
            }

            request.Parameters.AddOrUpdate(new Parameter { Type = _parameterType, Name = _usernameKey, Value = cred.UserName, ValidateOnAdd = false });
            request.Parameters.AddOrUpdate(new Parameter { Type = _parameterType, Name = _passwordKey, Value = cred.Password, ValidateOnAdd = false });

#if USE_TASKEX
            return TaskEx.FromResult(0);
#else
            return Task.FromResult(0);
#endif
        }
        /// <summary>
        /// Will be called when the authentication failed
        /// </summary>
        /// <param name="client">Client executing this request</param>
        /// <param name="request">Request to authenticate</param>
        /// <param name="credentials">The credentials used for the authentication</param>
        /// <param name="response">Response of the failed request</param>
        /// <returns>Task where the handler for a failed authentication gets executed</returns>
        public Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
        {
            return Task.Factory.StartNew(() =>
            {
                if (!CanHandleChallenge(client, request, credentials, response))
                    throw new InvalidOperationException();

                var responseUri = client.GetRequestUri(request, response);
                _authCredential = credentials.GetCredential(responseUri, AuthenticationMethod);
                var authModeInfo = response.GetAuthenticationMethodValue(_authHeader, AuthenticationMethod);
                ParseResponseHeader(authModeInfo);
            });
        }
        /// <summary>
        /// Determines if the authentication module can handle the challenge sent with the response.
        /// </summary>
        /// <param name="client">The REST client the response is assigned to</param>
        /// <param name="request">The REST request the response is assigned to</param>
        /// <param name="credentials">The credentials to be used for the authentication</param>
        /// <param name="response">The response that returned the authentication challenge</param>
        /// <returns>true when the authenticator can handle the sent challenge</returns>
        public virtual bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
        {
            // No credentials defined?
            if (credentials == null)
                return false;

            // No challenge header found?
            var authModeInfo = response.GetAuthenticationMethodValue(_authHeader, AuthenticationMethod);
            if (authModeInfo == null)
                return false;

            // Search for credential for request URI
            var responseUri = client.GetRequestUri(request, response);
            var credential = credentials.GetCredential(responseUri, AuthenticationMethod);
            if (credential == null)
                return false;

            // Did we already try to use the found credentials?
            if (ReferenceEquals(credential, _authCredential))
            {
                // Yes, so we don't retry the authentication.
                return false;
            }

            return true;
        }
예제 #54
0
파일: Pop3Client.cs 프로젝트: EGrun/MailKit
        /// <summary>
        /// Authenticates using the supplied credentials.
        /// </summary>
        /// <remarks>
        /// <para>If the POP3 server supports the APOP authentication mechanism,
        /// then APOP is used.</para>
        /// <para>If the APOP authentication mechanism is not supported and the
        /// server supports one or more SASL authentication mechanisms, then
        /// the SASL mechanisms that both the client and server support are tried
        /// in order of greatest security to weakest security. Once a SASL
        /// authentication mechanism is found that both client and server support,
        /// the credentials are used to authenticate.</para>
        /// <para>If the server does not support SASL or if no common SASL mechanisms
        /// can be found, then the USER and PASS commands are used as a fallback.</para>
        /// </remarks>
        /// <param name="credentials">The user's credentials.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="credentials"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ObjectDisposedException">
        /// The <see cref="Pop3Client"/> has been disposed.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// The <see cref="Pop3Client"/> is not connected or is already authenticated.
        /// </exception>
        /// <exception cref="System.OperationCanceledException">
        /// The operation was canceled via the cancellation token.
        /// </exception>
        /// <exception cref="MailKit.Security.AuthenticationException">
        /// Authentication using the supplied credentials has failed.
        /// </exception>
        /// <exception cref="MailKit.Security.SaslException">
        /// A SASL authentication error occurred.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        /// <exception cref="Pop3CommandException">
        /// A POP3 command failed.
        /// </exception>
        /// <exception cref="Pop3ProtocolException">
        /// An POP3 protocol error occurred.
        /// </exception>
        public void Authenticate(ICredentials credentials, CancellationToken cancellationToken)
        {
            CheckDisposed ();

            if (!IsConnected)
                throw new InvalidOperationException ("The Pop3Client must be connected before you can authenticate.");

            if (engine.State == Pop3EngineState.Transaction)
                throw new InvalidOperationException ("The Pop3Client is already authenticated.");

            if (credentials == null)
                throw new ArgumentNullException ("credentials");

            var uri = new Uri ("pop://" + host);
            NetworkCredential cred;
            string challenge;
            Pop3Command pc;

            // (Erik) Not sure what to do with these
            #if !NETFX_CORE && !WINDOWS_APP && !WINDOWS_PHONE_APP
            if ((engine.Capabilities & Pop3Capabilities.Apop) != 0) {
                cred = credentials.GetCredential (uri, "APOP");
                challenge = engine.ApopToken + cred.Password;
                var md5sum = new StringBuilder ();
                byte[] digest;

                using (var md5 = HashAlgorithm.Create ("MD5")) {
                    digest = md5.ComputeHash (Encoding.UTF8.GetBytes (challenge));
                }

                for (int i = 0; i < digest.Length; i++)
                    md5sum.Append (digest[i].ToString ("x2"));

                try {
                    SendCommand (cancellationToken, "APOP {0} {1}", cred.UserName, md5sum);
                    engine.State = Pop3EngineState.Transaction;
                } catch (Pop3CommandException) {
                }

                if (engine.State == Pop3EngineState.Transaction) {
                    engine.QueryCapabilities (cancellationToken);
                    ProbeCapabilities (cancellationToken);
                    return;
                }
            }

            if ((engine.Capabilities & Pop3Capabilities.Sasl) != 0) {
                foreach (var authmech in SaslMechanism.AuthMechanismRank) {
                    if (!engine.AuthenticationMechanisms.Contains (authmech))
                        continue;

                    var sasl = SaslMechanism.Create (authmech, uri, credentials);

                    cancellationToken.ThrowIfCancellationRequested ();

                    pc = engine.QueueCommand (cancellationToken, (pop3, cmd, text) => {
                        while (!sasl.IsAuthenticated && cmd.Status == Pop3CommandStatus.Continue) {
                            challenge = sasl.Challenge (text);
                            string response;

                            var buf = Encoding.ASCII.GetBytes (challenge + "\r\n");
                            pop3.Stream.Write (buf, 0, buf.Length);

                            response = pop3.ReadLine (cmd.CancellationToken);

                            cmd.Status = Pop3Engine.GetCommandStatus (response, out text);
                            if (cmd.Status == Pop3CommandStatus.ProtocolError)
                                throw new Pop3ProtocolException (string.Format ("Unexpected response from server: {0}", response));
                        }
                    }, "AUTH {0}", authmech);

                    while (engine.Iterate () < pc.Id) {
                        // continue processing commands
                    }

                    if (pc.Status == Pop3CommandStatus.Error)
                        continue;

                    if (pc.Status != Pop3CommandStatus.Ok)
                        throw CreatePop3Exception (pc);

                    if (pc.Exception != null)
                        throw pc.Exception;

                    engine.State = Pop3EngineState.Transaction;
                    engine.QueryCapabilities (cancellationToken);
                    ProbeCapabilities (cancellationToken);
                    return;
                }
            }
            #endif

            // fall back to the classic USER & PASS commands...
            cred = credentials.GetCredential (uri, "USER");

            try {
                SendCommand (cancellationToken, "USER {0}", cred.UserName);
                SendCommand (cancellationToken, "PASS {0}", cred.Password);
            } catch (Pop3CommandException) {
                throw new AuthenticationException ();
            }

            engine.State = Pop3EngineState.Transaction;
            engine.QueryCapabilities (cancellationToken);
            ProbeCapabilities (cancellationToken);
        }
예제 #55
0
        private static KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(ICredentials credentials, Uri requestUri)
        {
            NetworkCredential nc = null;
            CURLAUTH curlAuthScheme = CURLAUTH.None;

            if (credentials != null)
            {
                // we collect all the schemes that are accepted by libcurl for which there is a non-null network credential.
                // But CurlHandler works under following assumption:
                //           for a given server, the credentials do not vary across authentication schemes.
                for (int i=0; i < s_authSchemePriorityOrder.Length; i++)
                {
                    NetworkCredential networkCredential = credentials.GetCredential(requestUri, s_authenticationSchemes[i]);
                    if (networkCredential != null)
                    {
                        curlAuthScheme |= s_authSchemePriorityOrder[i];
                        if (nc == null)
                        {
                            nc = networkCredential;
                        }
                        else if(!AreEqualNetworkCredentials(nc, networkCredential))
                        {
                            throw new PlatformNotSupportedException(SR.net_http_unix_invalid_credential);
                        }
                    }
                }
            }

            VerboseTrace("curlAuthScheme = " + curlAuthScheme);
            return new KeyValuePair<NetworkCredential, CURLAUTH>(nc, curlAuthScheme); ;
        }
 private Authorization DoAuthenticate(string challenge, WebRequest webRequest, ICredentials credentials, bool preAuthenticate)
 {
     HttpDigestChallenge challenge2;
     if (credentials == null)
     {
         return null;
     }
     HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;
     NetworkCredential credential = credentials.GetCredential(httpWebRequest.ChallengedUri, Signature);
     if (credential is SystemNetworkCredential)
     {
         if (WDigestAvailable)
         {
             return this.XPDoAuthenticate(challenge, httpWebRequest, credentials, preAuthenticate);
         }
         return null;
     }
     if (!preAuthenticate)
     {
         int startingPoint = AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature);
         if (startingPoint < 0)
         {
             return null;
         }
         challenge2 = HttpDigest.Interpret(challenge, startingPoint, httpWebRequest);
     }
     else
     {
         challenge2 = challengeCache.Lookup(httpWebRequest.ChallengedUri.AbsoluteUri) as HttpDigestChallenge;
     }
     if (challenge2 == null)
     {
         return null;
     }
     if (!CheckQOP(challenge2))
     {
         if (Logging.On)
         {
             Logging.PrintError(Logging.Web, SR.GetString("net_log_digest_qop_not_supported", new object[] { challenge2.QualityOfProtection }));
         }
         return null;
     }
     if (preAuthenticate)
     {
         challenge2 = challenge2.CopyAndIncrementNonce();
         challenge2.SetFromRequest(httpWebRequest);
     }
     if (credential == null)
     {
         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);
     }
     Authorization authorization = HttpDigest.Authenticate(challenge2, credential, computeSpn, channelBinding);
     if ((!preAuthenticate && webRequest.PreAuthenticate) && (authorization != null))
     {
         string[] strArray = (challenge2.Domain == null) ? new string[] { httpWebRequest.ChallengedUri.GetParts(UriComponents.SchemeAndServer, UriFormat.UriEscaped) } : challenge2.Domain.Split(singleSpaceArray);
         authorization.ProtectionRealm = (challenge2.Domain == null) ? null : strArray;
         for (int i = 0; i < strArray.Length; i++)
         {
             challengeCache.Add(strArray[i], challenge2);
         }
     }
     return authorization;
 }
 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;
 }
예제 #58
0
		/// <summary>
		/// Authenticate using the supplied credentials.
		/// </summary>
		/// <remarks>
		/// <para>If the IMAP server supports one or more SASL authentication mechanisms,
		/// then the SASL mechanisms that both the client and server support are tried
		/// in order of greatest security to weakest security. Once a SASL
		/// authentication mechanism is found that both client and server support,
		/// the credentials are used to authenticate.</para>
		/// <para>If the server does not support SASL or if no common SASL mechanisms
		/// can be found, then LOGIN command is used as a fallback.</para>
		/// <para>Note: To prevent the usage of certain authentication mechanisms,
		/// simply remove them from the the <see cref="AuthenticationMechanisms"/> hash
		/// set before calling the Authenticate() method.</para>
		/// </remarks>
		/// <param name="credentials">The user's credentials.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="credentials"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="System.InvalidOperationException">
		/// The <see cref="ImapClient"/> is already authenticated.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="MailKit.Security.AuthenticationException">
		/// Authentication using the supplied credentials has failed.
		/// </exception>
		/// <exception cref="MailKit.Security.SaslException">
		/// A SASL authentication error occurred.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// An IMAP protocol error occurred.
		/// </exception>
		public override void Authenticate (ICredentials credentials, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (credentials == null)
				throw new ArgumentNullException ("credentials");

			CheckDisposed ();
			CheckConnected ();

			if (engine.State >= ImapEngineState.Authenticated)
				throw new InvalidOperationException ("The ImapClient is already authenticated.");

			int capabilitiesVersion = engine.CapabilitiesVersion;
			var uri = new Uri ("imap://" + engine.Uri.Host);
			NetworkCredential cred;
			ImapCommand ic = null;
			SaslMechanism sasl;
			string id;

			foreach (var authmech in SaslMechanism.AuthMechanismRank) {
				if (!engine.AuthenticationMechanisms.Contains (authmech))
					continue;

				if ((sasl = SaslMechanism.Create (authmech, uri, credentials)) == null)
					continue;

				cancellationToken.ThrowIfCancellationRequested ();

				var command = string.Format ("AUTHENTICATE {0}", sasl.MechanismName);

				if ((engine.Capabilities & ImapCapabilities.SaslIR) != 0 && sasl.SupportsInitialResponse) {
					var ir = sasl.Challenge (null);
					command += " " + ir + "\r\n";
				} else {
					command += "\r\n";
				}

				ic = engine.QueueCommand (cancellationToken, null, command);
				ic.ContinuationHandler = (imap, cmd, text) => {
					string challenge;

					if (sasl.IsAuthenticated) {
						// The server claims we aren't done authenticating, but our SASL mechanism thinks we are...
						// Send an empty string to abort the AUTHENTICATE command.
						challenge = string.Empty;
					} else {
						challenge = sasl.Challenge (text);
					}

					var buf = Encoding.ASCII.GetBytes (challenge + "\r\n");
					imap.Stream.Write (buf, 0, buf.Length, cmd.CancellationToken);
					imap.Stream.Flush (cmd.CancellationToken);
				};

				engine.Wait (ic);

				if (ic.Response != ImapCommandResponse.Ok)
					continue;

				engine.State = ImapEngineState.Authenticated;

				cred = credentials.GetCredential (uri, sasl.MechanismName);
				id = GetSessionIdentifier (cred.UserName);
				if (id != identifier) {
					engine.FolderCache.Clear ();
					identifier = id;
				}

				// Query the CAPABILITIES again if the server did not include an
				// untagged CAPABILITIES response to the AUTHENTICATE command.
				if (engine.CapabilitiesVersion == capabilitiesVersion)
					engine.QueryCapabilities (cancellationToken);

				engine.QueryNamespaces (cancellationToken);
				engine.QuerySpecialFolders (cancellationToken);
				OnAuthenticated (ic.ResponseText);
				return;
			}

			if ((Capabilities & ImapCapabilities.LoginDisabled) != 0) {
				if (ic == null)
					throw new AuthenticationException ("The LOGIN command is disabled.");

				throw CreateAuthenticationException (ic);
			}

			// fall back to the classic LOGIN command...
			cred = credentials.GetCredential (uri, "DEFAULT");

			ic = engine.QueueCommand (cancellationToken, null, "LOGIN %S %S\r\n", cred.UserName, cred.Password);

			engine.Wait (ic);

			if (ic.Response != ImapCommandResponse.Ok)
				throw CreateAuthenticationException (ic);

			engine.State = ImapEngineState.Authenticated;

			id = GetSessionIdentifier (cred.UserName);
			if (id != identifier) {
				engine.FolderCache.Clear ();
				identifier = id;
			}

			// Query the CAPABILITIES again if the server did not include an
			// untagged CAPABILITIES response to the LOGIN command.
			if (engine.CapabilitiesVersion == capabilitiesVersion)
				engine.QueryCapabilities (cancellationToken);

			engine.QueryNamespaces (cancellationToken);
			engine.QuerySpecialFolders (cancellationToken);
			OnAuthenticated (ic.ResponseText);
		}
예제 #59
0
		public Authorization Authenticate (string challenge, WebRequest webRequest, ICredentials credentials) 
		{
			HttpWebRequest request = webRequest as HttpWebRequest;
			if (request == null)
				return null;
	
			NetworkCredential cred = credentials.GetCredential (request.RequestUri, "NTLM");
			if (cred == null)
				return null;

			string userName = cred.UserName;
			string domain = cred.Domain;
			string password = cred.Password;
			if (userName == null || userName == "")
				return null;

			if (String.IsNullOrEmpty (domain)) {
				int idx = userName.IndexOf ('\\');
				if (idx == -1) {
					idx = userName.IndexOf ('/');
				}
				if (idx >= 0) {
					domain = userName.Substring (0, idx);
					userName = userName.Substring (idx + 1);
				}
			}

			bool completed = false;
			if (message == null) {
				Type1Message type1 = new Type1Message ();
				type1.Domain = domain;
				type1.Host = ""; // MS does not send it
				type1.Flags |= NtlmFlags.NegotiateNtlm2Key;
				message = type1;
			} else if (message.Type == 1) {
				// Should I check the credentials?
				if (challenge == null) {
					message = null;
					return null;
				}

				Type2Message type2 = new Type2Message (Convert.FromBase64String (challenge));
				if (password == null)
					password = "";

				Type3Message type3 = new Type3Message (type2);
				type3.Username = userName;
				type3.Password = password;
				type3.Domain = domain;
				message = type3;
				completed = true;
			} else {
				// Should I check the credentials?
				// type must be 3 here
				if (challenge == null || challenge == String.Empty) {
					Type1Message type1 = new Type1Message ();
					type1.Domain = domain;
					type1.Host = ""; // MS does not send it
					message = type1;
				} else {
					completed = true;
				}
			}
			
			string token = "NTLM " + Convert.ToBase64String (message.GetBytes ());
			return new Authorization (token, completed);
		}
        public Authorization Authenticate(string challenge, WebRequest request, ICredentials credentials)
        {
            if (!challenge.StartsWith("GoogleLogin ", StringComparison.OrdinalIgnoreCase))
                return null;

            HttpWebRequest httpRequest = (HttpWebRequest)request;

            string service;
            string realm;
            ParseChallenge(challenge, out realm, out service);
            if (realm != "http://www.google.com/accounts/ClientLogin")
                return null;

            NetworkCredential cred = credentials.GetCredential(request.RequestUri, AuthenticationType);

            string auth = _gdataCred.GetCredentialsIfValid(cred.UserName, cred.Password, service);
            if (auth != null)
            {
                return new Authorization(auth, true);
            }
            else
            {
                try
                {
                    _gdataCred.EnsureLoggedIn(cred.UserName, cred.Password, service, !BlogClientUIContext.SilentModeForCurrentThread);
                    auth = _gdataCred.GetCredentialsIfValid(cred.UserName, cred.Password, service);
                    if (auth != null)
                        return new Authorization(auth, true);
                    else
                        return null;
                }
                catch (Exception e)
                {
                    Trace.Fail(e.ToString());
                    return null;
                }
            }
        }