예제 #1
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;
                }
            }
        }
예제 #2
0
        public bool GetServerCredentialsFromCache(
            Uri uri,
            out uint serverAuthScheme,
            [NotNullWhen(true)] out NetworkCredential?serverCredentials)
        {
            serverAuthScheme  = 0;
            serverCredentials = null;

            NetworkCredential?cred = null;

            lock (_credentialCacheLock)
            {
                foreach (uint authScheme in s_authSchemePriorityOrder)
                {
                    cred = _credentialCache.GetCredential(uri, s_authSchemeStringMapping[authScheme] !);
                    if (cred != null)
                    {
                        serverAuthScheme  = authScheme;
                        serverCredentials = cred;

                        return(true);
                    }
                }
            }

            return(false);
        }
예제 #3
0
파일: MailClient.cs 프로젝트: chubrik/Kit
        public static void Setup(
            string?host     = null,
            int?port        = null,
            string?userName = null,
            string?password = null,
            string?from     = null,
            string?to       = null)
        {
            if (host != null)
            {
                _host = host;
            }

            if (port != null)
            {
                _port = (int)port;
            }

            if (userName != null && password != null)
            {
                _credentials = new NetworkCredential(userName, password);
            }

            if (from != null)
            {
                _from = from;
            }

            if (to != null)
            {
                _to = to;
            }

            ReportService.Clients.Add(Instance);
        }
예제 #4
0
        private WebRequest CreateFtpWebRequest(string host, bool createFile = false, NetworkCredential?credentials = null)
        {
            FtpWebRequest ftpRequest;

            if (createFile)
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create($"{host}/beatpulse");

                if (credentials != null)
                {
                    ftpRequest.Credentials = credentials;
                }

                ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;

                using (var stream = ftpRequest.GetRequestStream())
                {
                    stream.Write(new byte[] { 0x0 }, 0, 1);
                }
            }
            else
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(host);

                if (credentials != null)
                {
                    ftpRequest.Credentials = credentials;
                }

                ftpRequest.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;
            }

            return(ftpRequest);
        }
예제 #5
0
        public bool OpenCredentialsDialog(string target, out NetworkCredential?networkCredential)
        {
            using (var dialog = new CredentialDialog())
            {
                dialog.WindowTitle     = Resources.Dialog_Title;
                dialog.MainInstruction = "Credentials for " + target;
                dialog.Content         = "Enter Personal Access Tokens in the username field.";
                dialog.Target          = target;

                try
                {
                    if (dialog.ShowDialog())
                    {
                        networkCredential = dialog.Credentials;
                        return(true);
                    }
                }
                catch (Exception e)
                {
                    Show(e.Message, MessageLevel.Error);
                }

                networkCredential = null;
                return(false);
            }
        }
예제 #6
0
 public DownloadTask(string uid, string uri, Dictionary <string, string?>?headers, NetworkCredential?credential)
 {
     Uid        = uid;
     Uri        = uri;
     Headers    = headers;
     Credential = credential;
 }
예제 #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);
        }
        public Authorization?Authenticate(string?challenge, NetworkCredential?credential, object sessionCookie, string?spn, ChannelBinding?channelBindingToken)
        {
            lock (_sessions)
            {
                NetworkCredential?cachedCredential;
                if (!_sessions.TryGetValue(sessionCookie, out cachedCredential))
                {
                    if (credential == null || ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
                    {
                        return(null);
                    }

                    _sessions[sessionCookie] = credential;

                    string userName = credential.UserName;
                    string domain   = credential.Domain;

                    if (domain != null && domain.Length > 0)
                    {
                        userName = domain + "\\" + userName;
                    }

                    return(new Authorization(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(userName)), false));
                }
                else
                {
                    _sessions.Remove(sessionCookie);

                    return(new Authorization(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(cachedCredential.Password)), true));
                }
            }
        }
예제 #9
0
        public bool OpenCredentialsDialog(string target, out NetworkCredential?networkCredential)
        {
            DiagnosticsClient.TrackEvent("UIServices_OpenCredentialsDialog");
            using var dialog = new CredentialDialog
                  {
                      WindowTitle     = Resources.Dialog_Title,
                      MainInstruction = "Credentials for " + target,
                      Content         = "Enter Personal Access Tokens in the username field.",
                      Target          = target
                  };

            try
            {
                if (dialog.ShowDialog())
                {
                    networkCredential = dialog.Credentials;
                    return(true);
                }
            }
            catch (Exception e)
            {
                Show(e.Message, MessageLevel.Error);
            }

            networkCredential = null;
            return(false);
        }
예제 #10
0
        protected void SetCredentials(SettingLevel settingLevel, string name, NetworkCredential?value)
        {
            var targetName = GetWindowsCredentialsTarget(name, settingLevel);

            Validates.NotNull(targetName);
            Credentials.AddOrUpdate(targetName, value, (s, credential) => value);
        }
        private static void ProvideCredential(ClientCredentials client, NetworkCredential?credential)
        {
            client.Windows.AllowedImpersonationLevel
                = TokenImpersonationLevel.Impersonation;

            client.Windows.ClientCredential
                = credential ?? CredentialCache.DefaultNetworkCredentials;
        }
예제 #12
0
 public FtpClient(NetworkCredentialOptions?options, ILogService log)
 {
     _log = log;
     if (options != null)
     {
         Credential = options.GetCredential();
     }
 }
예제 #13
0
 public HttpEnvironmentProxyCredentials(Uri?httpProxy, NetworkCredential?httpCred,
                                        Uri?httpsProxy, NetworkCredential?httpsCred)
 {
     _httpCred   = httpCred;
     _httpsCred  = httpsCred;
     _httpProxy  = httpProxy;
     _httpsProxy = httpsProxy;
 }
예제 #14
0
 public DownloadBlockTask(string uid, string uri, long offset, long length, Dictionary <string, string?>?headers, NetworkCredential?credential)
 {
     Uid        = uid;
     Uri        = uri;
     Offset     = offset;
     Length     = length;
     Headers    = headers;
     Credential = credential;
 }
예제 #15
0
 /// <summary>
 /// Creates a new Open Service Broker Client.
 /// </summary>
 /// <param name="uri">The base URI of the Open Service Broker API instance (without the version number).</param>
 /// <param name="credentials">Optional HTTP Basic Auth credentials used to authenticate against the REST interface.</param>
 public OpenServiceBrokerClient(Uri uri, NetworkCredential?credentials = null)
     : base(uri, errorHandler: new OpenServiceBrokerErrorHandler())
 {
     if (credentials != null)
     {
         HttpClient.AddBasicAuth(credentials);
     }
     SetApiVersion(DefaultApiVersion);
 }
 public IReportExecutionSoapClient CreateExecutionClient(NetworkCredential?credential = null)
 {
     return(CreateClient <
                ReportExecutionServiceSoapClient,
                ReportExecutionServiceSoap
                >(
                () => new ReportExecutionServiceSoapClient(Binding, ExecutionAddress),
                credential
                ));
 }
예제 #17
0
        public NetworkCredential?GetCredential(Uri uriPrefix, string authType)
        {
            if (uriPrefix == null)
            {
                throw new ArgumentNullException(nameof(uriPrefix));
            }
            if (authType == null)
            {
                throw new ArgumentNullException(nameof(authType));
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this, uriPrefix, authType);
            }

            if (_cache == null)
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Info(this, "CredentialCache::GetCredential short-circuiting because the dictionary is null.");
                }
                return(null);
            }

            int longestMatchPrefix = -1;
            NetworkCredential?mostSpecificMatch = null;

            // Enumerate through every credential in the cache
            foreach (KeyValuePair <CredentialKey, NetworkCredential> pair in _cache)
            {
                CredentialKey key = pair.Key;

                // Determine if this credential is applicable to the current Uri/AuthType
                if (key.Match(uriPrefix, authType))
                {
                    int prefixLen = key.UriPrefixLength;

                    // Check if the match is better than the current-most-specific match
                    if (prefixLen > longestMatchPrefix)
                    {
                        // Yes: update the information about currently preferred match
                        longestMatchPrefix = prefixLen;
                        mostSpecificMatch  = pair.Value;
                    }
                }
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(this, $"Returning {(mostSpecificMatch == null ? "null" : "(" + mostSpecificMatch.UserName + ":" + mostSpecificMatch.Domain + ")")}");
            }

            return(mostSpecificMatch);
        }
예제 #18
0
            internal ResultsEnumerator(SearchResultCollection results, string?parentUserName, string?parentPassword, AuthenticationTypes parentAuthenticationType)
            {
                if (parentUserName != null && parentPassword != null)
                {
                    _parentCredentials = new NetworkCredential(parentUserName, parentPassword);
                }

                _parentAuthenticationType = parentAuthenticationType;
                _results     = results;
                _initialized = false;
            }
예제 #19
0
 public FtpClient(
     NetworkCredentialOptions?options,
     ILogService log,
     SecretServiceManager secretService)
 {
     _log = log;
     if (options != null)
     {
         Credential = options.GetCredential(secretService);
     }
 }
예제 #20
0
            private void Authenticate()
            {
                //if no credentials were supplied, try anonymous
                //servers don't appear to anounce that they support anonymous login.
                if (_connection._credentials != null)
                {
                    while (++_currentModule < _connection._authenticationModules.Length)
                    {
                        //only authenticate if the auth protocol is supported
                        ISmtpAuthenticationModule module = _connection._authenticationModules[_currentModule];
                        if (!_connection.AuthSupported(module))
                        {
                            continue;
                        }

                        NetworkCredential?credential = _connection._credentials.GetCredential(_host, _port, module.AuthenticationType);
                        if (credential == null)
                        {
                            continue;
                        }
                        Authorization?auth = _connection.SetContextAndTryAuthenticate(module, credential, _outerResult);

                        if (auth != null && auth.Message != null)
                        {
                            IAsyncResult result = AuthCommand.BeginSend(_connection, _connection._authenticationModules[_currentModule].AuthenticationType, auth.Message, s_authenticateCallback, this);
                            if (!result.CompletedSynchronously)
                            {
                                return;
                            }

                            LineInfo info = AuthCommand.EndSend(result);

                            if ((int)info.StatusCode == 334)
                            {
                                _authResponse = info.Line;
                                if (!AuthenticateContinue())
                                {
                                    return;
                                }
                            }
                            else if ((int)info.StatusCode == 235)
                            {
                                module.CloseContext(_connection);
                                _connection._isConnected = true;
                                break;
                            }
                        }
                    }
                }

                _connection._isConnected = true;
                InvokeCallback();
            }
예제 #21
0
        public static INetworkCredential?ToInterface(this NetworkCredential?credential)
        {
            if (credential == null)
            {
                return(null);
            }

            if (ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
            {
                return(CredentialCacheAdapter.DefaultNetworkCredentials);
            }

            return(new NetworkCredentialAdapter(credential));
        }
예제 #22
0
        public Authorization?Authenticate(string?challenge, NetworkCredential?credential, object sessionCookie, string?spn, ChannelBinding?channelBindingToken)
        {
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this, "Authenticate");
            }
            try
            {
                lock (_sessions)
                {
                    NTAuthentication?clientContext;
                    if (!_sessions.TryGetValue(sessionCookie, out clientContext))
                    {
                        if (credential == null)
                        {
                            return(null);
                        }

                        _sessions[sessionCookie] =
                            clientContext        =
                                new NTAuthentication(false, "Ntlm", credential, spn, ContextFlagsPal.Connection, channelBindingToken);
                    }

                    string?resp = clientContext.GetOutgoingBlob(challenge);

                    if (!clientContext.IsCompleted)
                    {
                        return(new Authorization(resp, false));
                    }
                    else
                    {
                        _sessions.Remove(sessionCookie);
                        return(new Authorization(resp, true));
                    }
                }
            }
            // From reflected type NTAuthentication in System.Net.Security.
            catch (NullReferenceException)
            {
                return(null);
            }
            finally
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Exit(this, "Authenticate");
                }
            }
        }
예제 #23
0
 public WebDavClientWrapper(NetworkCredentialOptions?options, ILogService log, ProxyService proxy)
 {
     _log = log;
     if (options != null && options.UserName != null)
     {
         _credential = options.GetCredential();
     }
     _proxy  = proxy;
     _client = new WebDavClient(new WebDavClientParams()
     {
         Proxy = _proxy.GetWebProxy(),
         UseDefaultCredentials = _proxy.UseSystemProxy,
         Credentials           = _credential
     });
 }
예제 #24
0
        /// <devdoc>
        /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class.
        /// </devdoc>
        public DirectoryEntry(string?path, string?username, string?password, AuthenticationTypes authenticationType) : this(path)
        {
            _credentials = new NetworkCredential(username, password);
            if (username == null)
            {
                _userNameIsNull = true;
            }

            if (password == null)
            {
                _passwordIsNull = true;
            }

            _authenticationType = authenticationType;
        }
예제 #25
0
 private bool TryAddUriCredentials(Uri feedUri, out NetworkCredential?credentials)
 {
     // Support username and password in feed URL as specified in RFC 1738
     if (!string.IsNullOrEmpty(feedUri.UserInfo))
     {
         var userInfoSplitted = feedUri.UserInfo.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
         if (userInfoSplitted.Length >= 2)
         {
             credentials = new NetworkCredential(userInfoSplitted[0], userInfoSplitted[1]);
             Add(credentials, feedUri);
             return(true);
         }
     }
     credentials = null;
     return(false);
 }
예제 #26
0
        private static SafeNativeMemory PackAuthenticationBuffer([CanBeNull] NetworkCredential?credential)
        {
            var userName = credential?.UserName;

            if (string.IsNullOrEmpty(userName))
            {
                return(new SafeNativeMemory());
            }

            var inCredSize = 0;

            NativeMethods.CredPackAuthenticationBuffer(0, userName, string.Empty, IntPtr.Zero, ref inCredSize);
            var buffer = new SafeNativeMemory(inCredSize);

            NativeMethods.CredPackAuthenticationBuffer(0, userName, string.Empty, buffer.DangerousGetHandle(), ref inCredSize);
            return(buffer);
        }
예제 #27
0
        public NetworkCredential?GetCredential(string host, int port, string authenticationType)
        {
            if (host == null)
            {
                throw new ArgumentNullException(nameof(host));
            }
            if (authenticationType == null)
            {
                throw new ArgumentNullException(nameof(authenticationType));
            }
            if (host.Length == 0)
            {
                throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(host)), nameof(host));
            }
            if (port < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(port));
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this, host, port, authenticationType);
            }

            if (_cacheForHosts == null)
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Info(this, "CredentialCache::GetCredential short-circuiting because the dictionary is null.");
                }
                return(null);
            }

            var key = new CredentialHostKey(host, port, authenticationType);

            NetworkCredential?match = null;

            _cacheForHosts.TryGetValue(key, out match);

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(this, $"Returning {((match == null) ? "null" : "(" + match.UserName + ":" + match.Domain + ")")}");
            }

            return(match);
        }
예제 #28
0
        public static bool TryGetCredentials(string registry, out NetworkCredential?credential)
        {
            credential = default;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                if (WindowsCredentials.CredRead(registry, WindowsCredentials.CRED_TYPE.GENERIC, 0, out var credPtr))
                {
                    var cred = (WindowsCredentials.CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(WindowsCredentials.CREDENTIAL)) !;
                    credential = new NetworkCredential(userName: cred.userName,
                                                       password: Marshal.PtrToStringAnsi(cred.credentialBlob, cred.credentialBlobSize));
                    return(true);
                }
            }

            // TODO: Retrieve credentials stored in OS X keychain

            return(false);
        }
예제 #29
0
        /// <summary>
        /// Executes an action while impersonating a user.
        /// </summary>
        /// <param name="credentials"><see cref="ICredentials"/> for the user to use for impersonation.</param>
        /// <param name="netOnly">Whether impersonation should be used for network access only.</param>
        /// <param name="action">The action to execute in the impersonation context.</param>
        public static void RunImpersonated(this ICredentials credentials, bool netOnly, Action action)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            NetworkCredential?Credentials = credentials.GetCredential(s_HttpLocalhost, string.Empty);

            if (Credentials == null)
            {
                throw new UnauthorizedAccessException();
            }

            using SafeAccessTokenHandle Token = new SafeAccessTokenHandle(ImpersonationSettings.LogonUser(Credentials.Domain, Credentials.UserName, Credentials.SecurePassword, netOnly));

            WindowsIdentity.RunImpersonated(Token, action);
        }
        static int Execute(
            string command,
            string arguments,
            string workingDirectory,
            out StringBuilder debugMessages,
            out StringBuilder infoMessages,
            out StringBuilder errorMessages,
            NetworkCredential?networkCredential,
            IDictionary <string, string>?customEnvironmentVariables,
            CancellationToken cancel
            )
        {
            var debug    = new StringBuilder();
            var info     = new StringBuilder();
            var error    = new StringBuilder();
            var exitCode = ShellExecutor.ExecuteCommand(
                command,
                arguments,
                workingDirectory,
                x =>
            {
                Console.WriteLine($"{DateTime.UtcNow} DBG: {x}");
                debug.Append(x);
            },
                x =>
            {
                Console.WriteLine($"{DateTime.UtcNow} INF: {x}");
                info.Append(x);
            },
                x =>
            {
                Console.WriteLine($"{DateTime.UtcNow} ERR: {x}");
                error.Append(x);
            },
                networkCredential,
                customEnvironmentVariables,
                cancel);

            debugMessages = debug;
            infoMessages  = info;
            errorMessages = error;

            return(exitCode);
        }