/// <summary>
        /// Authenticates a username and password using a specific <see cref="IConnection"/> instance. The password will
        /// be encrypted before being sent to the server.
        /// </summary>
        /// <param name="connection">An implementation of <see cref="IConnection"/> which represents a TCP connection to a Couchbase Server.</param>
        /// <param name="username">The username or bucket name to authentic against.</param>
        /// <param name="password">The password to authenticate against.</param>
        /// <returns>True if succesful.</returns>
        public bool Authenticate(IConnection connection, string username, string password)
        {
            var authenticated = false;

            Username = username;
            Password = password ?? string.Empty;

            var temp = connection;

            Log.Debug(m => m("Authenticating socket {0}", temp.Identity));

            var operation = new SaslStart(MechanismType, null, _converter);
            var result    = _ioStrategy.Execute(operation, connection);

            if (result.Status == ResponseStatus.AuthenticationContinue)
            {
                var challenge = result.Message;
                var reply     = ComputeResponse(challenge);

                operation = new SaslStep(MechanismType, reply, _converter);
                result    = _ioStrategy.Execute(operation, connection);

                authenticated = result.Status == ResponseStatus.Success &&
                                result.Value.Equals("Authenticated");

                Log.Debug(m => m("Authentication for socket {0} succeeded.", temp.Identity));
            }

            if (result.Status == ResponseStatus.AuthenticationError)
            {
                Log.Debug(m => m("Authentication for socket {0} failed: {1}", temp.Identity, result.Value));
            }

            return(authenticated);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Authenticates a username and password using a specific <see cref="IConnection"/> instance.
        /// </summary>
        /// <param name="connection">An implementation of <see cref="IConnection"/> which represents a TCP connection to a Couchbase Server.</param>
        /// <param name="username">The username or bucket name to authentic against.</param>
        /// <param name="password">The password to authenticate against.</param>
        /// <returns>True if succesful.</returns>
        public bool Authenticate(IConnection connection, string username, string password)
        {
            var authenticated = false;
            var temp          = connection;

            Log.Debug(m => m("Authenticating socket {0}", temp.Identity));

            try
            {
                var operation = new SaslStart(MechanismType, GetAuthData(username, password), _transcoder, SaslFactory.DefaultTimeout);
                var result    = _service.Execute(operation, connection);

                if (!result.Success &&
                    result.Status == ResponseStatus.AuthenticationError)
                {
                    Log.Debug(m => m("Authentication for socket {0} failed: {1}", temp.Identity, result.Value));
                }
                else
                {
                    authenticated = true;
                    Log.Debug(m => m("Authenticated socket {0} succeeded: {1}", temp.Identity, result.Value));
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            return(authenticated);
        }
        public void Test_SaslAuthenticate_Returns_Succuss_With_ValidCredentials()
        {
            var operation = new SaslStart("PLAIN", GetAuthData("authenticated", "secret"), new DefaultTranscoder(), OperationLifespan);
            var response  = _ioService.Execute(operation);

            Assert.AreEqual(ResponseStatus.Success, response.Status);
            Assert.IsTrue(response.Success);
        }
        public void Test_SaslAuthenticate_Returns_Succuss_With_ValidCredentials()
        {
            var operation = new SaslStart("PLAIN", GetAuthData("authenticated", "secret"), new DefaultTranscoder(), OperationLifespan);
            var response = _ioStrategy.Execute(operation);

            Assert.AreEqual(ResponseStatus.Success, response.Status);
            Assert.IsTrue(response.Success);
        }
        public void Test_SaslAuthenticate_Returns_Succuss_With_ValidCredentials()
        {
            var operation = new SaslStart("PLAIN", GetAuthData("authenticated", "secret"), new ManualByteConverter());
            var response  = _ioStrategy.Execute(operation);

            Assert.AreEqual("Authenticated", response.Value);
            Assert.AreEqual(ResponseStatus.Success, response.Status);
            Assert.IsTrue(response.Success);
        }
        public void Test_SaslAuthenticate_Returns_AuthFailure_With_InvalidCredentials()
        {
            var operation = new SaslStart("PLAIN", GetAuthData("foo", "bar"), new DefaultTranscoder(), OperationLifespan);
            var response  = _ioService.Execute(operation);

            Assert.AreEqual("Auth failure", response.Message);
            Assert.AreEqual(ResponseStatus.AuthenticationError, response.Status);
            Assert.IsFalse(response.Success);
        }
        public void When_CRAM_MD5_Used_SaslStart_Returns_AuthenticationContinue()
        {
            var operation = new SaslStart("CRAM-MD5", (VBucket)null, new DefaultTranscoder(), OperationLifespan);
            var response = _ioStrategy.Execute(operation);

            Assert.IsNotNullOrEmpty(response.Message);
            Assert.AreEqual(ResponseStatus.AuthenticationContinue, response.Status);
            Assert.IsFalse(response.Success);
        }
        public void Test_SaslAuthenticate_Returns_AuthFailure_With_InvalidCredentials()
        {
            var operation = new SaslStart("PLAIN", GetAuthData("foo", "bar"), new DefaultTranscoder(), OperationLifespan);
            var response = _ioService.Execute(operation);

            Assert.AreEqual("Auth failure", response.Message);
            Assert.AreEqual(ResponseStatus.AuthenticationError, response.Status);
            Assert.IsFalse(response.Success);
        }
        public void When_CRAM_MD5_Used_SaslStart_Returns_AuthenticationContinue()
        {
            var operation = new SaslStart("CRAM-MD5", (VBucket)null, new DefaultTranscoder(), OperationLifespan);
            var response  = _ioService.Execute(operation);

            Assert.That(() => !string.IsNullOrEmpty(response.Message));
            Assert.AreEqual(ResponseStatus.AuthenticationContinue, response.Status);
            Assert.IsFalse(response.Success);
        }
        public void Test_SaslAuthenticate_Returns_AuthFailure_With_InvalidCredentials()
        {
            var operation = new SaslStart("PLAIN", GetAuthData("foo", "bar"), new ManualByteConverter());
            var response  = _ioStrategy.Execute(operation);

            Assert.AreEqual("Auth failure", response.Message);
            Assert.AreEqual(ResponseStatus.AuthenticationError, response.Status);
            Assert.IsFalse(response.Success);
        }
        public void When_CRAM_MD5_Used_SaslStart_Returns_AuthenticationContinue()
        {
            var operation = new SaslStart("CRAM-MD5", null, new ManualByteConverter());
            var response  = _ioStrategy.Execute(operation);

            Assert.IsNotNullOrEmpty(response.Message);
            Assert.AreEqual(ResponseStatus.AuthenticationContinue, response.Status);
            Assert.IsFalse(response.Success);
        }
        public void Test_SaslAuthenticate_Returns_Succuss_With_ValidCredentials()
        {
            var operation = new SaslStart("PLAIN",  GetAuthData("authenticated", "secret"), new ManualByteConverter());
            var response = _ioStrategy.Execute(operation);

            Assert.AreEqual("Authenticated", response.Value);
            Assert.AreEqual(ResponseStatus.Success, response.Status);             
            Assert.IsTrue(response.Success);
        }
        public void When_CRAM_MD5_Used_SaslStart_Returns_AuthenticationContinue()
        {
            var operation = new SaslStart("CRAM-MD5", null, new ManualByteConverter());
            var response = _ioStrategy.Execute(operation);

            Assert.IsNotNullOrEmpty(response.Message);
            Assert.AreEqual(ResponseStatus.AuthenticationContinue, response.Status);
            Assert.IsFalse(response.Success);
        }
        public void Test_SaslAuthenticate_Returns_AuthFailure_With_InvalidCredentials()
        {
            var operation = new SaslStart("PLAIN",  GetAuthData("foo", "bar"), new ManualByteConverter());
            var response = _ioStrategy.Execute(operation);

            Assert.AreEqual("Auth failure", response.Message);
            Assert.AreEqual(ResponseStatus.AuthenticationError, response.Status);
            Assert.IsFalse(response.Success);
        }
 protected async Task <string> SaslStart(IConnection connection, string message, CancellationToken token)
 {
     using var authOp = new SaslStart
           {
               Key        = MechanismType.GetDescription(),
               Content    = message,
               Transcoder = Transcoder,
               Timeout    = Timeout
           };
     return(await SendAsync(authOp, connection, token).ConfigureAwait(false));
 }
Exemplo n.º 16
0
 protected async Task <string> SaslStart(IConnection connection, string message, IRequestSpan span, CancellationToken token)
 {
     using var childSpan = span.ChildSpan(OuterRequestSpans.ServiceSpan.Internal.SaslStart);
     using var authOp    = new SaslStart
           {
               Key     = MechanismType.GetDescription(),
               Content = message,
               Timeout = Timeout,
               Span    = childSpan
           };
     OperationConfigurator.Configure(authOp, SaslOptions.Instance);
     return(await SendAsync(authOp, connection, token).ConfigureAwait(false));
 }
Exemplo n.º 17
0
 protected async Task <string> SaslStart(IConnection connection, string message, IInternalSpan span, CancellationToken token)
 {
     using var childSpan = Tracer.InternalSpan(OperationNames.SaslStart, span);
     using var authOp    = new SaslStart
           {
               Key        = MechanismType.GetDescription(),
               Content    = message,
               Transcoder = Transcoder,
               Timeout    = Timeout,
               Span       = childSpan
           };
     return(await SendAsync(authOp, connection, token).ConfigureAwait(false));
 }
Exemplo n.º 18
0
        /// <summary>
        /// Authenticates a username and password using a specific <see cref="IConnection"/> instance. The password will
        /// be encrypted before being sent to the server.
        /// </summary>
        /// <param name="connection">An implementation of <see cref="IConnection"/> which represents a TCP connection to a Couchbase Server.</param>
        /// <param name="username">The username or bucket name to authentic against.</param>
        /// <param name="password">The password to authenticate against.</param>
        /// <returns>True if succesful.</returns>
        public bool Authenticate(IConnection connection, string username, string password)
        {
            var authenticated = false;

            Username = username;
            Password = password ?? string.Empty;

            var temp = connection;

            Log.Debug(m => m("Authenticating socket {0}", temp.Identity));

            var operation = new SaslStart(MechanismType, null, _converter);
            var result    = _ioStrategy.Execute(operation, connection);

            if (result.Status == ResponseStatus.AuthenticationContinue)
            {
                var challenge = result.Message;
                var reply     = ComputeResponse(challenge);

                operation = new SaslStep(MechanismType, reply, _converter);
                result    = _ioStrategy.Execute(operation, connection);
            }

            //even if the request succeeded, if the body doesn't contain 'Authenticated' then auth failed.
            authenticated = result.Status == ResponseStatus.Success &&
                            result.Value.Equals("Authenticated");

            if (result.Status == ResponseStatus.AuthenticationError)
            {
                var tempResult = result;
                Log.Debug(m => m("Authentication for socket {0} failed: {1}", temp.Identity, tempResult.Message));
            }
            else if (result.Status != ResponseStatus.Success)
            {
                var tempResult = result;
                Log.Debug(m => m("Authentication for socket {0} failed for a non-auth related reason: {1} - {2}", temp.Identity, tempResult.Message, tempResult.Status));
                if (operation.Exception != null)
                {
                    Log.Debug(m => m("Throwing exception for connection {0}", temp.Identity));
                    throw operation.Exception;
                }
            }
            else
            {
                Log.Debug(m => m("Authentication for socket {0} succeeded.", temp.Identity));
            }

            return(authenticated);
        }
        public void When_SaslMechinism_Is_Set_On_MultiplexingIOService_And_Authentication_Fails_Return_AuthenticationError()
        {
            var mockAuthenticator = new Mock<ISaslMechanism>();
            mockAuthenticator.Setup(x => x.Authenticate(It.IsAny<IConnection>(), Username, Password))
                .Returns(false);
            mockAuthenticator.SetupGet(x => x.Username).Returns(BucketName);

            var service = new MultiplexingIOService(_connectionPool, mockAuthenticator.Object);
            var operation = new SaslStart("PLAIN", GetAuthData(Username, Password), new DefaultTranscoder(), OperationLifespan);
            var response = service.Execute(operation);

            Assert.AreEqual(string.Format("Authentication failed for bucket '{0}'", BucketName), response.Message);
            Assert.AreEqual(ResponseStatus.AuthenticationError, response.Status);
            Assert.IsFalse(response.Success);
        }
        public void When_SaslMechinism_Is_Set_On_MultiplexingIOService_And_Authentication_Fails_Return_AuthenticationError()
        {
            var mockAuthenticator = new Mock <ISaslMechanism>();

            mockAuthenticator.Setup(x => x.Authenticate(It.IsAny <IConnection>(), Username, Password))
            .Returns(false);
            mockAuthenticator.SetupGet(x => x.Username).Returns(BucketName);

            var service   = new MultiplexingIOService(_connectionPool, mockAuthenticator.Object);
            var operation = new SaslStart("PLAIN", GetAuthData(Username, Password), new DefaultTranscoder(), OperationLifespan);
            var response  = service.Execute(operation);

            Assert.AreEqual(string.Format("Authentication failed for bucket '{0}'", BucketName), response.Message);
            Assert.AreEqual(ResponseStatus.AuthenticationError, response.Status);
            Assert.IsFalse(response.Success);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Authenticates a username and password using a specific <see cref="IConnection"/> instance. The password will
        /// be encrypted before being sent to the server.
        /// </summary>
        /// <param name="connection">An implementation of <see cref="IConnection"/> which represents a TCP connection to a Couchbase Server.</param>
        /// <param name="username">The username or bucket name to authentic against.</param>
        /// <param name="password">The password to authenticate against.</param>
        /// <returns>True if succesful.</returns>
        public bool Authenticate(IConnection connection, string username, string password)
        {
            Username = username;
            Password = password ?? string.Empty;

            var temp = connection;

            var operation = new SaslStart(MechanismType, (VBucket)null, _transcoder, SaslFactory.DefaultTimeout);

            Log.Debug("Authenticating socket {0} with opaque {1}", temp.Identity, operation.Opaque);

            var result = Execute(operation, connection);

            if (result.Status == ResponseStatus.AuthenticationContinue)
            {
                var challenge = result.Value;
                var reply     = ComputeResponse(challenge);

                operation = new SaslStep(MechanismType, reply, _transcoder, SaslFactory.DefaultTimeout);
                result    = Execute(operation, connection);
            }

            if (result.Status == ResponseStatus.AuthenticationError)
            {
                var tempResult = result;
                Log.Debug("Authentication for socket {0} failed: {1}", temp.Identity, tempResult.Message);
            }
            else if (result.Status != ResponseStatus.Success)
            {
                var tempResult = result;
                Log.Debug("Authentication for socket {0} failed for a non-auth related reason: {1} - {2}", temp.Identity, tempResult.Message, tempResult.Status);
                if (operation.Exception != null)
                {
                    Log.Debug("Throwing exception for connection {0}", temp.Identity);
                    throw operation.Exception;
                }
            }
            else
            {
                Log.Debug("Authentication for socket {0} succeeded.", temp.Identity);
            }

            return(result.Status == ResponseStatus.Success);
        }
        public bool Authenticate(IConnection connection, string username, string password)
        {
            var authenticated = false;

            ClientFirstMessage     = "n,,n=" + username + ",r=" + ClientNonce;
            ClientFirstMessageBare = ClientFirstMessage.Substring(3);

            Log.Debug("Client First Message {0} - {1}: {2} [U:{3}|P:{4}", connection.EndPoint, connection.Identity, ClientFirstMessage, username, password);
            var authOp            = new SaslStart(MechanismType, ClientFirstMessage, _transcoder, SaslFactory.DefaultTimeout);
            var serverFirstResult = Execute(authOp, connection);

            if (serverFirstResult.Status == ResponseStatus.AuthenticationContinue)
            {
                Log.Debug("Server First Message {0} - {1}: {2}", connection.EndPoint, connection.Identity, serverFirstResult.Message);

                //get the server nonce, salt and iterationcount from the server
                var serverFirstMessage = DecodeResponse(serverFirstResult.Value);
                ServerNonce    = serverFirstMessage["r"];
                Salt           = Convert.FromBase64String(serverFirstMessage["s"]);
                IterationCount = Convert.ToInt32(serverFirstMessage["i"]);

                //normalize and salt the password using the salt and iteration count
                var normalizedPassword = password.Normalize(NormalizationForm.FormKC);
                SaltedPassword = GetSaltedPassword(normalizedPassword);

                //build the final client message
                ClientFinalMessageNoProof = "c=biws,r=" + ServerNonce;
                ClientFinalMessage        = ClientFinalMessageNoProof + ",p=" + Convert.ToBase64String(GetClientProof());
                Log.Debug("Client Final Message {0} - {1}: {2}", connection.EndPoint, connection.Identity, ClientFinalMessage);

                //send the final client message
                authOp = new SaslStep(MechanismType, ClientFinalMessage, _transcoder, SaslFactory.DefaultTimeout);
                var serverFinalResult = Execute(authOp, connection);
                Log.Debug("Server Final Message {0} - {1}: {2}", connection.EndPoint, connection.Identity, serverFinalResult.Message);
                authenticated = serverFinalResult.Status == ResponseStatus.Success;
            }
            return(authenticated);
        }
Exemplo n.º 23
0
        bool Authenticate(IPooledSocket socket)
        {
            var       isAuthenticated = true;
            const int authContinue    = 0x21;

            SaslStep step = new SaslStart(_provider);

            socket.Write(step.GetBuffer());
            while (!step.ReadResponse(socket).Success)
            {
                if (step.StatusCode == authContinue)
                {
                    step = new SaslContinue(_provider, step.Data);
                    socket.Write(step.GetBuffer());
                }
                else
                {
                    isAuthenticated = false;
                    break;
                }
            }
            return(isAuthenticated);
        }
        /// <summary>
        /// Authenticates a username and password using a specific <see cref="IConnection"/> instance.
        /// </summary>
        /// <param name="connection">An implementation of <see cref="IConnection"/> which represents a TCP connection to a Couchbase Server.</param>
        /// <param name="username">The username or bucket name to authentic against.</param>
        /// <param name="password">The password to authenticate against.</param>
        /// <returns>True if succesful.</returns>
        public bool Authenticate(IConnection connection, string username, string password)
        {
            var authenticated = false;
            var temp = connection;
            Log.LogDebug("Authenticating socket {0}", temp.Identity);

            try
            {
                var operation = new SaslStart(MechanismType, GetAuthData(username, password), _transcoder, SaslFactory.DefaultTimeout);
                var result = _service.Execute(operation, connection);

                if (!result.Success &&
                    result.Status == ResponseStatus.AuthenticationError)
                {
                    Log.LogDebug("Authentication for socket {0} failed: {1}", temp.Identity, result.Value);
                }
                else
                {
                    authenticated = true;
                    Log.LogDebug("Authenticated socket {0} succeeded: {1}", temp.Identity, result.Value);
                }
            }
            catch (Exception e)
            {
                Log.LogError(e.Message, e);
            }
            return authenticated;
        }
Exemplo n.º 25
0
        /// <summary>
        /// Authenticates a username and password using a specific <see cref="IConnection"/> instance. The password will
        /// be encrypted before being sent to the server.
        /// </summary>
        /// <param name="connection">An implementation of <see cref="IConnection"/> which represents a TCP connection to a Couchbase Server.</param>
        /// <param name="username">The username or bucket name to authentic against.</param>
        /// <param name="password">The password to authenticate against.</param>
        /// <returns>True if succesful.</returns>
        public bool Authenticate(IConnection connection, string username, string password)
        {
            Username = username;
            Password = password ?? string.Empty;

            var temp = connection;

            var operation = new SaslStart(MechanismType, (VBucket)null, _transcoder, SaslFactory.DefaultTimeout);
            Log.LogDebug("Authenticating socket {0} with opaque {1}", temp.Identity, operation.Opaque);

            var result = _ioService.Execute(operation, connection);
            if (result.Status == ResponseStatus.AuthenticationContinue)
            {
                var challenge = result.Message;
                var reply = ComputeResponse(challenge);

                operation = new SaslStep(MechanismType, reply, _transcoder, SaslFactory.DefaultTimeout);
                result = _ioService.Execute(operation, connection);
            }

            if (result.Status == ResponseStatus.AuthenticationError)
            {
                var tempResult = result;
                Log.LogDebug("Authentication for socket {0} failed: {1}", temp.Identity, tempResult.Message);
            }
            else if (result.Status != ResponseStatus.Success)
            {
                var tempResult = result;
                Log.LogDebug("Authentication for socket {0} failed for a non-auth related reason: {1} - {2}", temp.Identity, tempResult.Message, tempResult.Status);
                if (operation.Exception != null)
                {
                    Log.LogDebug("Throwing exception for connection {0}", temp.Identity);
                    throw operation.Exception;
                }
            }
            else
            {
                Log.LogDebug("Authentication for socket {0} succeeded.", temp.Identity);
            }

            return result.Status == ResponseStatus.Success;
        }
        /// <summary>
        /// Authenticates a username and password using a specific <see cref="IConnection"/> instance.
        /// </summary>
        /// <param name="connection">An implementation of <see cref="IConnection"/> which represents a TCP connection to a Couchbase Server.</param>
        /// <param name="username">The username or bucket name to authentic against.</param>
        /// <param name="password">The password to authenticate against.</param>
        /// <returns>True if succesful.</returns>
        public bool Authenticate(IConnection connection, string username, string password)
        {
            var authenticated = false;
            var temp = connection;
            Log.Debug(m => m("Authenticating socket {0}", temp.Identity));

            try
            {
                var operation = new SaslStart(MechanismType, GetAuthData(username, password), _converter);
                var result = _strategy.Execute(operation, connection);

                if (!result.Success &&
                    result.Status == ResponseStatus.AuthenticationError)
                {
                    Log.Debug(m => m("Authentication for socket {0} failed: {1}", temp.Identity, result.Value));
                }
                else
                {
                    authenticated = true;
                    Log.Debug(m => m("Authenticated socket {0} succeeded: {1}", temp.Identity, result.Value));
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            return authenticated;
        }
        /// <summary>
        /// Authenticates a username and password using a specific <see cref="IConnection"/> instance. The password will
        /// be encrypted before being sent to the server.
        /// </summary>
        /// <param name="connection">An implementation of <see cref="IConnection"/> which represents a TCP connection to a Couchbase Server.</param>
        /// <param name="username">The username or bucket name to authentic against.</param>
        /// <param name="password">The password to authenticate against.</param>
        /// <returns>True if succesful.</returns>
        public bool Authenticate(IConnection connection, string username, string password)
        {
            var authenticated = false;
            Username = username;
            Password = password ?? string.Empty;
           
            var temp = connection;
            Log.Debug(m => m("Authenticating socket {0}", temp.Identity));

            var operation = new SaslStart(MechanismType, null, _converter);
            var result = _ioStrategy.Execute(operation, connection);
            if (result.Status == ResponseStatus.AuthenticationContinue)
            {
                var challenge = result.Message;
                var reply = ComputeResponse(challenge);

                operation = new SaslStep(MechanismType, reply, _converter);
                result = _ioStrategy.Execute(operation, connection);
            }

            authenticated = result.Status == ResponseStatus.Success &&
                   result.Value.Equals("Authenticated");

            if (result.Status == ResponseStatus.AuthenticationError)
            {
                var tempResult = result;
                Log.Debug(m => m("Authentication for socket {0} failed: {1}", temp.Identity, tempResult.Message));
            }
            else if (result.Status != ResponseStatus.Success)
            {
                var tempResult = result;
                Log.Debug(m => m("Authentication for socket {0} failed: {1}", temp.Identity, tempResult.Message));
                if (operation.Exception != null)
                {
                    throw operation.Exception;
                }
            }
            else
            {
                Log.Debug(m => m("Authentication for socket {0} succeeded.", temp.Identity));
            }

            return authenticated;
        }