Example #1
0
 public static RetsSession Create(string baseUrl, string loginUrl, int port, string userName, string password, string userAgent, string userAgentAuth, string retsVersion, AuthenticationMethod authMethod)
 {
     return new RetsSession
     {
         SessionInfo = SessionInfo.Create(baseUrl, loginUrl, port, userName, password, userAgent, userAgentAuth, retsVersion, authMethod)
     };
 }
Example #2
0
 public PopClient( string host, int port, string username, string password, AuthenticationMethod authenticationMethod, SslProtocols sslProtocol )
     : this()
 {
     Host = host;
     Port = port;
     Username = username;
     Password = password;
     AuthenticationMethod = authenticationMethod;
     SslProtocol = sslProtocol;
 }
 public IAutenticationProvider Create(AuthenticationMethod method)
 {
     switch (method)
     {
         case AuthenticationMethod.ByPass :
             return _dependencyResolver.Resolve<IAutenticationProvider>(ByPassProviderKey);
         default:
             throw new ArgumentException();
     }
 }
        public void whenBuildingAuthenticationMethodWithAPIValueKBAThenKBAAuthenticationMethodIsReturned()
        {
            string expectedSDKValue = "KBA";


            AuthenticationMethod classUnderTest = AuthenticationMethod.valueOf("KBA");
            String actualSDKValue = classUnderTest.getSdkValue();


            Assert.AreEqual(expectedSDKValue, actualSDKValue);
        }
        public void whenBuildingAuthenticationMethodWithUnknownAPIValueThenUNRECOGNIZEDAuthenticationMethodIsReturned()
        {
            string expectedSDKValue = "UNRECOGNIZED";


            AuthenticationMethod classUnderTest = AuthenticationMethod.valueOf("ThisAuthenticationMethodDoesNotExistINSDK");
            String actualSDKValue = classUnderTest.getSdkValue();


            Assert.AreEqual(expectedSDKValue, actualSDKValue);
        }
Example #6
0
 private void CheckObsoleteAuth()
 {
     if (!string.IsNullOrEmpty(BasicAuthUsername) && !string.IsNullOrEmpty(BasicAuthPassword))
     {
         LogLog.Warn(GetType(), "BasicAuthUsername & BasicAuthPassword tags are obsolete, Please use AuthenticationMethod new tag");
         var auth = new BasicAuthenticationMethod {
             Username = BasicAuthUsername, Password = BasicAuthPassword
         };
         AuthenticationMethod.AddBasic(auth);
     }
 }
 public void TestAuthenticationMethod()
 {
     foreach (AuthenticationMethod authenticationMethod in AuthenticationMethod.Values())
     {
         Assert.IsNotNull(authenticationMethod.ToString());
         Assert.IsNotEmpty(authenticationMethod.ToString());
     }
     Assert.AreEqual(1, AuthenticationMethod.CHALLENGE);
     Assert.AreEqual("SMS", (string)AuthenticationMethod.SMS);
     Assert.AreEqual("SMS", AuthenticationMethod.SMS.GetName());
 }
        Create_IfServiceForAuthMethodDoesNotExist_ThrowsNotImplementedException(AuthenticationMethod authMethod)
        {
            var context = new ApiContext(It.IsAny <Environments>())
            {
                AuthenticationMethod = authMethod
            };

            Assert.Throws <NotImplementedException>(() =>
            {
                AuthenticationServiceFactory.Create(context, It.IsAny <string>(), It.IsAny <string>());
            });
        }
Example #9
0
        public TRequest CreateRequest <TRequest>(AuthenticationMethod method = AuthenticationMethod.Bearer) where TRequest : JsonWebRequest, new()
        {
            var request = new TRequest
            {
                RootUri              = _baseUri,
                SessionManager       = _sessionManager,
                AuthenticationMethod = method,
            };

            request.RegisterConverters(_converters);
            return(request);
        }
Example #10
0
        /// <summary>
        /// Constructs the authorization by combining the customer id
        /// from the credential with the stringToSign hashed with
        /// the secret key.
        /// </summary>
        /// <param name="stringToSign">
        /// The stringToSign that is used for authentication.
        /// </param>
        /// <param name="authMethod">The method used for authentication.</param>
        /// <returns>The authorization string.</returns>
        public string ConstructAuthorizationString(
            string stringToSign,
            AuthenticationMethod authMethod)
        {
            CheckArgument.NotNullOrEmpty(stringToSign, "stringToSign");

            return(string.Format(
                       CultureInfo.InvariantCulture,
                       "TSA {0}:{1}",
                       this.credential.CustomerId,
                       this.ComputeHash(stringToSign, authMethod)));
        }
 internal static AuthenticationMethod GetAuthenticationMethod(object authenticationMethodObject)
 {
     if (authenticationMethodObject is AuthenticationMethodFlags)
     {
         AuthenticationMethod authenticationMethod = (AuthenticationMethod)authenticationMethodObject;
         if (EnumValidator.IsValidValue <AuthenticationMethod>(authenticationMethod))
         {
             return(authenticationMethod);
         }
     }
     return(AuthenticationMethod.None);
 }
Example #12
0
        public SynoReportViaSSH(DSMHost host, Func <string, string> getPassPhraseMethod, Func <DSMKeyboardInteractiveEventArgs, string> getInteractiveMethod, IProxySettings proxy = null)
        {
            bool canceled = false;

            RmExecutionMode = ConsoleCommandMode.InteractiveSudo;

            _host = host ?? throw new ArgumentNullException(nameof(host));
            if (getPassPhraseMethod == null)
            {
                throw new ArgumentNullException(nameof(getPassPhraseMethod));
            }
            if (getInteractiveMethod == null)
            {
                throw new ArgumentNullException(nameof(getInteractiveMethod));
            }
            _interactiveMethod = getInteractiveMethod;

            int i = 0;

            AuthenticationMethod[] methods = new AuthenticationMethod[host.AuthenticationSection.Count];
            foreach (var m in host.AuthenticationMethods)
            {
                methods[i++] = m.getAuthenticationMethod(host.UserName, host.StorePassPhrases, getPassPhraseMethod, getInteractiveMethod, out canceled);
            }
            if (!canceled)
            {
                if (proxy != null)
                {
                    ProxyTypes proxypath;
                    if (!Enum.TryParse(proxy.ProxyType, true, out proxypath))
                    {
                        proxypath = ProxyTypes.None;
                    }
                    _ci = new ConnectionInfo(host.Host, host.Port, host.UserName, proxypath, proxy.Host, proxy.Port, proxy.UserName, proxy.Password, methods);
                }
                else
                {
                    _ci = new ConnectionInfo(host.Host, host.Port, host.UserName, methods);
                }

                _ci.AuthenticationBanner += AuthorizationBannerAction;

                foreach (var am in _ci.AuthenticationMethods)
                {
                    KeyboardInteractiveAuthenticationMethod kb = am as KeyboardInteractiveAuthenticationMethod;
                    if (kb != null)
                    {
                        kb.AuthenticationPrompt += AuthenticationPromptAction;
                    }
                }
            }
        }
Example #13
0
        private void SetHeaders(HttpWebRequest webRequest, string url, string requestString)
        {
            var requestData = new RequestData {
                WebRequest = webRequest, Url = url, RequestString = requestString
            };

            var authorizationHeaderValue = AuthenticationMethod.CreateAuthenticationHeader(requestData);

            if (!string.IsNullOrEmpty(authorizationHeaderValue))
            {
                webRequest.Headers[HttpRequestHeader.Authorization] = authorizationHeaderValue;
            }
        }
Example #14
0
        private void btnTest_Click(object sender, EventArgs e)
        {
            if (!currentThread.IsAlive && checkInputs())
            {
                currentThread = new Thread(ExecuteThread);
                currentThread.IsBackground = true;

                test = true;
                progressBar.Value = 0;
                authMethod        = (AuthenticationMethod)cmbAuthMethod.SelectedIndex; //hack for getting the auth method from a separate thread
                currentThread.Start();
            }
        }
Example #15
0
        /// <summary>
        /// Maps the AuthenticationMethod enumeration to the string used in headers.
        /// </summary>
        /// <param name="authMethod">The authentication method.</param>
        /// <returns>The header string for the authentication method.</returns>
        public string MapAuthenticationMethodToHeaderString(AuthenticationMethod authMethod)
        {
            switch (authMethod)
            {
            case AuthenticationMethod.HmacSha1:
                return("hmac-sha1");

            case AuthenticationMethod.HmacSha256:
                return("hmac-sha256");

            default:
                throw new NotSupportedException("Only HMAC SHA1 and SHA256 authentication is currently supported");
            }
        }
Example #16
0
        //the errors tab will pop up and ask for credentials
        //entering the credentials seems to be more reliable than loading them (credential loading seems buggy!)
        private void Authenticate(AuthenticationMethod authenticationMethod)
        {
            switch (authenticationMethod)
            {
            case AuthenticationMethod.UsernamePassword:
                EnterCredentialsUsernameAndPassword();
                break;

            case AuthenticationMethod.KeyOIDCToken:
                EnterCredentialsKeyOIDCToken();
                break;
            }
            ClickSetCredentialsMessageBoxOK();
        }
        private void AuthenticationSuccessful(RequestMessage message, UserauthArgs args,
                                              AuthenticationMethod method)
        {
            this.Session.AuthenticationMethods[method] = true;

            var remainingAuthenticationMethods = this.GetRemainingAuthenticationMethods();

            if (remainingAuthenticationMethods.Count > 0)
            {
                this.Session.SendMessage(new FailureMessage(remainingAuthenticationMethods, true));
                return;
            }
            this.AuthenticationSuccessful(message, args);
        }
Example #18
0
        public NTStatus Login(string domainName, string userName, string password, AuthenticationMethod authenticationMethod)
        {
            if (!m_isConnected)
            {
                throw new InvalidOperationException("A connection must be successfully established before attempting login");
            }

            byte[] negotiateMessage = NTLMAuthenticationHelper.GetNegotiateMessage(m_securityBlob, domainName, authenticationMethod);
            if (negotiateMessage == null)
            {
                return(NTStatus.SEC_E_INVALID_TOKEN);
            }

            SessionSetupRequest request = new SessionSetupRequest();

            request.SecurityMode   = SecurityMode.SigningEnabled;
            request.SecurityBuffer = negotiateMessage;
            TrySendCommand(request);
            SMB2Command response = WaitForCommand(SMB2CommandName.SessionSetup);

            if (response != null)
            {
                if (response.Header.Status == NTStatus.STATUS_MORE_PROCESSING_REQUIRED && response is SessionSetupResponse)
                {
                    byte[] authenticateMessage = NTLMAuthenticationHelper.GetAuthenticateMessage(((SessionSetupResponse)response).SecurityBuffer, domainName, userName, password, authenticationMethod, out m_sessionKey);
                    if (authenticateMessage == null)
                    {
                        return(NTStatus.SEC_E_INVALID_TOKEN);
                    }

                    m_sessionID            = response.Header.SessionID;
                    request                = new SessionSetupRequest();
                    request.SecurityMode   = SecurityMode.SigningEnabled;
                    request.SecurityBuffer = authenticateMessage;
                    TrySendCommand(request);
                    response = WaitForCommand(SMB2CommandName.SessionSetup);
                    if (response != null)
                    {
                        m_isLoggedIn = (response.Header.Status == NTStatus.STATUS_SUCCESS);
                        return(response.Header.Status);
                    }
                }
                else
                {
                    return(response.Header.Status);
                }
            }
            return(NTStatus.STATUS_INVALID_SMB);
        }
Example #19
0
        public void Authenticate(string username, string password, AuthenticationMethod authenticationMethod)
        {
            base.CheckDisposed();
            if (username == null)
            {
                throw new ArgumentNullException("username");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (this.State != ConnectionState.Authorization)
            {
                throw new Exception("You have to be connected and not authorized when trying to authorize yourself");
            }
            try
            {
                switch (authenticationMethod)
                {
                case AuthenticationMethod.UsernameAndPassword:
                    this.AuthenticateUsingUserAndPassword(username, password);
                    break;

                case AuthenticationMethod.Apop:
                    this.AuthenticateUsingApop(username, password);
                    break;

                case AuthenticationMethod.Auto:
                    if (this.ApopSupported)
                    {
                        this.AuthenticateUsingApop(username, password);
                    }
                    else
                    {
                        this.AuthenticateUsingUserAndPassword(username, password);
                    }
                    break;

                case AuthenticationMethod.CramMd5:
                    this.AuthenticateUsingCramMd5(username, password);
                    break;
                }
            }
            catch (Exception e)
            {
                throw new Exception("Problem logging in using method .Server response was: " + this.LastServerResponse, e);
            }
            this.State = ConnectionState.Transaction;
        }
Example #20
0
 public void SignRequest(HttpClient client, AuthenticationMethod method = AuthenticationMethod.Bearer)
 {
     if (method != AuthenticationMethod.None)
     {
         if (_client.IsConnected)
         {
             OnAssignAuthenticationMethod(client, method);
         }
         else
         {
             throw new WebProxyException(
                       "Unable to sign request as the session manager is not currently connected and AutoConnect is false.");
         }
     }
 }
Example #21
0
        public void ConstructorWithEnvironmentAndCredentials_IfAuthenticationMethodIsSet_InitializesCorrectly(
            Environments env,
            string username,
            string password,
            AuthenticationMethod authenticationMethod)
        {
            var context = new ApiContext(env, username, password, authenticationMethod);

            Assert.AreEqual(env, context.Environment);
            Assert.AreEqual(username, context.UserName);
            Assert.AreEqual(password, context.Password);
            Assert.AreEqual(authenticationMethod, context.AuthenticationMethod);
            Assert.Null(context.AccessToken);
            Assert.Null(context.Affiliate);
        }
        /// <summary>
        /// Sets the authentication method of the specified context.
        /// </summary>
        /// <param name="contextId">The ID of the context.</param>
        /// <param name="authenticationMethod">The authentication method configuration.</param>
        public void SetAuthenticationMethod(int contextId, AuthenticationMethod authenticationMethod)
        {
            var parameters = new Parameters
            {
                { "contextId", contextId },
                { "authMethodName", authenticationMethod.MethodName }
            };

            foreach (var parameter in authenticationMethod.Parameters)
            {
                parameters.Add(parameter.Key, parameter.Value);
            }

            CallAction("setAuthenticationMethod", parameters);
        }
Example #23
0
        public Plugin(IEnumerable <KeyValuePair <string, string> > deviceKVP)
        {
            _config    = new Configuration();
            _devices   = deviceKVP.OrderBy((d) => d.Key);
            _output    = new Dictionary <string, StringBuilder>();
            AuthMethod = CreateAuthMethod();

            Console.WriteLine();
            Console.WriteLine("Prometheus Plugin Started...");
            Console.WriteLine();

            if (_config.Settings.Enabled)
            {
                Generate();
            }
        }
Example #24
0
 ///<summary>Called when client has been notified of the selected authentication method.</summary>
 ///<param name="ar">The result of the asynchronous operation.</param>
 private void OnAuthSent(IAsyncResult ar)
 {
     try
     {
         if (Connection.EndSend(ar) <= 0 || AuthenticationMethod == null)
         {
             Dispose(false);
             return;
         }
         AuthenticationMethod.StartAuthentication(Connection, OnAuthenticationComplete);
     }
     catch
     {
         Dispose(false);
     }
 }
Example #25
0
        public Plugin(IEnumerable <OxidizedInputModel> devices)
        {
            _config    = new Configuration();
            _devices   = devices.OrderBy((x) => x.Name);
            _output    = new StringBuilder();
            AuthMethod = CreateAuthMethod();

            Console.WriteLine();
            Console.WriteLine("Oxidized Plugin Started...");
            Console.WriteLine();

            if (_config.Settings.Enabled)
            {
                Generate();
            }
        }
Example #26
0
        private void UpdateInternalAndExternalAuthenticationMethods()
        {
            List <AuthenticationMethod> list = new List <AuthenticationMethod>();

            if (base.InternalAuthenticationMethods != null)
            {
                list.AddRange(base.InternalAuthenticationMethods);
            }
            ADExchangeServiceVirtualDirectory.AddOrRemoveAuthenticationMethod(list, this.LiveIdNegotiateAuthentication, new AuthenticationMethod[]
            {
                AuthenticationMethod.LiveIdNegotiate
            });
            ADExchangeServiceVirtualDirectory.AddOrRemoveAuthenticationMethod(list, this.AdfsAuthentication, new AuthenticationMethod[]
            {
                AuthenticationMethod.Adfs
            });
            ADExchangeServiceVirtualDirectory.AddOrRemoveAuthenticationMethod(list, this.WSSecurityAuthentication, new AuthenticationMethod[]
            {
                AuthenticationMethod.WSSecurity
            });
            ADExchangeServiceVirtualDirectory.AddOrRemoveAuthenticationMethod(list, this.LiveIdBasicAuthentication, new AuthenticationMethod[]
            {
                AuthenticationMethod.LiveIdBasic
            });
            List <AuthenticationMethod> authenticationMethods = list;
            bool?authenticationMethodFlag = this.BasicAuthentication;

            AuthenticationMethod[] applicableAuthenticationMethods = new AuthenticationMethod[1];
            ADExchangeServiceVirtualDirectory.AddOrRemoveAuthenticationMethod(authenticationMethods, authenticationMethodFlag, applicableAuthenticationMethods);
            ADExchangeServiceVirtualDirectory.AddOrRemoveAuthenticationMethod(list, this.DigestAuthentication, new AuthenticationMethod[]
            {
                AuthenticationMethod.Digest
            });
            ADExchangeServiceVirtualDirectory.AddOrRemoveAuthenticationMethod(list, this.WindowsAuthentication, new AuthenticationMethod[]
            {
                AuthenticationMethod.Ntlm,
                AuthenticationMethod.WindowsIntegrated
            });
            ADExchangeServiceVirtualDirectory.AddOrRemoveAuthenticationMethod(list, this.OAuthAuthentication, new AuthenticationMethod[]
            {
                AuthenticationMethod.OAuth
            });
            MultiValuedProperty <AuthenticationMethod> multiValuedProperty = new MultiValuedProperty <AuthenticationMethod>(list);

            base.InternalAuthenticationMethods = multiValuedProperty;
            base.ExternalAuthenticationMethods = multiValuedProperty;
        }
Example #27
0
        private static string GetAuthenticationMethodName(AuthenticationMethod authenticationMethod)
        {
            switch (authenticationMethod)
            {
            case AuthenticationMethod.PublicKey:
                return("publickey");

            case AuthenticationMethod.Password:
                return("password");

            case AuthenticationMethod.HostBased:
                return("hostbased");

            default:
                return("none");
            }
        }
Example #28
0
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!currentThread.IsAlive && checkInputs())
            {
                currentThread = new Thread(ExecuteThread);
                currentThread.IsBackground = true;

                if (MessageBox.Show("This operation cannot be undone. Would you like to proceed?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                {
                    return;
                }

                test = false;
                progressBar.Value = 0;
                authMethod        = (AuthenticationMethod)cmbAuthMethod.SelectedIndex; //hack for getting the auth method from a separate thread
                currentThread.Start();
            }
        }
        void NegotiateVersion(out AuthenticationMethod[] methods)
        {
            _c.SendVersion(new Version(3, 8));

            _clientVersion = _c.ReceiveVersion();
            if (_clientVersion == new Version(3, 8))
            {
                methods = new[]
                {
                    _options.AuthenticationMethod == AuthenticationMethod.Password
                        ? AuthenticationMethod.Password : AuthenticationMethod.None
                };
            }
            else
            {
                methods = new AuthenticationMethod[0];
            }
        }
        /// <summary>
        /// Default Constructor for the DropboxClient
        /// </summary>
        /// <param name="apiKey">The Api Key to use for the Dropbox Requests</param>
        /// <param name="appSecret">The Api Secret to use for the Dropbox Requests</param>
        /// <param name="authenticationMethod">The authentication method to use.</param>
        public DropBoxClient(string apiKey, string appSecret, AuthenticationMethod authenticationMethod = AuthenticationMethod.OAuth2)
        {
            Guard.NotNullOrEmpty(() => apiKey, apiKey);
            Guard.NotNullOrEmpty(() => appSecret, appSecret);

            this.LoadClient( );
            this._apiKey               = apiKey;
            this._appsecret            = appSecret;
            this._authenticationMethod = authenticationMethod;
            this.UserLogin             = null;

            var js = new JsonMediaTypeFormatter( );

            js.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));

            this._mediaTypeFormatters = new List <MediaTypeFormatter> {
                js
            };
        }
Example #31
0
        /// <summary>
        /// Create new navigation property to methods for me
        /// <param name="body"></param>
        /// <param name="requestConfiguration">Configuration for the request such as headers, query parameters, and middleware options.</param>
        /// </summary>
        public RequestInformation CreatePostRequestInformation(AuthenticationMethod body, Action <MethodsRequestBuilderPostRequestConfiguration> requestConfiguration = default)
        {
            _ = body ?? throw new ArgumentNullException(nameof(body));
            var requestInfo = new RequestInformation {
                HttpMethod     = Method.POST,
                UrlTemplate    = UrlTemplate,
                PathParameters = PathParameters,
            };

            requestInfo.SetContentFromParsable(RequestAdapter, "application/json", body);
            if (requestConfiguration != null)
            {
                var requestConfig = new MethodsRequestBuilderPostRequestConfiguration();
                requestConfiguration.Invoke(requestConfig);
                requestInfo.AddRequestOptions(requestConfig.Options);
                requestInfo.AddHeaders(requestConfig.Headers);
            }
            return(requestInfo);
        }
        public static string GetName(this AuthenticationMethod method)
        {
            switch (method)
            {
            case AuthenticationMethod.PublicKey:
                return("public key");

            case AuthenticationMethod.Password:
                return("password");

            case AuthenticationMethod.HostBased:
                return("host-based");

            case AuthenticationMethod.KeyboardInteractive:
                return("keyboard-interactive");
            }

            return("");
        }
Example #33
0
        public SFtpBatch(IConfiguration configuration)
        {
            this.configuration = configuration;
            var authenticationMethod = new AuthenticationMethod[] { new PasswordAuthenticationMethod(configuration.FtpLogin, configuration.FtpPassword) };
            var connectionInfo       = new ConnectionInfo(configuration.FtpHost, configuration.FtpLogin, authenticationMethod);

            this.sftp = new SftpClient(connectionInfo);
            this.sftp.OperationTimeout = TimeSpan.FromMinutes(1);
            sftp.BufferSize            = 4096;

            try
            {
                sftp.Connect();
            }
            catch (Exception e)
            {
                log.Error(e);
                throw;
            }
        }
        /// <summary>
        /// Constructs the authorization string as defined in the TeleSign REST API. First a
        /// "StringToSign" is constructed then this is the string that is hashed
        /// and that hash is used to authenticate the user. Then the authorization string is created
        /// from the customer id and the StringToSign hashed with the secret key.
        /// </summary>
        /// <param name="resourceName">The name of the resource - ie. the relative part of the URL.</param>
        /// <param name="method">The http method - POST, DELETE, GET, PUT.</param>
        /// <param name="timestamp">The timestamp to use.</param>
        /// <param name="nonce">The nonce (used for preventing replay attacks).</param>
        /// <param name="contentType">The mime type content type.</param>
        /// <param name="encodedBody">The body of a POST request.</param>
        /// <param name="authMethod">The authentication method to use.</param>
        /// <returns>The string that will be signed for authentication.</returns>
        public string ConstructAuthorizationString(
                    string resourceName,
                    string method,
                    DateTime timestamp,
                    string nonce,
                    string contentType,
                    string encodedBody,
                    AuthenticationMethod authMethod)
        {
            string stringToSign = this.ConstructStringToSign(
                        resourceName,
                        method,
                        timestamp,
                        nonce,
                        contentType,
                        encodedBody,
                        authMethod);

            return this.ConstructAuthorizationString(
                        stringToSign, 
                        authMethod);
        }
Example #35
0
 /// <summary>
 /// verify user and password
 /// </summary>
 /// <param name="strlogin">user name</param>
 /// <param name="strPassword">strPassword</param>
 /// <param name="authenticationMethod">verification mode</param>
 public void Authenticate(string strlogin,string strPassword,AuthenticationMethod authenticationMethod)
 {
     if(authenticationMethod==AuthenticationMethod.USERPASS)
     {
         AuthenticateUsingUSER(strlogin,strPassword);
     }
     else if(authenticationMethod==AuthenticationMethod.APOP)
     {
         AuthenticateUsingAPOP(strlogin,strPassword);
     }
     else if(authenticationMethod==AuthenticationMethod.TRYBOTH)
     {
         try
         {
             AuthenticateUsingUSER(strlogin,strPassword);
         }
         catch(InvalidLoginException e)
         {
             Utility.LogError("Authenticate():"+e.Message);
         }
         catch(InvalidPasswordException e)
         {
             Utility.LogError("Authenticate():"+e.Message);
         }
         catch(Exception e)
         {
             Utility.LogError("Authenticate():"+e.Message);
             AuthenticateUsingAPOP(strlogin,strPassword);
         }
     }
 }
Example #36
0
 /// <summary>
 /// Construct new POPClient
 /// </summary>
 public POPClient(string strHost,int intPort,string strlogin,string strPassword,AuthenticationMethod authenticationMethod)
 {
     Connect(strHost, intPort);
     Authenticate(strlogin,strPassword,authenticationMethod);
 }
        private void NegotiateSecurity(AuthenticationMethod[] methods)
        {
            Logger.Info("Negotiating security");

            this.c.SendByte((byte)methods.Length);
            VncStream.Require(
                methods.Length > 0,
                                  "Client is not allowed in.",
                                  VncFailureReason.NoSupportedAuthenticationMethods);
            foreach (var method in methods)
            {
                this.c.SendByte((byte)method);
            }

            var selectedMethod = (AuthenticationMethod)this.c.ReceiveByte();
            VncStream.Require(
                methods.Contains(selectedMethod),
                              "Invalid authentication method.",
                              VncFailureReason.UnrecognizedProtocolElement);

            bool success = true;
            if (selectedMethod == AuthenticationMethod.Password)
            {
                var challenge = VncPasswordChallenge.GenerateChallenge();
                using (new Utility.AutoClear(challenge))
                {
                    this.c.Send(challenge);

                    var response = this.c.Receive(16);
                    using (new Utility.AutoClear(response))
                    {
                        var e = new PasswordProvidedEventArgs(challenge, response);
                        this.OnPasswordProvided(e);
                        success = e.IsAuthenticated;
                    }
                }
            }

            this.c.SendUInt32BE(success ? 0 : (uint)1);
            VncStream.Require(
                success,
                              "Failed to authenticate.",
                              VncFailureReason.AuthenticationFailed);

            Logger.Info("The user authenticated successfully.");
        }
        private void NegotiateVersion(out AuthenticationMethod[] methods)
        {
            Logger.Info("Negotiating the version.");

            this.c.SendVersion(new Version(3, 8));

            this.clientVersion = this.c.ReceiveVersion();
            if (this.clientVersion == new Version(3, 8))
            {
                methods = new[]
                {
                    this.options.AuthenticationMethod == AuthenticationMethod.Password
                        ? AuthenticationMethod.Password : AuthenticationMethod.None
                };
            }
            else
            {
                methods = new AuthenticationMethod[0];
            }

            Logger.Info($"The client version is {this.clientVersion}");
            Logger.Info($"Supported autentication method are {string.Join(" ", methods)}");
        }
        /// <summary>
        /// Constructs the authorization by combining the customer id
        /// from the credential with the stringToSign hashed with
        /// the secret key.
        /// </summary>
        /// <param name="stringToSign">
        /// The stringToSign that is used for authentication.
        /// </param>
        /// <param name="authMethod">The method used for authentication.</param>
        /// <returns>The authorization string.</returns>
        public string ConstructAuthorizationString(
                    string stringToSign, 
                    AuthenticationMethod authMethod)
        {
            CheckArgument.NotNullOrEmpty(stringToSign, "stringToSign");

            return string.Format(
                        CultureInfo.InvariantCulture,
                        "TSA {0}:{1}",
                        this.credential.CustomerId,
                        this.ComputeHash(stringToSign, authMethod));
        }
Example #40
0
        /// <summary>
        /// Get authentication parameters to access an OAuth
        /// protected resource.  Used for two-legged OAuth.
        /// </summary>
        /// <param name="uri">Destination URL.</param>
        /// <param name="requestorId">Name of the user account at the remote site.</param>
        /// <param name="arguments">Arguments to include in the request.</param>
        /// <param name="consumerKey">The consumer key.</param>
        /// <param name="consumerSecret">The consumer secret.</param>
        /// <param name="format">The format of the resulting string.</param>
        /// <param name="method">HTTP method that will be used during the request.</param>
        /// <param name="rsaCert">The X509 certificate containing the private key used for RSA-SHA1.</param>
        /// <param name="sigMethod">Signature signing method.</param>
        /// <returns>String containing all authentication parameters, in the specified format.</returns>
        internal static string GetAuthParameters(Uri uri, string requestorId, NameValueCollection arguments, string consumerKey, string consumerSecret, X509Certificate2 rsaCert, AuthenticationMethod format, string method, SignatureMethod sigMethod)
        {
            NameValueCollection sigColl = new NameValueCollection();
            if (arguments != null) sigColl.Add(arguments);
            sigColl[OAuthArguments.XOAuthRequestorId] = requestorId;

            NameValueCollection queryArgs = HttpUtility.ParseQueryString(uri.Query);
            sigColl.Add(queryArgs);
            NameValueCollection nvc = TokenArgs(uri, sigColl, consumerKey, consumerSecret, null, null, rsaCert, sigMethod, method);

            foreach (string key in queryArgs.Keys)
            {
                nvc.Remove(key);
            }

            return OAuthUtility.ArgsToVal(nvc, format);
        }
Example #41
0
 /// <summary>
 /// Get a new RequestToken from the service provider.
 /// </summary>
 /// <param name="uri">Request token URL.</param>
 /// <param name="args">Arguments to include in the request.</param>
 /// <param name="consumerKey">The consumer key.</param>
 /// <param name="consumerSecret">The consumer secret.</param>
 /// <param name="sigMethod">The signature signing method.</param>
 /// <param name="mode">The HTTP connection and argument format to use.</param>
 /// <param name="rsaCert">The X509 certificate containing the private key for RSA-SHA1.</param>
 /// <returns>A populated Request Token.</returns>
 static RequestToken GetRequestToken(Uri uri, NameValueCollection args, string consumerKey, string consumerSecret, X509Certificate2 rsaCert, SignatureMethod sigMethod, AuthenticationMethod mode)
 {
     NameValueCollection nvc = TokenArgs(uri, args, consumerKey, consumerSecret, null, null, rsaCert, sigMethod, AuthenticationMethodToString(mode));
     WebResponse response = Request(uri, nvc, mode);
     NameValueCollection rnvc = FormatResponse(response);
     return new RequestToken(rnvc);
 }
Example #42
0
        /// <summary>
        /// Authenticates a user towards the POP server using some <see cref="AuthenticationMethod"/>.
        /// </summary>
        /// <param name="username">The username</param>
        /// <param name="password">The user password</param>
        /// <param name="authenticationMethod">The way that the client should authenticate towards the server</param>
        /// <exception cref="NotSupportedException">If <see cref="AuthenticationMethod.Apop"/> is used, but not supported by the server</exception>
        /// <exception cref="InvalidLoginException">If the user credentials was not accepted</exception>
        /// <exception cref="PopServerLockedException">If the server said the the mailbox was locked</exception>
        /// <exception cref="ArgumentNullException">If <paramref name="username"/> or <paramref name="password"/> is <see langword="null"/></exception>
        /// <exception cref="LoginDelayException">If the server rejects the login because of too recent logins</exception>
        public void Authenticate(string username, string password, AuthenticationMethod authenticationMethod)
        {
            AssertDisposed();

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

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

            if(State != ConnectionState.Authorization)
                throw new InvalidUseException("You have to be connected and not authorized when trying to authorize yourself");

            try
            {
                switch (authenticationMethod)
                {
                    case AuthenticationMethod.UsernameAndPassword:
                        AuthenticateUsingUserAndPassword(username, password);
                        break;

                    case AuthenticationMethod.Apop:
                        AuthenticateUsingApop(username, password);
                        break;

                    case AuthenticationMethod.Auto:
                        if (ApopSupported)
                            AuthenticateUsingApop(username, password);
                        else
                            AuthenticateUsingUserAndPassword(username, password);
                        break;

                    case AuthenticationMethod.CramMd5:
                        AuthenticateUsingCramMd5(username, password);
                        break;
                }
            } catch(PopServerException e)
            {
                DefaultLogger.Log.LogError("Problem logging in using method " + authenticationMethod + ". Server response was: " + LastServerResponse);

                // Throw a more specific exception if special cases of failure is detected
                // using the response the server generated when the last command was sent
                CheckFailedLoginServerResponse(LastServerResponse, e);

                // If no special failure is detected, tell that the login credentials were wrong
                throw new InvalidLoginException(e);
            }

            // We are now authenticated and therefore we enter the transaction state
            State = ConnectionState.Transaction;
        }
Example #43
0
        /// <summary>
        /// Authenticates a user towards the POP server using some AuthenticationMethod.
        /// </summary>
        /// <param name="username">The username</param>
        /// <param name="password">The user password</param>
		/// <param name="authenticationMethod">The way that the client should authenticate towards the server</param>
        /// <exception cref="NotSupportedException">If AuthenticationMethod.APOP is used, but not supported by the server</exception>
		public void Authenticate(string username, string password, AuthenticationMethod authenticationMethod)
		{
			if(authenticationMethod == AuthenticationMethod.USERPASS)
			{
				AuthenticateUsingUSER(username, password);				
			}
			else if(authenticationMethod == AuthenticationMethod.APOP)
			{
				AuthenticateUsingAPOP(username, password);
			}
			else if(authenticationMethod == AuthenticationMethod.TRYBOTH)
			{
                // Check if APOP is supported
                if(APOPSupported)
                    AuthenticateUsingAPOP(username, password);
                else
                    AuthenticateUsingUSER(username, password);
			}
		}
Example #44
0
 /// <summary>
 /// Get a string containing the Authentication parameters that should be
 /// passed in the authentication request. Compatible with Two-Legged OAuth 
 /// authentication.
 /// </summary>
 /// <remarks>
 /// Not for the faint of heart.  For most situations, use GetCredentials()
 /// and pass the output to the WebRequest.Credentials property.
 /// </remarks>
 /// <param name="uri">URL for the request.</param>
 /// <param name="method">HTTP Request method.</param>
 /// <param name="requestorId">User account ID.</param>
 /// <param name="postArgs">Argumentst that will be in the POST body that need to be signed.</param>
 /// <param name="format">Format of the authentication request data.</param>
 /// <returns>String containing the OAuth authentication parameters.</returns>
 public string GetAuthParameters(Uri uri, string method, string requestorId, NameValueCollection postArgs, AuthenticationMethod format)
 {
     if (SignatureType == SignatureMethod.RsaSha1 && RsaCertificate == null) throw new RequiredPropertyNotSetException(Strings.ExRsaCertificateRequired);
     return GetAuthParameters(uri, requestorId, postArgs, ConsumerKey, ConsumerSecret, RsaCertificate, format, method, SignatureType);
 }
Example #45
0
		private void Initialize()
		{
			if (this.ptr == IntPtr.Zero || isInitialized)
			{
				return;
			}

			isInitialized = true;

			// marshal the structure
			raw = (SSL_CIPHER)Marshal.PtrToStructure(ptr, typeof(SSL_CIPHER));
			// start picking the data out
			bool isExport = IsExport(raw.algo_strength);
			int privateKeyLength = ExportPrivateKeyLength(raw.algo_strength);
			int keyLength = ExportKeyLength(raw.algorithm_enc, raw.algo_strength);

			// Get the SSL Protocol version
            if ((raw.algorithm_ssl & SSL_SSLV2) == SSL_SSLV2)
			{
				sslProtocol = SslProtocols.Ssl2;
			}
            else if ((raw.algorithm_ssl & SSL_SSLV3) == SSL_SSLV3)
			{
				sslProtocol = SslProtocols.Tls; // SSL3 & TLS are the same here...
			}
            else if ((raw.algorithm_ssl & SSL_TLSV1_2) == SSL_TLSV1_2)
            {
                sslProtocol = SslProtocols.Tls; // WARNING: TLSV1_2 support not fully implemented
            }

			// set the keyExchange strength
			keyExchangeStrength = privateKeyLength;

			// Get the Key Exchange cipher and strength
            switch (raw.algorithm_mkey)
			{
				case SSL_kRSA:
					keyExchangeAlgorithm = ExchangeAlgorithmType.RsaKeyX;
					break;
				case SSL_kDHr:
				case SSL_kDHd:
				case SSL_kEDH:
					keyExchangeAlgorithm = ExchangeAlgorithmType.DiffieHellman;
					break;
				case SSL_kKRB5:
					keyExchangeAlgorithm = ExchangeAlgorithmType.Kerberos;
					break;
                case SSL_kECDHr:
                case SSL_kECDHe:
                case SSL_kEECDH:
					keyExchangeAlgorithm = ExchangeAlgorithmType.ECDiffieHellman;
					break;
                case SSL_kPSK:
					keyExchangeAlgorithm = ExchangeAlgorithmType.PSK;
					break;
                case SSL_kGOST:
                    keyExchangeAlgorithm = ExchangeAlgorithmType.GOST;
                    break;
                case SSL_kSRP:
                    keyExchangeAlgorithm = ExchangeAlgorithmType.SRP;
                    break;
			}

			// Get the authentication method
            switch (raw.algorithm_auth)
			{
				case SSL_aRSA:
					authMethod = AuthenticationMethod.Rsa;
					break;
				case SSL_aDSS:
					authMethod = AuthenticationMethod.Dss;
					break;
				case SSL_aDH:
					authMethod = AuthenticationMethod.DiffieHellman;
					break;
				case SSL_aKRB5:         /* VRS */
					authMethod = AuthenticationMethod.Kerberos;
					break;
				case SSL_aNULL:
					authMethod = AuthenticationMethod.None;
					break;
				case SSL_aECDSA:
					authMethod = AuthenticationMethod.ECDsa;
					break;
                case SSL_aPSK:
                    authMethod = AuthenticationMethod.PSK;
                    break;
                case SSL_aGOST94:
                    authMethod = AuthenticationMethod.GOST;
                    break;
                case SSL_aGOST01:
                    authMethod = AuthenticationMethod.GOST;
                    break;
			}
			// Get the symmetric encryption cipher info
            switch (raw.algorithm_enc)
			{
				case SSL_DES:
					cipherAlgorithm = CipherAlgorithmType.Des;
					if (isExport && keyLength == 5)
					{
						cipherStrength = 40;
					}
					else
					{
						cipherStrength = 56;
					}
					break;
				case SSL_3DES:
					cipherAlgorithm = CipherAlgorithmType.TripleDes;
					cipherStrength = 168;
					break;
				case SSL_RC4:
					cipherAlgorithm = CipherAlgorithmType.Rc4;
					if (isExport)
					{
						if (keyLength == 5)
						{
							cipherStrength = 40;
						}
						else
						{
							cipherStrength = 56;
						}
					}
					else
					{
						if ((raw.algorithm2 & SSL2_CF_8_BYTE_ENC) == SSL2_CF_8_BYTE_ENC)
						{
							cipherStrength = 64;
						}
						else
						{
							cipherStrength = 128;
						}
					}
					break;
				case SSL_RC2:
					cipherAlgorithm = CipherAlgorithmType.Rc2;
					if (isExport)
					{
						if (keyLength == 5)
						{
							cipherStrength = 40;
						}
						else
						{
							cipherStrength = 56;
						}
					}
					else
					{
						cipherStrength = 128;
					}
					break;
				case SSL_IDEA:
					cipherAlgorithm = CipherAlgorithmType.Idea;
					cipherStrength = 128;
					break;
				case SSL_eNULL:
					cipherAlgorithm = CipherAlgorithmType.None;
					break;
                case SSL_AES128:
                    cipherAlgorithm = CipherAlgorithmType.Aes128;
                    cipherStrength = 128;
                    break;
                case SSL_AES256:
                    cipherAlgorithm = CipherAlgorithmType.Aes256;
                    cipherStrength = 256;
                    break;
                case SSL_AES128GCM:
                    cipherAlgorithm = CipherAlgorithmType.Aes128GCM;
                    cipherStrength = 128;
                    break;
                case SSL_AES256GCM:
                    cipherAlgorithm = CipherAlgorithmType.Aes256GCM;
                    cipherStrength = 256;
					break;
/*
					switch (raw.strength_bits)
					{
						case 128: cipherAlgorithm = CipherAlgorithmType.Aes128; break;
						case 192: cipherAlgorithm = CipherAlgorithmType.Aes192; break;
						case 256: cipherAlgorithm = CipherAlgorithmType.Aes256; break;
					}
*/
                case SSL_CAMELLIA128:
                    cipherAlgorithm = CipherAlgorithmType.Seed;
					cipherStrength = 128;
                    break;
                case SSL_CAMELLIA256:
                    cipherAlgorithm = CipherAlgorithmType.Seed;
					cipherStrength = 128;
                    break;
/*
					switch (raw.strength_bits)
					{
						case 128: cipherAlgorithm = CipherAlgorithmType.Camellia128; break;
						case 256: cipherAlgorithm = CipherAlgorithmType.Camellia256; break;
					}
*/
                case SSL_eGOST2814789CNT:
                    cipherAlgorithm = CipherAlgorithmType.eGOST2814789CNT;
                    cipherStrength = 128; // ???
                    break;
				case SSL_SEED:
					cipherAlgorithm = CipherAlgorithmType.Seed;
					cipherStrength = 128;
					break;
			}

			// Get the MAC info
            switch (raw.algorithm_mac)
			{
				case SSL_MD5:
					hashAlgorithm = HashAlgorithmType.Md5;
					break;
				case SSL_SHA1:
					hashAlgorithm = HashAlgorithmType.Sha1;
					break;
                case SSL_GOST94:
                    hashAlgorithm = HashAlgorithmType.Gost94;
                    break;
                case SSL_GOST89MAC:
                    hashAlgorithm = HashAlgorithmType.Gost89MAC;
                    break;
                case SSL_SHA256:
                    hashAlgorithm = HashAlgorithmType.Sha256;
                    break;
                case SSL_SHA384:
                    hashAlgorithm = HashAlgorithmType.Sha384;
					break;
				default:
					hashAlgorithm = HashAlgorithmType.None;
					break;
			}
		}
Example #46
0
		public Authentication(AuthenticationMethod method)
		{
			this.method = method;
		}
Example #47
0
		public ProfileItem(
			string name,
			Guid interfaceId,
			string interfaceName,
			string interfaceDescription,
			AuthenticationMethod authentication,
			EncryptionType encryption,
			int position,
			bool isAutomatic,
			int signal,
			bool isConnected)
		{
			if (string.IsNullOrWhiteSpace(name))
				throw new ArgumentNullException(nameof(name));

			if (interfaceId == Guid.Empty)
				throw new ArgumentException(nameof(interfaceId));

			this.Name = name;
			this.InterfaceId = interfaceId;
			this.InterfaceName = interfaceName;
			this.InterfaceDescription = interfaceDescription;
			this.Authentication = authentication;
			this.Encryption = encryption;
			this.Position = position;
			this.IsAutomatic = isAutomatic;
			this.Signal = signal;
			this.IsConnected = isConnected;
		}
        /// <summary>
        /// Retrieve a user by their oAuth profile Id
        /// </summary>
        /// <param name="profile">Profile Id</param>
        /// <param name="method">Authentication method</param>
        /// <returns>User</returns>
        public User GetUserByOAuthProfile(string profile, AuthenticationMethod method)
        {
            if (string.IsNullOrWhiteSpace(profile))
                return null;

            var query = _userRepository.Table;

            switch (method)
            {
                case AuthenticationMethod.Facebook:

                    query = query.Where(u => u.FacebookProfile == profile);

                    break;
                case AuthenticationMethod.Twitter:

                    query = query.Where(u => u.TwitterProfile == profile);

                    break;
            }

            var user = query.FirstOrDefault();
            return user;
        }
Example #49
0
 /// <summary>
 /// Convert AuthenticationMethods to the appropriate
 /// HTTP method for token requests.
 /// </summary>
 /// <param name="method">Input value.</param>
 /// <returns>Appropriate HTTP method.</returns>
 static string AuthenticationMethodToString(AuthenticationMethod method)
 {
     switch (method)
     {
         case AuthenticationMethod.Get:
             return "GET";
         case AuthenticationMethod.Header:
             return "POST";
         case AuthenticationMethod.Post:
             return "POST";
     }
     return "POST";
 }
        /// <summary>
        /// Checks a user exists with a given oAuth profile Id
        /// </summary>
        /// <param name="profile">Profile Id</param>
        /// <param name="method">Authentication method</param>
        /// <returns>True/False</returns>
        public bool UserExists(string profile, AuthenticationMethod method)
        {
            if (string.IsNullOrWhiteSpace(profile))
                return false;

            var query = _userRepository.Table;

            switch (method)
            {
                case AuthenticationMethod.Facebook:
                    return query.Any(u => u.FacebookProfile == profile);
                case AuthenticationMethod.Twitter:
                    return query.Any(u => u.TwitterProfile == profile);
            }

            return false;
        }
        /// <summary>
        /// Computes the hash of the StringToSign using the secret key.
        /// </summary>
        /// <param name="stringToSign">The StringToSign that will be hashed with the secret key.</param>
        /// <param name="authMethod">The authorization/hash method to be used.</param>
        /// <returns>The hash of the string to sign.</returns>
        public string ComputeHash(
                    string stringToSign, 
                    AuthenticationMethod authMethod)
        {
            CheckArgument.NotNullOrEmpty(stringToSign, "stringToSign");

            byte[] secretKeyBytes = Convert.FromBase64String(this.credential.SecretKey);
            byte[] stringToSignBytes = Encoding.UTF8.GetBytes(stringToSign);

            HMAC hasher = null;

            switch (authMethod)
            {
                case AuthenticationMethod.HmacSha1:
                    hasher = new HMACSHA1(secretKeyBytes);
                    break;
                case AuthenticationMethod.HmacSha256:
                    hasher = new HMACSHA256(secretKeyBytes);
                    break;
                default:
                    throw new NotSupportedException("Only HMAC SHA1 and SHA256 authentication is currently supported");
            }

            return Convert.ToBase64String(hasher.ComputeHash(stringToSignBytes));
        }
Example #52
0
 /// <summary>
 /// Upgrade a Request Token to an Access Token.
 /// </summary>
 /// <param name="uri">Access token URL.</param>
 /// <param name="token">RequestToken to upgrade.</param>
 /// <param name="consumerKey">The consumer key.</param>
 /// <param name="consumerSecret">The consumer secret.</param>
 /// <param name="sigMethod">The signature signing method.</param>
 /// <param name="mode">The HTTP connection and argument format to use.</param>
 /// <param name="rsaCert">The X509 certificate containing the private key used for RSA-SHA1.</param>
 /// <returns>A populated AccessToken.</returns>
 static AccessToken GetAccessToken(Uri uri, RequestToken token, string consumerKey, string consumerSecret, X509Certificate2 rsaCert, SignatureMethod sigMethod, AuthenticationMethod mode)
 {
     NameValueCollection nvc = TokenArgs(uri, null, consumerKey, consumerSecret, token.Key, token.Secret, rsaCert, sigMethod, AuthenticationMethodToString(mode));
     WebResponse response = Request(uri, nvc, mode);
     NameValueCollection rparams = FormatResponse(response);
     return new AccessToken(rparams);
 }
Example #53
0
        /// <summary>
        /// Perform an HTTP request with OAuth authentication arguments.
        /// </summary>
        /// <remarks>
        /// Used for Token requests.
        /// </remarks>
        /// <param name="uri">Destination URL.</param>
        /// <param name="oauthArguments">Arguments to include in the OAuth authentication data.</param>
        /// <param name="format">The required OAuth argument format.</param>
        /// <returns>The resulting WebResponse object.</returns>
        static WebResponse Request(Uri uri, NameValueCollection oauthArguments, AuthenticationMethod format)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            string realm = OAuthUtility.Realm(uri);

            Trace.WriteLine(uri.AbsoluteUri, "TokenWebRequest");

            WebResponse response = null;
            switch (format)
            {
                case AuthenticationMethod.Header:
                    request.Method = "POST";
                    string headerstr = String.Format(CultureInfo.InvariantCulture, "{0} realm={1}, {2}", Strings.OAuth, OAuthUtility.Realm(uri), OAuthUtility.ArgsToVal(oauthArguments, AuthenticationMethod.Header));
                    Trace.WriteLine(headerstr, "HttpHeader_Authorization");
                    request.Headers.Add(HttpRequestHeader.Authorization, headerstr);
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ContentLength = 0;
                    break;
                case AuthenticationMethod.Get:
                    request.Method = "GET";
                    UriBuilder ub = new UriBuilder(uri);
                    if (String.IsNullOrEmpty(ub.Query))
                    {
                        ub.Query = OAuthUtility.ArgsToVal(oauthArguments, format);
                    }
                    else
                    {
                        ub.Query += "&" + OAuthUtility.ArgsToVal(oauthArguments, format);
                    }
                    Trace.WriteLine(ub.Uri.Query, "GetRequestArguments");
                    request = (HttpWebRequest)HttpWebRequest.Create(ub.Uri);
                    break;
                case AuthenticationMethod.Post:
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    string vals = OAuthUtility.ArgsToVal(oauthArguments, format);
                    Trace.WriteLine(vals, "PostRequestArguments");
                    byte[] data = System.Text.Encoding.UTF8.GetBytes(vals);
                    request.ContentLength = data.Length;
                    Stream s = request.GetRequestStream();
                    s.Write(data, 0, data.Length);
                    s.Close();
                    break;
            }
            try
            {
                response = request.GetResponse();
            }
            catch (WebException e)
            {
                string err = null;
                if (e.Response != null)
                {
                    using (StreamReader sr = new StreamReader(e.Response.GetResponseStream()))
                    {
                        err = sr.ReadToEnd();
                    }
                    HttpWebResponse hwr = (HttpWebResponse)e.Response;
                    Trace.Write(string.Format(CultureInfo.InvariantCulture, "HTTP Status Code: {0}, Description: {1}", hwr.StatusCode, hwr.StatusDescription));
                    throw new WebException(String.Format(CultureInfo.CurrentCulture, "Message Received From Server: {0}", err), e);
                }
                throw;
            }
            return response;
        }
Example #54
0
 /// <summary>
 /// Initialize a new Auth confiuration with basic scope
 /// </summary>
 /// <param name="clientId">The client id for your app</param>
 /// <param name="clientSecret">The client secret for your app</param>
 /// <param name="redirectUri">
 /// The URI where the user is redirected after authorization. 
 /// This must match the exact URI registered for your app in the Instagram dev console
 /// </param>
 /// <param name="authMethod">The authentication flow to use during the authorization process</param>
 public OAuth(string clientId, string clientSecret, string redirectUri, AuthenticationMethod authMethod) 
     : this(clientId, clientSecret, redirectUri)
 {
     AuthMethod = authMethod;
 }
        /// <summary>
        /// Merge two users together
        /// </summary>
        /// <param name="primaryUser">Primary user entity</param>
        /// <param name="addUser">User entity to add</param>
        /// /// <param name="method">Authentication method</param>
        public void MergeUsers(User primaryUser, User addUser, AuthenticationMethod method)
        {
            if (primaryUser == null || addUser == null)
                return;

            var commentService = EngineContext.Current.Resolve<ICommentService>();
            var moderationQueueService = EngineContext.Current.Resolve<IModerationQueueService>();
            var projectService = EngineContext.Current.Resolve<IProjectService>();
            var successStoryService = EngineContext.Current.Resolve<ISuccessStoryService>();

            // Change ownership of any comments
            commentService.MigrateCommentOwnership(addUser.Id, primaryUser);

            // Change ownership of any moderation requests
            moderationQueueService.MigrateModerationQueueOwnership(addUser.Id, primaryUser.Id);

            // Change ownership of any projects
            projectService.MigrateProjectOwnership(addUser.Id, primaryUser);

            // Change ownership and author of any success stories
            successStoryService.MigrateSuccessStoryAuthor(addUser.Id, primaryUser);

            switch (method)
            {
                case AuthenticationMethod.Facebook:

                    primaryUser.FacebookDisplayName = addUser.FacebookDisplayName;
                    primaryUser.FacebookProfile = addUser.FacebookProfile;

                    break;
                case AuthenticationMethod.Twitter:

                    primaryUser.TwitterDisplayName = addUser.TwitterDisplayName;
                    primaryUser.TwitterProfile = addUser.TwitterProfile;

                    break;
            }

            // Update primary user entity
            _userRepository.Update(primaryUser);

            // Delete the old user
            _userRepository.Delete(addUser, true);
        }
 /// <summary>
 /// Maps the AuthenticationMethod enumeration to the string used in headers.
 /// </summary>
 /// <param name="authMethod">The authentication method.</param>
 /// <returns>The header string for the authentication method.</returns>
 public string MapAuthenticationMethodToHeaderString(AuthenticationMethod authMethod)
 {
     switch (authMethod)
     {
         case AuthenticationMethod.HmacSha1:
             return "hmac-sha1";
         case AuthenticationMethod.HmacSha256:
             return "hmac-sha256";
         default:
             throw new NotSupportedException("Only HMAC SHA1 and SHA256 authentication is currently supported");
     }
 }
        /// <summary>
        /// Constructs a .NET WebRequest object for the request.
        /// </summary>
        /// <param name="resourceName">The name of the resource - ie. the relative part of the URL.</param>
        /// <param name="method">The http method - POST, DELETE, GET, PUT.</param>
        /// <param name="fields">The fields that are the arguments to the request.</param>
        /// <param name="authMethod">The method of authentication to use.</param>
        /// <returns>A WebRequest object.</returns>
        protected WebRequest ConstructWebRequest(
                    string resourceName,
                    string method,
                    Dictionary<string, string> fields = null,
                    AuthenticationMethod authMethod = AuthenticationMethod.HmacSha1)
        {
            CheckArgument.NotNullOrEmpty(resourceName, "resourceName");
            CheckArgument.NotNullOrEmpty(method, "method");

            DateTime timeStamp = DateTime.UtcNow;
            string nonce = Guid.NewGuid().ToString();

            // When the Uri is constructed. If it is a GET request the fields
            // are put into the Uri's query string eg ?foo=bar. When the
            // method is POST the fields are not used in constructing the Uri,
            // but below they are placed in the encoded body.
            Uri fullUri = this.ConstructResourceUri(
                        resourceName,
                        method,
                        fields);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(fullUri);
            request.Method = method;

            string contentType = string.Empty;
            string encodedBody = string.Empty;
            if (method == "POST")
            {
                contentType = "application/x-www-form-urlencoded";
                encodedBody = TeleSignService.ConstructQueryString(fields);
            }

            string authorizationString = this.authentication.ConstructAuthorizationString(
                        resourceName,
                        method,
                        timeStamp,
                        nonce,
                        contentType,
                        encodedBody,
                        authMethod);

            request.Headers.Add("Authorization", authorizationString);
            request.Headers.Add("x-ts-auth-method", this.authentication.MapAuthenticationMethodToHeaderString(authMethod));
            request.Headers.Add("x-ts-date", timeStamp.ToString("r"));
            request.Headers.Add("x-ts-nonce", nonce);

            if (method == "POST")
            {
                byte[] body = Encoding.UTF8.GetBytes(encodedBody);

                request.Accept = "application/json";
                request.ContentType = contentType;
                request.ContentLength = body.Length;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(body, 0, body.Length);
                }
            }

            return request;
        }
 //public List<SshWinConsoleChannel> GetAllTerminalChannels()
 //{
 //    var list = new List<SshWinConsoleChannel>();
 //    // Add each terminal channel to list.
 //    foreach (var client in _service.TcpServer.Clients)
 //    {
 //        foreach (var channel in client.ConnectionService.Channels)
 //        {
 //            if (channel is SshWinConsoleChannel)
 //                list.Add((SshWinConsoleChannel)channel);
 //        }
 //    }
 //    return list;
 //}
 protected void LogClientAuthEvent(SshClient client, AuthenticationMethod method,
     AuthUserEventArgs authUserEventArgs)
 {
     // Check result of authentication.
     switch (authUserEventArgs.Result)
     {
         case AuthenticationResult.Success:
             LogClientEvent(client, string.Format("User '{0}' has authenticated using the " +
                 "{1} method.", authUserEventArgs.UserName, method.GetName()),
                 EventLogEntryType.Information);
             break;
         case AuthenticationResult.FurtherAuthRequired:
             LogClientEvent(client, string.Format("User '{0}' has authenticated using the " +
                 "{1} method but further authentication is required.", authUserEventArgs.UserName,
                 method.GetName()), EventLogEntryType.Information);
             break;
         case AuthenticationResult.Failure:
             LogClientEvent(client, string.Format("User '{0}' has failed to authenticate using the" +
                 "{1} method.", authUserEventArgs.UserName, method.GetName()),
                 EventLogEntryType.Information);
             break;
         case AuthenticationResult.PasswordExpired:
             LogClientEvent(client, string.Format("User '{0}' has attempted to authenticate " +
                 "using an expired password.", authUserEventArgs.UserName),
                 EventLogEntryType.Information);
             break;
         case AuthenticationResult.RequestMoreInfo:
             LogClientEvent(client, string.Format("User '{0}' has correctly responded to prompts " +
                 "but the server requested more information.", authUserEventArgs.UserName),
                 EventLogEntryType.Information);
             break;
     }
 }
 public AuthMethodRequestedEventArgs(AuthenticationMethod authMethod)
     : base()
 {
     this.AuthMethod = authMethod;
 }
Example #60
0
		private void Initialize()
		{
			if (this.ptr == IntPtr.Zero || isInitialized)
			{
				return;
			}

			isInitialized = true;

			// marshal the structure
			raw = (SSL_CIPHER)Marshal.PtrToStructure(ptr, typeof(SSL_CIPHER));
			// start picking the data out
			bool isExport = IsExport(raw.algo_strength);
			int privateKeyLength = ExportPrivateKeyLength(raw.algo_strength);
			int keyLength = ExportKeyLength(raw.algorithms, raw.algo_strength);

			// Get the SSL Protocol version
			if ((raw.algorithms & SSL_SSLV2) == SSL_SSLV2)
			{
				sslProtocol = SslProtocols.Ssl2;
			}
			else if ((raw.algorithms & SSL_SSLV3) == SSL_SSLV3)
			{
				sslProtocol = SslProtocols.Tls; // SSL3 & TLS are the same here...
			}

			// set the keyExchange strength
			keyExchangeStrength = privateKeyLength;

			// Get the Key Exchange cipher and strength
			switch (raw.algorithms & SSL_MKEY_MASK)
			{
				case SSL_kRSA:
					keyExchangeAlgorithm = ExchangeAlgorithmType.RsaKeyX;
					break;
				case SSL_kDHr:
				case SSL_kDHd:
				case SSL_kEDH:
					keyExchangeAlgorithm = ExchangeAlgorithmType.DiffieHellman;
					break;
				case SSL_kKRB5:         /* VRS */
				case SSL_KRB5:          /* VRS */
					keyExchangeAlgorithm = ExchangeAlgorithmType.Kerberos;
					break;
				case SSL_kFZA:
					keyExchangeAlgorithm = ExchangeAlgorithmType.Fortezza;
					break;
				case SSL_kECDH:
				case SSL_kECDHE:
					keyExchangeAlgorithm = ExchangeAlgorithmType.ECDiffieHellman;
					break;
			}

			// Get the authentication method
			switch (raw.algorithms & SSL_AUTH_MASK)
			{
				case SSL_aRSA:
					authMethod = AuthenticationMethod.Rsa;
					break;
				case SSL_aDSS:
					authMethod = AuthenticationMethod.Dss;
					break;
				case SSL_aDH:
					authMethod = AuthenticationMethod.DiffieHellman;
					break;
				case SSL_aKRB5:         /* VRS */
				case SSL_KRB5:          /* VRS */
					authMethod = AuthenticationMethod.Kerberos;
					break;
				case SSL_aFZA:
				case SSL_aNULL:
					authMethod = AuthenticationMethod.None;
					break;
				case SSL_aECDSA:
					authMethod = AuthenticationMethod.ECDsa;
					break;
			}
			// Get the symmetric encryption cipher info
			switch (raw.algorithms & SSL_ENC_MASK)
			{
				case SSL_DES:
					cipherAlgorithm = CipherAlgorithmType.Des;
					if (isExport && keyLength == 5)
					{
						cipherStrength = 40;
					}
					else
					{
						cipherStrength = 56;
					}
					break;
				case SSL_3DES:
					cipherAlgorithm = CipherAlgorithmType.TripleDes;
					cipherStrength = 168;
					break;
				case SSL_RC4:
					cipherAlgorithm = CipherAlgorithmType.Rc4;
					if (isExport)
					{
						if (keyLength == 5)
						{
							cipherStrength = 40;
						}
						else
						{
							cipherStrength = 56;
						}
					}
					else
					{
						if ((raw.algorithm2 & SSL2_CF_8_BYTE_ENC) == SSL2_CF_8_BYTE_ENC)
						{
							cipherStrength = 64;
						}
						else
						{
							cipherStrength = 128;
						}
					}
					break;
				case SSL_RC2:
					cipherAlgorithm = CipherAlgorithmType.Rc2;
					if (isExport)
					{
						if (keyLength == 5)
						{
							cipherStrength = 40;
						}
						else
						{
							cipherStrength = 56;
						}
					}
					else
					{
						cipherStrength = 128;
					}
					break;
				case SSL_IDEA:
					cipherAlgorithm = CipherAlgorithmType.Idea;
					cipherStrength = 128;
					break;
				case SSL_eFZA:
					cipherAlgorithm = CipherAlgorithmType.Fortezza;
					break;
				case SSL_eNULL:
					cipherAlgorithm = CipherAlgorithmType.None;
					break;
				case SSL_AES:
					switch (raw.strength_bits)
					{
						case 128: cipherAlgorithm = CipherAlgorithmType.Aes128; break;
						case 192: cipherAlgorithm = CipherAlgorithmType.Aes192; break;
						case 256: cipherAlgorithm = CipherAlgorithmType.Aes256; break;
					}
					break;
				case SSL_CAMELLIA:
					switch (raw.strength_bits)
					{
						case 128: cipherAlgorithm = CipherAlgorithmType.Camellia128; break;
						case 256: cipherAlgorithm = CipherAlgorithmType.Camellia256; break;
					}
					break;
				case SSL_SEED:
					cipherAlgorithm = CipherAlgorithmType.Seed;
					cipherStrength = 128;
					break;
			}
			// Get the MAC info
			switch (raw.algorithms & SSL_MAC_MASK)
			{
				case SSL_MD5:
					hashAlgorithm = HashAlgorithmType.Md5;
					break;
				case SSL_SHA1:
					hashAlgorithm = HashAlgorithmType.Sha1;
					break;
				default:
					hashAlgorithm = HashAlgorithmType.None;
					break;
			}
		}