Exemple #1
0
        public void AuthServiceMsgs_Msg_AuthMsgAndAck()
        {
            EnhancedStream       es = new EnhancedMemoryStream();
            AuthMsg              authMsgIn, authMsgOut;
            AuthAck              authAckIn, authAckOut;
            string               rsaKey = AsymmetricCrypto.CreatePrivateKey(CryptoAlgorithm.RSA, 1024);
            SymmetricKey         saClient, saServer;
            string               r, a, p;
            AuthenticationResult authResult;

            authMsgOut = new AuthMsg(AuthMsg.EncryptCredentials(rsaKey, "realm", "account", "password", out saClient));

            Msg.Save(es, authMsgOut);
            es.Position = 0;
            authMsgIn   = (AuthMsg)Msg.Load(es);

            AuthMsg.DecryptCredentials(rsaKey, authMsgIn.EncryptedCredentials, out r, out a, out p, out saServer);

            Assert.AreEqual("realm", r);
            Assert.AreEqual("account", a);
            Assert.AreEqual("password", p);

            authAckOut = new AuthAck(AuthAck.EncryptResult(saServer, new AuthenticationResult(AuthenticationStatus.Authenticated, "Test", TimeSpan.FromMinutes(25))));

            es.SetLength(0);
            Msg.Save(es, authAckOut);
            es.Position = 0;
            authAckIn   = (AuthAck)Msg.Load(es);

            authResult = AuthAck.DecryptResult(saClient, authAckIn.EncryptedResult);
        }
Exemple #2
0
 private void VerifySplitList(String s, String[] expected)
 {
     String[] split = AuthMsg.SplitList(s);
     Assert.AreEqual(split.Length, expected.Length);
     for (int i = 0; i < split.Length; i++)
     {
         Assert.AreEqual(split[i], expected[i]);
     }
     AuthMsg[] msgs = AuthMsg.ListFromStr(s);
     Assert.AreEqual(msgs.Length, expected.Length);
 }
Exemple #3
0
 public void BadFromStrTest()
 {
     AuthMsg.FromStr("hmac salt=a=b hash=sha-1");
     AuthMsg.FromStr("hmac salt=abc hash=sha-1 bad/key=val");
     AuthMsg.FromStr("(bad)");
     AuthMsg.FromStr("ok key=val not good");
     AuthMsg.FromStr("ok key not good=val");
     AuthMsg.FromStr("ok key not good=val");
     AuthMsg.FromStr("hmac foo");
     AuthMsg.FromStr("hmac foo=bar xxx");
 }
Exemple #4
0
        public void EncodeTest()
        {
            //basic identity
            Assert.AreEqual(AuthMsg.FromStr("foo"), AuthMsg.FromStr("foo"));
            Assert.AreEqual(AuthMsg.FromStr("a x=y"), AuthMsg.FromStr("a x=y"));
            Assert.AreEqual(AuthMsg.FromStr("a i=j, x=y"), AuthMsg.FromStr("a i = j, x = y"));
            Assert.AreEqual(AuthMsg.FromStr("a i=j, x=y"), AuthMsg.FromStr("a i=j, x=y"));
            Assert.AreNotEqual(AuthMsg.FromStr("foo"), AuthMsg.FromStr("bar"));
            Assert.AreNotEqual(AuthMsg.FromStr("foo"), AuthMsg.FromStr("foo k=v"));

            //basics on fromStr
            AuthMsg q = AuthMsg.FromStr("foo alpha=beta, gamma=delta");

            Assert.AreEqual(q.scheme, "foo");
            Assert.AreEqual(q.Param("alpha"), "beta");
            Assert.AreEqual(q.Param("Alpha"), "beta");
            Assert.AreEqual(q.Param("ALPHA"), "beta");
            Assert.AreEqual(q.Param("Gamma"), "delta");

            //fromStr parsing
            SortedDictionary <string, string> parameters = new SortedDictionary <string, string>();

            parameters.Add("alpha", "beta");
            Assert.AreEqual(AuthMsg.FromStr("foo alpha \t = \t beta"), new AuthMsg("foo", parameters));

            parameters.Clear();
            parameters.Add("A", "b");
            parameters.Add("C", "d");
            parameters.Add("E", "f");
            parameters.Add("G", "h");
            Assert.AreEqual(AuthMsg.FromStr("foo a=b, c = d, e=f, g=h"), new AuthMsg("foo", parameters));

            parameters.Clear();
            parameters.Add("G", "h");
            parameters.Add("E", "f");
            parameters.Add("C", "d");
            parameters.Add("A", "b");
            Assert.AreEqual(AuthMsg.FromStr("foo a=b, c = d, e=f, g=h"), new AuthMsg("foo", parameters));

            parameters.Clear();
            parameters.Add("G", "h");
            parameters.Add("E", "f");
            parameters.Add("C", "d");
            parameters.Add("A", "b");
            Assert.AreEqual(AuthMsg.FromStr("foo g=h, c = d, e=f,  a = b").ToString(), "foo a=b, c=d, e=f, g=h");
        }
Exemple #5
0
            public override void Update()
            {
                base.Update();

                if (_obj is AuthMsg)
                {
                    // authentication
                    AuthMsg authMsg = (AuthMsg)_obj;
                    if (authMsg.psw == Server._password)
                    {
                        MsgStream.Send(new AckMsg(true), Server._commSocket);
                        Server.SetAuthenticated();
                    }
                    else
                    {
                        MsgStream.Send(new AckMsg(false), Server._commSocket);
                        Server.State = new WaitingState();
                    }
                }
            }
Exemple #6
0
        /// <summary>
        /// Handles the async reception of the public key from the authentication service.
        /// </summary>
        /// <param name="ar">The async result instance.</param>
        private void OnGetKey(IAsyncResult ar)
        {
            AuthAsyncResult arAuth = (AuthAsyncResult)ar.AsyncState;
            GetPublicKeyAck ack;
            AuthMsg         authMsg;

            using (TimedLock.Lock(this))
            {
                try
                {
                    if (!isOpen)
                    {
                        throw new AuthenticationException(NotOpenMsg);
                    }

                    ack       = (GetPublicKeyAck)router.EndQuery(ar);
                    publicKey = ack.PublicKey;

                    // Now that we have the public key, we're going to broadcast
                    // it to the authentication service instances so that they can
                    // perform a man-in-the-middle security check.

                    router.BroadcastTo(AbstractAuthServerEP, new AuthServerIDMsg(ack.PublicKey, ack.MachineName, ack.Address));

                    // Now initiate the authentication query.

                    arAuth.OpState = AuthOpState.AuthPending;
                    authMsg        = new AuthMsg(AuthMsg.EncryptCredentials(publicKey, arAuth.Realm, arAuth.Account, arAuth.Password, out arAuth.SymmetricKey));

                    router.BeginQuery(AbstractAuthServerEP, authMsg, onAuth, arAuth);
                }
                catch (System.TimeoutException)
                {
                    arAuth.Notify(new AuthenticationException("No authentication service instances responded."));
                }
                catch (Exception e)
                {
                    arAuth.Notify(e);
                }
            }
        }
        private MainMessage HandleAuthMsg(MainMessage msg)
        {
            _log.Debug("Received authorization message.");
            AuthMsg authMsg  = msg.UserMngMsg.AuthMsg;
            string  username = authMsg.Username;
            string  password = authMsg.Password;

            User user = User.Get(username);

            if (user == null)
            {
                _log.Debug("Could not find user with this username.");
                return(ISystemService.CreateErrorMessage(0, 0, 0,
                                                         "Could not find user with this username."));
            }
            if (!user.CheckPassword(password))
            {
                _log.Debug("Invalid password.");
                return(ISystemService.CreateErrorMessage(0, 0, 0,
                                                         "Invalid password."));
            }
            MainMessage response = new MainMessage();

            response.UserMngMsg         = new UserMngMsg();
            response.UserMngMsg.UserMsg = new UserMsg();
            response.UserMngMsg.UserMsg.UserDetailMsg          = user.ToMessage();
            response.UserMngMsg.UserMsg.UserDetailMsg.Password = "";

            // clientId == 0 --> unsassigned ID
            if (msg.ClientId != 0 && msg.ClientId < (ulong)_clientMachines.Count)
            {
                _clientMachines[(int)msg.ClientId] = user;
                response.ClientId = msg.ClientId;
            }
            else
            {
                response.ClientId = (uint)_clientMachines.Count;
                _clientMachines.Add(user);
            }
            return(response);
        }
Exemple #8
0
        /// <summary>
        /// Initiates an asynchronous account credential authentication.
        /// </summary>
        /// <param name="realm">The authentication realm.</param>
        /// <param name="account">The account.</param>
        /// <param name="password">The password.</param>
        /// <param name="callback">The delegate to be called when the operation completes (or <c>null</c>).</param>
        /// <param name="state">Application defined state (or <c>null</c>).</param>
        /// <returns>An <see cref="IAsyncResult" /> instance to be used to track the operation.</returns>
        /// <remarks>
        /// <note>
        /// Successful calls to this method must eventually be followed by a call
        /// to <see cref="EndAuthenticate" />.
        /// </note>
        /// </remarks>
        /// <exception cref="AuthenticationException">Thrown if the authenticator is not open.</exception>
        public IAsyncResult BeginAuthenticate(string realm, string account, string password, AsyncCallback callback, object state)
        {
            string               cacheKey = GetCacheKey(realm, account, password);
            AuthAsyncResult      arAuth;
            AuthenticationResult result;

            using (TimedLock.Lock(this))
            {
                if (!isOpen)
                {
                    throw new AuthenticationException(NotOpenMsg);
                }

                arAuth          = new AuthAsyncResult(this, callback, state);
                arAuth.Realm    = realm;
                arAuth.Account  = account;
                arAuth.Password = password;

                arAuth.Started();

                // First check to see if the answer is already cached

                if (cache != null && cache.TryGetValue(cacheKey, out result))
                {
                    arAuth.Result = result;
                    arAuth.Notify();

                    if (result.Status != AuthenticationStatus.Authenticated &&
                        result.Status != AuthenticationStatus.AccountLocked)
                    {
                        // If the authentication failed and the account is not locked
                        // then broadcast message to the authentication services so that
                        // they can increment their fail counts.

                        router.BroadcastTo(AbstractAuthServerEP, new AuthControlMsg("auth-failed", string.Format("realm={0};account={1};status={2}", realm, account, result.Status)));
                    }

                    return(arAuth);
                }

                // If we don't have the authentication service's public key yet then
                // initiate an async query to get it.

                if (publicKey == null)
                {
                    arAuth.OpState = AuthOpState.GetPublicKey;
                    router.BeginQuery(AbstractAuthServerEP, new GetPublicKeyMsg(), onGetKey, arAuth);
                    return(arAuth);
                }

                // Initiate an async authentication query, encrypting the credentials
                // using the authentication service's public key.

                AuthMsg authMsg;

                arAuth.OpState = AuthOpState.AuthPending;
                authMsg        = new AuthMsg(AuthMsg.EncryptCredentials(publicKey, realm, account, password, out arAuth.SymmetricKey));

                router.BeginQuery(AbstractAuthServerEP, authMsg, onAuth, arAuth);

                return(arAuth);
            }
        }