Esempio n. 1
0
        public object Login(string id, string pwd)
        {
            WorkContext.NeedsSession();
            var session = WorkContext.Session;


            if (session == null || id.IsNullOrWhiteSpace())
            {
                return(Localizer.MakePage <Pages.Login>(""));
            }


            if (session.User.Status == UserStatus.Invalid)
            {
                var cred = new IDPasswordCredentials(id, pwd);
                var user = App.SecurityManager.Authenticate(cred);
                if (user.Status == UserStatus.Invalid)
                {
                    return(Localizer.MakePage <Pages.Login>("Invalid login"));
                }

                WorkContext.Session.User = user;
            }
            return(new Redirect("/"));
        }
Esempio n. 2
0
        public void Authenticate_BadUserPassword(int realm)
        {
            var credentials = new IDPasswordCredentials("user1", "wqerwqerwqer");
            var user        = m_App.SecurityManager.Authenticate(credentials);

            Aver.IsTrue(user.Status == UserStatus.Invalid);
        }
Esempio n. 3
0
        public void CalcStrenghtScore()
        {
            var buf   = IDPasswordCredentials.PlainPasswordToSecureBuffer("qwerty");
            var score = Manager.CalculateStrenghtScore(PasswordFamily.Text, buf);

            Aver.AreEqual(30, score);

            buf   = IDPasswordCredentials.PlainPasswordToSecureBuffer("qwerty123");
            score = Manager.CalculateStrenghtScore(PasswordFamily.Text, buf);
            Aver.AreEqual(93, score);

            buf   = IDPasswordCredentials.PlainPasswordToSecureBuffer("aaaaaaaaaaaaaaaaaaaaaaa");
            score = Manager.CalculateStrenghtScore(PasswordFamily.Text, buf);
            Aver.AreEqual(32, score);

            buf   = IDPasswordCredentials.PlainPasswordToSecureBuffer("@blue+sky=");
            score = Manager.CalculateStrenghtScore(PasswordFamily.Text, buf);
            Aver.AreEqual(198, score);

            buf   = IDPasswordCredentials.PlainPasswordToSecureBuffer("@8luE+5ky=");
            score = Manager.CalculateStrenghtScore(PasswordFamily.Text, buf);
            Aver.AreEqual(299, score);

            buf   = IDPasswordCredentials.PlainPasswordToSecureBuffer(null);
            score = Manager.CalculateStrenghtScore(PasswordFamily.Text, buf);
            Aver.AreEqual(0, score);

            buf   = IDPasswordCredentials.PlainPasswordToSecureBuffer(string.Empty);
            score = Manager.CalculateStrenghtScore(PasswordFamily.Text, buf);
            Aver.AreEqual(0, score);

            buf   = IDPasswordCredentials.PlainPasswordToSecureBuffer("   ");
            score = Manager.CalculateStrenghtScore(PasswordFamily.Text, buf);
            Aver.AreEqual(0, score);
        }
Esempio n. 4
0
        public void Verify_InvalidHash()
        {
            var  buf = IDPasswordCredentials.PlainPasswordToSecureBuffer("@8luE+5ky=");
            var  hash = Manager.ComputeHash(PasswordFamily.Text, buf);
            bool rehash, check;

            hash["salt"] = null;
            try
            {
                check = Manager.Verify(buf, hash, out rehash);
                Aver.Fail("no exception");
            }
            catch (AzosException e)
            {
                Aver.IsTrue(e.Message.Contains("ExtractPasswordHashingOptions((hash|hash[salt])==null)"));
            }

            hash = null;
            try
            {
                check = Manager.Verify(buf, hash, out rehash);
                Aver.Fail("no exception");
            }
            catch (AzosException e)
            {
                Aver.IsTrue(e.Message.Contains("Verify((password|hash)==null)"));
            }
        }
Esempio n. 5
0
        public void Authenticate_RegularUser_2_Invalid_KDFPassword()
        {
            var credentials = new IDPasswordCredentials("ukdf2", "zizi-kaka12345");
            var user        = m_App.SecurityManager.Authenticate(credentials);

            Aver.IsTrue(user.Status == UserStatus.Invalid);
        }
Esempio n. 6
0
 public void Authenticate_IDPasswordCredentials(int realm, string name, string pwd)
 {
   var credentials = new IDPasswordCredentials("user1", pwd);
   var user = m_App.SecurityManager.Authenticate(credentials);
   Aver.IsTrue(user.Status == UserStatus.User);
   Aver.AreEqual(name, user.Name);
 }
Esempio n. 7
0
        public void AreEquivalent()
        {
            var buf   = IDPasswordCredentials.PlainPasswordToSecureBuffer("@8luE+5ky=");
            var hash1 = Manager.ComputeHash(PasswordFamily.Text, buf);
            var hash2 = HashedPassword.FromString(hash1.ToString());



            Aver.IsTrue(m_Manager.AreEquivalent(hash1, hash2));

            Aver.IsFalse(m_Manager.AreEquivalent(null, null));

            var hash3 = new HashedPassword("OTH", hash2.Family);

            hash3["hash"] = hash2["hash"];
            hash3["salt"] = hash2["salt"];
            Aver.IsFalse(m_Manager.AreEquivalent(hash1, hash3));

            hash2 = Manager.ComputeHash(PasswordFamily.Text, buf);
            Aver.IsFalse(m_Manager.AreEquivalent(hash1, hash2));

            buf   = IDPasswordCredentials.PlainPasswordToSecureBuffer("qwerty");
            hash2 = Manager.ComputeHash(PasswordFamily.Text, buf);
            Aver.IsFalse(m_Manager.AreEquivalent(hash1, hash2));
        }
Esempio n. 8
0
        public void Authenticate_IDPasswordCredentials()
        {
            var credentials = new IDPasswordCredentials("user1", "awsedr");
            var user        = m_App.SecurityManager.Authenticate(credentials);

            Aver.IsTrue(user.Status == UserStatus.User);
            Aver.AreEqual("User1", user.Name);
        }
Esempio n. 9
0
        public void Authenticate_RegularUser_3_KDFPassword()
        {
            var credentials = new IDPasswordCredentials("ukdf3", "zizi-kaka12345");
            var user        = m_App.SecurityManager.Authenticate(credentials);

            Aver.IsTrue(user.Status == UserStatus.User);
            Aver.AreEqual("UserKDF3", user.Name);
            Aver.AreEqual("User3 with KDF password", user.Description);
        }
Esempio n. 10
0
        public void Authenticate_SystemUser()
        {
            var credentials = new IDPasswordCredentials("sys", "thejake");
            var user        = m_App.SecurityManager.Authenticate(credentials);

            Aver.IsTrue(user.Status == UserStatus.System);
            Aver.AreEqual("UserSystem", user.Name);
            Aver.AreEqual("User System", user.Description);
        }
Esempio n. 11
0
        public void Authenticate_RegularUser()
        {
            var credentials = new IDPasswordCredentials("user1", "thejake");
            var user        = m_App.SecurityManager.Authenticate(credentials);

            Aver.IsTrue(user.Status == UserStatus.User);
            Aver.AreEqual("User1", user.Name);
            Aver.AreEqual("Just a User", user.Description);
        }
Esempio n. 12
0
        public void Compute_Verify_Fail()
        {
            var  buf = IDPasswordCredentials.PlainPasswordToSecureBuffer("@8luE+5ky=");
            bool rehash, check;

            var hash = Manager.ComputeHash(PasswordFamily.Text, buf);

            buf   = IDPasswordCredentials.PlainPasswordToSecureBuffer("qwerty");
            check = Manager.Verify(buf, hash, out rehash);
            Aver.IsFalse(check);
        }
Esempio n. 13
0
        //We always make a new in-memory ephemeral session which gets collected right after this request
        protected override WaveSession MakeNewSessionInstance(WorkContext work)
        {
            const string BASIC  = WebConsts.AUTH_SCHEME_BASIC + " ";
            const string BEARER = WebConsts.AUTH_SCHEME_BEARER + " ";

            //Always create new session
            var session = base.MakeNewSessionInstance(work);

            //try to inject session.DataContextName
            var dch = DataContextHeader;

            if (dch.IsNotNullOrWhiteSpace())
            {
                var dcn = work.Request.Headers[dch];
                if (dcn.IsNotNullOrWhiteSpace())
                {
                    dcn = dcn.Trim().TakeFirstChars(1024);//hard limit safeguard
                    session.DataContextName = dcn;
                }
            }

            var hdr = work.Request.Headers[WebConsts.HTTP_HDR_AUTHORIZATION]?.TrimStart(' ');

            if (hdr.IsNullOrWhiteSpace())
            {
                return(session);                   //unauthorized
            }
            Credentials credentials = null;

            try
            {
                if (hdr.StartsWith(BASIC, StringComparison.OrdinalIgnoreCase))
                {
                    var basic = hdr.Substring(BASIC.Length).Trim();
                    credentials = IDPasswordCredentials.FromBasicAuth(basic);
                }
                else if (hdr.StartsWith(BEARER, StringComparison.OrdinalIgnoreCase))
                {
                    var bearer = hdr.Substring(BEARER.Length).Trim();
                    credentials = new BearerCredentials(bearer);
                }
            }
            catch { }

            if (credentials == null)
            {
                throw HTTPStatusException.BadRequest_400("Bad [Authorization] header");
            }

            session.User = App.SecurityManager.Authenticate(credentials);//authenticate the user
            work.SetAuthenticated(session.User.IsAuthenticated);
            return(session);
        }
Esempio n. 14
0
        public override void Configure(IConfigSectionNode node)
        {
            base.Configure(node);

            var unm  = node.AttrByName(CONFIG_UNAME_ATTR).Value;
            var upwd = node.AttrByName(CONFIG_UPWD_ATTR).Value;

            if (unm.IsNotNullOrWhiteSpace())
            {
                var cred = new IDPasswordCredentials(unm, upwd);
                var at   = new AuthenticationToken(ServerURL, unm);
                User = new User(cred, at, UserStatus.User, unm, unm, Rights.None);
            }
        }
Esempio n. 15
0
        public void CalcStrenghtPercent()
        {
            var buf  = IDPasswordCredentials.PlainPasswordToSecureBuffer("qwerty");
            var pcnt = Manager.CalculateStrenghtPercent(PasswordFamily.Text, buf);

            Aver.AreEqual(12, pcnt);

            buf  = IDPasswordCredentials.PlainPasswordToSecureBuffer("@8luE+5ky=");
            pcnt = Manager.CalculateStrenghtPercent(PasswordFamily.Text, buf);
            Aver.AreEqual(100, pcnt);

            buf  = IDPasswordCredentials.PlainPasswordToSecureBuffer("@8luE+5ky=");
            pcnt = Manager.CalculateStrenghtPercent(PasswordFamily.Text, buf, DefaultPasswordManager.TOP_SCORE_MAXIMUM);
            Aver.AreEqual(85, pcnt);
        }
Esempio n. 16
0
        public void CheckServiceActive()
        {
            var pm  = new DefaultPasswordManager(NOPApplication.Instance);
            var buf = IDPasswordCredentials.PlainPasswordToSecureBuffer("@8luE+5ky=");

            try
            {
                var hash = pm.ComputeHash(PasswordFamily.Text, buf);
                Aver.Fail("no exception");
            }
            catch (AzosException e)
            {
                Aver.AreEqual(e.Message, StringConsts.DAEMON_INVALID_STATE +
                              typeof(DefaultPasswordManager).Name);
            }
        }
Esempio n. 17
0
        public void CheckServiceActive()
        {
            var pm  = new DefaultPasswordManager();
            var buf = IDPasswordCredentials.PlainPasswordToSecureBuffer("@8luE+5ky=");

            try
            {
                var hash = pm.ComputeHash(PasswordFamily.Text, buf);
                Assert.Fail("no exception");
            }
            catch (NFXException e)
            {
                Assert.AreEqual(e.Message, StringConsts.SERVICE_INVALID_STATE +
                                typeof(DefaultPasswordManager).Name);
            }
        }
Esempio n. 18
0
        public void Compute_Verify_Pass()
        {
            var  buf = IDPasswordCredentials.PlainPasswordToSecureBuffer("qwerty");
            var  hash = Manager.ComputeHash(PasswordFamily.Text, buf);
            bool rehash, check;

            check = Manager.Verify(buf, hash, out rehash);
            Aver.IsTrue(check);

            buf   = IDPasswordCredentials.PlainPasswordToSecureBuffer("@8luE+5ky=");
            hash  = Manager.ComputeHash(PasswordFamily.Text, buf);
            check = Manager.Verify(buf, hash, out rehash);
            Aver.IsTrue(check);

            check = Manager.Verify(buf, HashedPassword.FromString(hash.ToJSON()), out rehash);
            Aver.IsTrue(check);
        }
Esempio n. 19
0
        public void AreEquivalent()
        {
            var pm = new DefaultPasswordManager(NOPApplication.Instance);

            pm.Start();

            var buf   = IDPasswordCredentials.PlainPasswordToSecureBuffer("@8luE+5ky=");
            var hash1 = Manager.ComputeHash(PasswordFamily.Text, buf);
            var hash2 = HashedPassword.FromString(hash1.ToString());

            try
            {
                Aver.IsTrue(pm.AreEquivalent(hash1, hash2));
                Aver.Fail("no exception");
            }
            catch (AzosException e)
            {
                Aver.AreEqual(e.Message, StringConsts.DAEMON_INVALID_STATE +
                              typeof(DefaultPasswordManager).Name);
            }

            pm.SignalStop();
            pm.WaitForCompleteStop();

            Aver.IsTrue(pm.AreEquivalent(hash1, hash2));

            Aver.IsFalse(pm.AreEquivalent(null, null));

            var hash3 = new HashedPassword("OTH", hash2.Family);

            hash3["hash"] = hash2["hash"];
            hash3["salt"] = hash2["salt"];
            Aver.IsFalse(pm.AreEquivalent(hash1, hash3));

            hash2 = Manager.ComputeHash(PasswordFamily.Text, buf);
            Aver.IsFalse(pm.AreEquivalent(hash1, hash2));

            buf   = IDPasswordCredentials.PlainPasswordToSecureBuffer("qwerty");
            hash2 = Manager.ComputeHash(PasswordFamily.Text, buf);
            Aver.IsFalse(pm.AreEquivalent(hash1, hash2));
        }
Esempio n. 20
0
        public void Authenticate_Reauthenticate_RegularUser()
        {
            void ensure(User u)
            {
                Aver.IsTrue(u.Status == UserStatus.User);
                Aver.AreEqual("User1", u.Name);
                Aver.AreEqual("Just a User", u.Description);
            }

            var credentials = new IDPasswordCredentials("user1", "thejake");
            var user        = m_App.SecurityManager.Authenticate(credentials);

            ensure(user);

            var token = user.AuthToken;
            var user2 = m_App.SecurityManager.Authenticate(token);

            ensure(user2);

            m_App.SecurityManager.Authenticate(user2);//re-authenticate in-place
            ensure(user2);
        }
Esempio n. 21
0
        static void run(string[] args)
        {
            using (var app = new AzosApplication(args, null))
            {
                var silent = app.CommandArgs["s", "silent"].Exists;
                if (!silent)
                {
                    ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Welcome.txt"));

                    ConsoleUtils.Info("Build information:");
                    Console.WriteLine(" Azos:     " + BuildInformation.ForFramework);
                    Console.WriteLine(" Tool:     " + new BuildInformation(typeof(ascon.ProgramBody).Assembly));
                }

                if (app.CommandArgs["?", "h", "help"].Exists)
                {
                    ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Help.txt"));
                    return;
                }


                var cred = app.CommandArgs["c", "cred"];
                var user = cred.AttrByName("id").Value;
                var pwd  = cred.AttrByName("pwd").Value;

                if (user.IsNullOrWhiteSpace())
                {
                    if (!silent)
                    {
                        Console.Write("User ID: ");
                    }
                    user = Console.ReadLine();
                }
                else
                if (!silent)
                {
                    ConsoleUtils.Info("User ID: " + user);
                }

                if (pwd.IsNullOrWhiteSpace())
                {
                    if (!silent)
                    {
                        Console.Write("Password: "******"Password: <supplied>");
                }


                var node = app.CommandArgs.AttrByIndex(0).ValueAsString("{0}://127.0.0.1:{1}".Args(SysConsts.APTERM_BINDING,
                                                                                                   SysConsts.DEFAULT_HOST_GOV_APPTERM_PORT));

                if (new Node(node).Binding.IsNullOrWhiteSpace())
                {
                    node = "{0}://{1}".Args(SysConsts.APTERM_BINDING, node);
                }

                if (new Node(node).Service.IsNullOrWhiteSpace())
                {
                    node = "{0}:{1}".Args(node, SysConsts.DEFAULT_HOST_GOV_APPTERM_PORT);
                }

                var file = app.CommandArgs["f", "file"].AttrByIndex(0).Value;

                if (file.IsNotNullOrWhiteSpace())
                {
                    if (!System.IO.File.Exists(file))
                    {
                        throw new SkyException("File not found:" + file);
                    }
                    if (!silent)
                    {
                        ConsoleUtils.Info("Reading from file: " + file);
                    }
                    file = System.IO.File.ReadAllText(file);
                    if (!silent)
                    {
                        ConsoleUtils.Info("Command text: " + file);
                    }
                }

                var txt = app.CommandArgs["t", "txt"].AttrByIndex(0).Value;

                if (txt.IsNotNullOrWhiteSpace())
                {
                    if (!silent)
                    {
                        ConsoleUtils.Info("Verbatim command text: " + txt);
                    }
                }

                var credentials = new IDPasswordCredentials(user, pwd);


                using (var client = new RemoteTerminal(app.Glue, node.ToResolvedServiceNode(true)))
                {
                    client.Headers.Add(new AuthenticationHeader(credentials));

                    var hinfo = client.Connect("{0}@{1}".Args(user, System.Environment.MachineName));
                    if (!silent)
                    {
                        var c = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.Magenta;
                        Console.WriteLine("Connected. Use ';' at line end to submit statement, 'exit;' to disconnect");
                        Console.WriteLine("Type 'help;' for edification or '<command> /?;' for command-specific help");
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine(hinfo.WelcomeMsg);
                        Console.ForegroundColor = c;
                    }

                    if (txt.IsNotNullOrWhiteSpace() || file.IsNotNullOrWhiteSpace())
                    {
                        try
                        {
                            if (txt.IsNotNullOrWhiteSpace())
                            {
                                write(client.Execute(txt));
                            }
                            if (file.IsNotNullOrWhiteSpace())
                            {
                                write(client.Execute(file));
                            }
                        }
                        catch (RemoteException remoteError)
                        {
                            TerminalUtils.ShowRemoteException(remoteError);
                            Environment.ExitCode = -1;
                        }
                    }
                    else
                    {
                        while (true)
                        {
                            if (!silent)
                            {
                                var c = Console.ForegroundColor;
                                Console.ForegroundColor = ConsoleColor.White;
                                Console.Write("{0}@{1}@{2}>".Args(hinfo.TerminalName, hinfo.AppName, hinfo.Host));
                                Console.ForegroundColor = c;
                            }
                            var command = "";

                            while (true)
                            {
                                var ln = Console.ReadLine();
                                command += ln;
                                if (ln.EndsWith(";"))
                                {
                                    break;
                                }
                                if (!silent)
                                {
                                    var c = Console.ForegroundColor;
                                    Console.ForegroundColor = ConsoleColor.White;
                                    Console.Write(">");
                                    Console.ForegroundColor = c;
                                }
                            }

                            command = command.Remove(command.Length - 1, 1);

                            if (command == "exit")
                            {
                                break;
                            }

                            string response = null;

                            try
                            {
                                response = client.Execute(command);
                            }
                            catch (RemoteException remoteError)
                            {
                                TerminalUtils.ShowRemoteException(remoteError);
                                continue;
                            }
                            write(response);
                        }
                    }

                    var disconnectMessage = client.Disconnect();
                    if (!silent)
                    {
                        write(disconnectMessage);
                    }
                }
            }
        }//run
Esempio n. 22
0
        //We always make a new in-memory ephemeral session which gets collected right after this request
        protected override WaveSession MakeNewSessionInstance(WorkContext work)
        {
            //Always create new session
            var session = base.MakeNewSessionInstance(work);

            //try to inject session.DataContextName
            var dch = DataContextHeader;

            if (dch.IsNotNullOrWhiteSpace())
            {
                var dcn = work.Request.Headers[dch];
                if (dcn.IsNotNullOrWhiteSpace())
                {
                    dcn = dcn.Trim().TakeFirstChars(1024);//hard limit safeguard
                    session.DataContextName = dcn;
                }
            }

            string hdr = null;

            var altHdrName = AltAuthorizationHeader;

            if (altHdrName.IsNotNullOrWhiteSpace())
            {
                hdr = work.Request.Headers[altHdrName]?.TrimStart(' ');
            }

            if (hdr.IsNullOrWhiteSpace())
            {
                //real AUTHORIZATION header
                hdr = work.Request.Headers[WebConsts.HTTP_HDR_AUTHORIZATION]?.TrimStart(' ');
                if (hdr.IsNullOrWhiteSpace())
                {
                    var mockHdrName = DefaultImpersonationAuthorizationHeaderValue;
                    if (mockHdrName.IsNotNullOrEmpty())
                    {
                        hdr = mockHdrName;
                    }
                    else
                    {
                        return(session);//unauthorized
                    }
                }
            }

            User user;

            if (EnableSystemTokens && hdr.StartsWith(SYSTOKEN, StringComparison.OrdinalIgnoreCase))
            {
                var sysTokenContent = hdr.Substring(SYSTOKEN.Length).Trim();

                if (sysTokenContent.IsNullOrWhiteSpace() || // empty or null tokens treated as empty
                    !SysAuthToken.TryParse(sysTokenContent, out var sysToken))
                {
                    throw HTTPStatusException.BadRequest_400("Bad [Authorization] header systoken");
                }

                user = App.SecurityManager.Authenticate(sysToken);//authenticate the user using Systoken
            }
            else//credentials
            {
                Credentials credentials = null;

                try
                {
                    if (hdr.StartsWith(BASIC, StringComparison.OrdinalIgnoreCase))
                    {
                        var basic = hdr.Substring(BASIC.Length).Trim();
                        credentials = IDPasswordCredentials.FromBasicAuth(basic);
                    }
                    else if (hdr.StartsWith(BEARER, StringComparison.OrdinalIgnoreCase))
                    {
                        var pfxBasic = BearerBasicPrefix;
                        var bearer   = hdr.Substring(BEARER.Length).Trim();
                        if (pfxBasic.IsNotNullOrWhiteSpace() && bearer.IsNotNullOrWhiteSpace() && bearer.StartsWith(pfxBasic))
                        {
                            var basicContent = bearer.Substring(pfxBasic.Length).Trim();
                            credentials = IDPasswordCredentials.FromBasicAuth(basicContent);
                        }
                        else
                        {
                            credentials = new BearerCredentials(bearer);
                        }
                    }
                }
                catch { }

                if (credentials == null)
                {
                    throw HTTPStatusException.BadRequest_400("Bad [Authorization] header");
                }

                user = App.SecurityManager.Authenticate(credentials);//authenticate the user
            }

            session.User = user;//<===========================================================I
            work.SetAuthenticated(user.IsAuthenticated);

            //gate bad traffic
            var gate = NetGate;

            if (!user.IsAuthenticated && gate != null && gate.Enabled)
            {
                var vname = GateBadAuthVar;
                if (vname.IsNotNullOrWhiteSpace())
                {
                    gate.IncreaseVariable(IO.Net.Gate.TrafficDirection.Incoming,
                                          work.EffectiveCallerIPEndPoint.Address.ToString(),
                                          vname,
                                          1);
                }
            }

            return(session);
        }