예제 #1
0
        /*
         * Deletes all specified access objects.
         */
        public static void DeleteAccess(ApplicationContext context, Node args)
        {
            // Locking access to password file as we create new access object.
            AuthFile.ModifyAuthFile(
                context,
                delegate(Node authFile) {
                // Verifying access rights exists.
                if (authFile ["access"] == null)
                {
                    return;
                }

                // Iterating all access objects passed in by caller.
                var access    = authFile ["access"];
                var delAccess = XUtil.Iterate <Node> (context, args).ToList();
                foreach (var idxAccess in delAccess)
                {
                    // Removing all matches by simply "untying" the access object matching currently iterated access object.
                    access.Children.First(ix => ix.Name == idxAccess.Name && ix.Get(context, "") == idxAccess.GetExValue(context, "")).UnTie();
                }
            });
        }
        /*
         * Retrieves a specific user from system
         */
        public static void GetUser(ApplicationContext context, Node args)
        {
            // Retrieving "auth" file in node format
            var authFile = AuthFile.GetAuthFile(context);

            // Iterating all users requested by caller
            foreach (var idxUsername in XUtil.Iterate <string> (context, args))
            {
                // Checking if user exist
                if (authFile ["users"] [idxUsername] == null)
                {
                    throw new LambdaException(
                              string.Format("User '{0}' does not exist", idxUsername),
                              args,
                              context);
                }

                // Adding user's node as return value, and each property of user, except [password]
                args.Add(idxUsername);
                args [idxUsername].AddRange(authFile ["users"] [idxUsername].Clone().Children.Where(ix => ix.Name != "password"));
            }
        }
        /*
         * Changes password of "root" account, but only if existing root account's password
         * is null. Used during setup of system
         */
        public static void SetRootPassword(ApplicationContext context, Node args)
        {
            // Retrieving password given.
            string password = args.GetExChildValue <string> ("password", context);

            // Retrieving password rules from web.config, if any.
            var pwdRulesNode = new Node(".p5.config.get", "p5.auth.password-rules");
            var pwdRule      = context.RaiseEvent(".p5.config.get", pwdRulesNode) [0]?.Get(context, "");

            if (!string.IsNullOrEmpty(pwdRule))
            {
                // Verifying that specified password obeys by rules from web.config.
                Regex regex = new Regex(pwdRule);
                if (!regex.IsMatch(password))
                {
                    // New password was not accepted, throwing an exception.
                    args.FindOrInsert("password").Value = "xxx";
                    throw new LambdaSecurityException("Password didn't obey by your configuration settings, which are as follows; " + pwdRule, args, context);
                }
            }

            // Creating root account.
            var rootAccountNode = new Node("", "root");

            rootAccountNode.Add("password", password);
            rootAccountNode.Add("role", "root");
            CreateUser(context, rootAccountNode);

            // Creating "guest account" section, which is needed for settings among other things.
            var guestAccountName = context.RaiseEvent(".p5.auth.get-default-context-username").Get <string> (context);

            AuthFile.ModifyAuthFile(
                context,
                delegate(Node authFile) {
                authFile ["users"].Add(guestAccountName);
                authFile ["users"] ["guest"].Add("role", context.RaiseEvent(".p5.auth.get-default-context-role").Get <string> (context));
            });
        }
        /*
         * Retrieves settings for currently logged in user
         */
        public static void GetSettings(ApplicationContext context, Node args)
        {
            // Retrieving "auth" file in node format
            var authFile = AuthFile.GetAuthFile(context);

            // Checking if user exist
            if (authFile ["users"] [context.Ticket.Username] == null)
            {
                throw new LambdaException(
                          "You do not exist",
                          args,
                          context);
            }

            // Checking if caller is retieving a single section.
            var section = args.GetExValue(context, "");

            if (string.IsNullOrEmpty(section))
            {
                // All settings invocation.
                args.AddRange(authFile ["users"] [context.Ticket.Username].Clone().Children.Where(ix => ix.Name != "password" && ix.Name != "role"));
            }
            else if (section != "password" && section != "role")
            {
                // Single section invocation.
                var sectionNode = authFile ["users"] [context.Ticket.Username] [section]?.Clone();
                if (sectionNode != null)
                {
                    args.Add(sectionNode);
                }
            }
            else
            {
                // Illegal attempt at trying to retrieve role or password.
                throw new LambdaSecurityException("Illegal invocation, you can't retrieve [password] or [role]", args, context);
            }
        }
예제 #5
0
        /*
         * Changes the password for currently logged in user
         */
        public static void ChangePassword(ApplicationContext context, Node args)
        {
            string password = args.GetExValue(context, "");

            if (string.IsNullOrEmpty(password))
            {
                throw new LambdaException("No password supplied", args, context);
            }

            string username = context.Ticket.Username;

            // Locking access to password file as we edit user object
            AuthFile.ModifyAuthFile(
                context,
                delegate(Node authFile) {
                // Changing user's password
                // Creating user salt, and retrieving system salt
                var serverSalt = context.Raise(".p5.auth.get-server-salt").Get <string> (context);

                // Then salting password with user salt and system, before salting it with system salt
                var userPasswordFingerprint = context.Raise("p5.crypto.hash.create-sha256", new Node("", serverSalt + password)).Get <string> (context);
                authFile ["users"][username]["password"].Value = userPasswordFingerprint;
            });
        }
예제 #6
0
        /*
         * Tries to login user according to given user credentials
         */
        public static void Login(ApplicationContext context, Node args)
        {
            // Defaulting result of Active Event to unsuccessful
            args.Value = false;

            // Retrieving supplied credentials
            string username = args.GetExChildValue <string> ("username", context);
            string password = args.GetExChildValue <string> ("password", context);
            bool   persist  = args.GetExChildValue("persist", context, false);

            // Getting password file in Node format, but locking file access as we retrieve it
            Node pwdFile = AuthFile.GetAuthFile(context);

            // Checking for match on specified username
            Node userNode = pwdFile["users"][username];

            if (userNode == null)
            {
                throw new LambdaSecurityException("Credentials not accepted", args, context);
            }

            // Getting system salt
            var serverSalt = context.Raise(".p5.auth.get-server-salt").Get <string> (context);

            // Then creating system fingerprint from given password
            var cookiePasswordFingerprint = context.Raise("p5.crypto.hash.create-sha256", new Node("", serverSalt + password)).Get <string> (context);

            // Checking for match on password
            if (userNode["password"].Get <string> (context) != cookiePasswordFingerprint)
            {
                throw new LambdaSecurityException("Credentials not accepted", args, context);  // Exact same wording as above! IMPORTANT!!
            }
            // Success, creating our ticket
            string role = userNode["role"].Get <string>(context);

            SetTicket(new ApplicationContext.ContextTicket(username, role, false));
            args.Value = true;

            // Removing last login attempt, to reset brute force login cool off seconds for user's IP address
            LastLoginAttemptForIP = DateTime.MinValue;

            // Associating newly created Ticket with Application Context, since user now possibly have extended rights
            context.UpdateTicket(GetTicket(context));

            // Checking if we should create persistent cookie on disc to remember username for given client
            if (persist)
            {
                // Caller wants to create persistent cookie to remember username/password
                HttpCookie cookie = new HttpCookie(_credentialCookieName);
                cookie.Expires = DateTime.Now.AddDays(context.Raise(
                                                          ".p5.config.get",
                                                          new Node(".p5.config.get", "p5.auth.credential-cookie-valid")) [0].Get <int> (context));
                cookie.HttpOnly = true; // To avoid JavaScript access to credential cookie

                // Notice, we use another fingerprint as password for cookie than what we use for storing cookie in auth file
                // The "system salted fingerprint" hence never leaves the server
                // If this was not the case, then the system fingerprint would effectively BE the password, allowing anyone
                // who somehow gets access to "auth" file also to log in by creating false cookies
                cookie.Value = username + " " + cookiePasswordFingerprint;
                HttpContext.Current.Response.Cookies.Add(cookie);
            }

            // Making sure we invoke an [.onlogin] lambda callbacks for user.
            var onLogin = new Node();

            GetSettings(context, onLogin);
            if (onLogin [".onlogin"] != null)
            {
                var lambda = onLogin[".onlogin"].Clone();
                context.Raise("eval", lambda);
            }
        }
예제 #7
0
        /*
         * Creates a new user
         */
        public static void CreateUser(ApplicationContext context, Node args)
        {
            string username = args.GetExValue <string>(context);
            string password = args.GetExChildValue <string>("password", context);
            string role     = args.GetExChildValue <string>("role", context);

            // Making sure [password] never leaves method, in case of exceptions
            args.FindOrInsert("password").Value = "xxx";

            // Basic syntax checking
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(role))
            {
                throw new LambdaException(
                          "User must have [username], [password] and [role] at the very least",
                          args,
                          context);
            }

            // Verifying username is valid, since we'll need to create a folder for user
            VerifyUsernameValid(username);

            // Creating user salt, and retrieving system salt
            var serverSalt = context.Raise(".p5.auth.get-server-salt").Get <string> (context);

            // Then salting password with user salt, before salting it with system salt
            var userPasswordFingerprint = context.Raise("p5.crypto.hash.create-sha256", new Node("", serverSalt + password)).Get <string> (context);

            // Locking access to password file as we create new user object
            AuthFile.ModifyAuthFile(
                context,
                delegate(Node authFile) {
                // Checking if user exist from before
                if (authFile["users"][username] != null)
                {
                    throw new LambdaException(
                        "Sorry, that [username] is already taken by another user in the system",
                        args,
                        context);
                }

                // Adding user
                authFile["users"].Add(username);

                // Creates a salt and password for user
                authFile ["users"].LastChild.Add("password", userPasswordFingerprint);

                // Adding user to specified role
                authFile ["users"].LastChild.Add("role", role);

                // Adding all other specified objects to user
                foreach (var idxNode in args.Children.Where(ix => ix.Name != "username" && ix.Name != "password" && ix.Name != "role"))
                {
                    // Only adding nodes with some sort of actual value
                    if (idxNode.Value != null || idxNode.Children.Count > 0)
                    {
                        authFile["users"].LastChild.Add(idxNode.Clone());
                    }
                }
            });

            // Creating newly created user's directory structure
            CreateUserDirectory(context.Raise(".p5.core.application-folder").Get <string>(context), username);
        }
예제 #8
0
 /*
  * Returns true if root account exists, which implies that server has been setup.
  */
 public static bool HasRootAccount(ApplicationContext context)
 {
     // Retrieving password file, and returning true if root user exists.
     return(AuthFile.GetAuthFile(context) ["users"] ["root"] != null);
 }
        /*
         * Tries to login user according to given user credentials
         */
        public static void Login(ApplicationContext context, Node args)
        {
            // Defaulting result of Active Event to unsuccessful.
            args.Value = false;

            // Retrieving supplied credentials
            string username = args.GetExChildValue <string> ("username", context);
            string password = args.GetExChildValue <string> ("password", context);

            args.FindOrInsert("password").Value = "xxx";  // In case an exception occurs.
            bool persist = args.GetExChildValue("persist", context, false);

            /*
             * Checking if current username has attempted to login just recently, and the
             * configured timespan for each successive login attempt per user, has not passed.
             *
             * This should be able to defend us from a "brute force password attack".
             */
            var bruteConf = new Node(".p5.config.get", ".p5.auth.cooldown-period");
            var cooldown  = context.RaiseEvent(".p5.config.get", bruteConf) [0]?.Get(context, -1) ?? -1;

            if (cooldown != -1)
            {
                // User has configured the system to have a "cooldown period" for successive login attempts.
                var bruteForceLastAttempt = new Node(".p5.web.application.get", ".p5.io.last-login-attempt-for-" + username);
                var lastAttemptNode       = context.RaiseEvent(".p5.web.application.get", bruteForceLastAttempt);
                if (lastAttemptNode.Count > 0)
                {
                    // Previous attempt has been attempted.
                    var date            = lastAttemptNode [0].Get <DateTime> (context, DateTime.MinValue);
                    int timeSpanSeconds = System.Convert.ToInt32((DateTime.Now - date).TotalSeconds);
                    if (timeSpanSeconds < cooldown)
                    {
                        throw new LambdaException("You need to wait " + (cooldown - timeSpanSeconds) + " seconds before you can try again", args, context);
                    }
                }
            }

            // Getting password file in Node format, but locking file access as we retrieve it
            Node pwdFile = AuthFile.GetAuthFile(context);

            // Checking for match on specified username
            Node userNode = pwdFile ["users"] [username];

            if (userNode == null)
            {
                throw new LambdaSecurityException("Credentials not accepted", args, context);
            }

            // Getting system salt
            var serverSalt = context.RaiseEvent(".p5.auth.get-server-salt").Get <string> (context);

            // Then creating system fingerprint from given password
            var hashedPassword = context.RaiseEvent("p5.crypto.hash.create-sha256", new Node("", serverSalt + password)).Get <string> (context);

            // Checking for match on password
            if (userNode ["password"].Get <string> (context) != hashedPassword)
            {
                // Making sure we guard against brute force password attacks.
                var bruteForceLastAttempt = new Node(".p5.web.application.set", ".p5.io.last-login-attempt-for-" + username);
                bruteForceLastAttempt.Add("src", DateTime.Now);
                context.RaiseEvent(".p5.web.application.set", bruteForceLastAttempt);
                throw new LambdaSecurityException("Credentials not accepted", args, context);
            }

            // Success, creating our ticket
            string role = userNode ["role"].Get <string> (context);

            SetTicket(new ContextTicket(username, role, false));
            args.Value = true;

            // Removing last login attempt, to reset brute force login cool off seconds for user's IP address
            LastLoginAttemptForIP = DateTime.MinValue;

            // Associating newly created Ticket with Application Context, since user now possibly have extended rights
            context.UpdateTicket(GetTicket(context));

            // Checking if we should create persistent cookie on disc to remember username for given client
            if (persist)
            {
                // Caller wants to create persistent cookie to remember username/password
                var cookie = new HttpCookie(_credentialCookieName);
                cookie.Expires = DateTime.Now.AddDays(context.RaiseEvent(
                                                          ".p5.config.get",
                                                          new Node(".p5.config.get", "p5.auth.credential-cookie-valid")) [0].Get <int> (context));
                cookie.HttpOnly = true; // To avoid JavaScript access to credential cookie

                // Notice, we use another fingerprint as password for cookie than what we use for storing cookie in auth file
                // The "system salted fingerprint" hence never leaves the server
                // If this was not the case, then the system fingerprint would effectively BE the password, allowing anyone
                // who somehow gets access to "auth" file also to log in by creating false cookies
                cookie.Value = username + " " + hashedPassword;
                HttpContext.Current.Response.Cookies.Add(cookie);
            }

            // Making sure we invoke an [.onlogin] lambda callbacks for user.
            var onLogin = new Node();

            GetSettings(context, onLogin);
            if (onLogin [".onlogin"] != null)
            {
                var lambda = onLogin [".onlogin"].Clone();
                context.RaiseEvent("eval", lambda);
            }
        }
예제 #10
0
        /*
         * Creates a new user.
         */
        public static void CreateUser(ApplicationContext context, Node args)
        {
            // Retrieving arguments.
            var username = args.GetExValue <string> (context);
            var password = args.GetExChildValue <string> ("password", context);
            var role     = args.GetExChildValue <string> ("role", context);

            // Sanity checking role name towards guest account name.
            if (role == context.RaiseEvent(".p5.auth.get-default-context-role").Get <string> (context))
            {
                throw new LambdaException("Sorry, but that's the name of our guest account role.", args, context);
            }

            // Sanity checking username towards guest account name.
            if (username == context.RaiseEvent(".p5.auth.get-default-context-username").Get <string> (context))
            {
                throw new LambdaException("Sorry, but that's the name of our guest account.", args, context);
            }

            // Making sure [password] never leaves method in case of an exception.
            args.FindOrInsert("password").Value = "xxx";

            // Retrieving password rules from web.config, if any.
            if (!Passwords.IsGoodPassword(context, password))
            {
                // New password was not accepted, throwing an exception.
                throw new LambdaSecurityException(
                          "Password didn't obey by your configuration settings, which are as follows; " +
                          Passwords.PasswordRuleDescription(context),
                          args,
                          context);
            }

            // Basic sanity check new user's data.
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(role))
            {
                throw new LambdaException(
                          "User must have username as value, [password] and [role] at the very least",
                          args,
                          context);
            }

            // Verifying username is valid, since we'll need to create a folder for user.
            VerifyUsernameValid(username);

            // To reduce lock time of "auth" file, we execute Blow Fish hashing before we enter lock.
            password = Passwords.SaltAndHashPassword(context, password);

            // Locking access to password file as we create new user object.
            AuthFile.ModifyAuthFile(
                context,
                delegate(Node authFile) {
                // Checking if user exist from before.
                if (authFile ["users"] [username] != null)
                {
                    throw new LambdaException(
                        "Sorry, that [username] is already taken by another user in the system",
                        args,
                        context);
                }

                // Adding user.
                var userNode = authFile ["users"].Add(username).LastChild;

                // Salting and hashing password, before storing it in "auth" file.
                userNode.Add("password", password);

                // Adding user to specified role.
                userNode.Add("role", role);

                // Adding all other specified objects to user.
                userNode.AddRange(args.Children.Where(ix => ix.Name != "password" && ix.Name != "role").Select(ix => ix.Clone()));
            });

            // Creating newly created user's directory structure.
            CreateUserDirectory(context, username);
        }
        /*
         * Edits an existing user
         */
        public static void EditUser(ApplicationContext context, Node args)
        {
            // Retrieving username, and sanity checking invocation.
            string username = args.GetExValue <string> (context);

            if (args ["username"] != null)
            {
                throw new LambdaSecurityException("Cannot change username for user", args, context);
            }

            // Retrieving new password and role, defaulting to null, which will not update existing values.
            string newPassword = args.GetExChildValue <string> ("password", context);
            string newRole     = args.GetExChildValue <string> ("role", context);

            // Sanity checking role name towards guest account name.
            if (newRole == context.RaiseEvent(".p5.auth.get-default-context-role").Get <string> (context))
            {
                throw new LambdaException("Sorry, but that's the name of our guest account role.", args, context);
            }

            // Retrieving password rules from web.config, if any.
            // But only if a new password was given.
            if (!string.IsNullOrEmpty(newPassword))
            {
                // Verifying password conforms to password rules.
                var pwdRulesNode = new Node(".p5.config.get", "p5.auth.password-rules");
                var pwdRule      = context.RaiseEvent(".p5.config.get", pwdRulesNode) [0]?.Get(context, "");
                if (!string.IsNullOrEmpty(pwdRule))
                {
                    // Verifying that specified password obeys by rules from web.config.
                    Regex regex = new Regex(pwdRule);
                    if (!regex.IsMatch(newPassword))
                    {
                        // New password was not accepted, throwing an exception.
                        args.FindOrInsert("password").Value = "xxx";
                        throw new LambdaSecurityException("Password didn't obey by your configuration settings, which are as follows; " + pwdRule, args, context);
                    }
                }
            }

            // Retrieving system salt before we enter write lock. (important, since otherwise we'd have a deadlock condition here).
            var serverSalt = newPassword == null ? null : context.RaiseEvent(".p5.auth.get-server-salt").Get <string> (context);

            // Locking access to password file as we edit user object.
            AuthFile.ModifyAuthFile(
                context,
                delegate(Node authFile) {
                // Checking to see if user exist.
                if (authFile ["users"] [username] == null)
                {
                    throw new LambdaException(
                        "Sorry, that user does not exist",
                        args,
                        context);
                }

                // Updating user's password, but only if a new password was supplied by caller.
                if (!string.IsNullOrEmpty(newPassword))
                {
                    // Making sure we salt password with system salt, before we create our SHA256 value, which is what we actually store in our "auth" file.
                    var userPasswordFingerprint = context.RaiseEvent("p5.crypto.hash.create-sha256", new Node("", serverSalt + newPassword)).Get <string> (context);
                    authFile ["users"] [username] ["password"].Value = userPasswordFingerprint;
                }

                // Updating user's role, if a new role was supplied by caller.
                if (newRole != null)
                {
                    authFile ["users"] [username] ["role"].Value = newRole;
                }

                // Checking if caller wants to edit settings.
                if (args.Name == "p5.auth.users.edit")
                {
                    // Removing old settings.
                    authFile ["users"] [username].RemoveAll(ix => ix.Name != "password" && ix.Name != "role");

                    // Adding all other specified objects to user.
                    foreach (var idxNode in args.Children.Where(ix => ix.Name != "password" && ix.Name != "role"))
                    {
                        authFile ["users"] [username].Add(idxNode.Clone());
                    }
                }
            });
        }
        /*
         * Creates a new user
         */
        public static void CreateUser(ApplicationContext context, Node args)
        {
            // Retrieving arguments.
            string username = args.GetExValue <string> (context);
            string password = args.GetExChildValue <string> ("password", context);
            string role     = args.GetExChildValue <string> ("role", context);

            // Sanity checking role name towards guest account name.
            if (role == context.RaiseEvent(".p5.auth.get-default-context-role").Get <string> (context))
            {
                throw new LambdaException("Sorry, but that's the name of our guest account role.", args, context);
            }

            // Sanity checking username towards guest account name.
            if (username == context.RaiseEvent(".p5.auth.get-default-context-username").Get <string> (context))
            {
                throw new LambdaException("Sorry, but that's the name of our guest account.", args, context);
            }

            // Making sure [password] never leaves method.
            args.FindOrInsert("password").Value = "xxx";

            // Retrieving password rules from web.config, if any.
            var pwdRulesNode = new Node(".p5.config.get", "p5.auth.password-rules");
            var pwdRule      = context.RaiseEvent(".p5.config.get", pwdRulesNode) [0]?.Get(context, "");

            if (!string.IsNullOrEmpty(pwdRule))
            {
                // Verifying that specified password obeys by rules from web.config.
                Regex regex = new Regex(pwdRule);
                if (!regex.IsMatch(password))
                {
                    // New password was not accepted, throwing an exception.
                    args.FindOrInsert("password").Value = "xxx";
                    throw new LambdaSecurityException("Password didn't obey by your configuration settings, which are as follows; " + pwdRule, args, context);
                }
            }

            // Basic sanity check.
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(role))
            {
                throw new LambdaException(
                          "User must have username as value, [password] and [role] at the very least",
                          args,
                          context);
            }

            // Verifying username is valid, since we'll need to create a folder for user.
            VerifyUsernameValid(username);

            // Retrieving system salt before we enter write lock.
            var serverSalt = context.RaiseEvent(".p5.auth.get-server-salt").Get <string> (context);

            // Then salting user's password.
            var userPasswordFingerprint = context.RaiseEvent("p5.crypto.hash.create-sha256", new Node("", serverSalt + password)).Get <string> (context);

            // Locking access to password file as we create new user object.
            AuthFile.ModifyAuthFile(
                context,
                delegate(Node authFile) {
                // Checking if user exist from before.
                if (authFile ["users"] [username] != null)
                {
                    throw new LambdaException(
                        "Sorry, that [username] is already taken by another user in the system",
                        args,
                        context);
                }

                // Adding user.
                authFile ["users"].Add(username);

                // Creates a salt and password for user.
                authFile ["users"].LastChild.Add("password", userPasswordFingerprint);

                // Adding user to specified role.
                authFile ["users"].LastChild.Add("role", role);

                // Adding all other specified objects to user.
                foreach (var idxNode in args.Children.Where(ix => ix.Name != "username" && ix.Name != "password" && ix.Name != "role"))
                {
                    // Only adding nodes with some sort of actual value.
                    if (idxNode.Value != null || idxNode.Count > 0)
                    {
                        authFile ["users"].LastChild.Add(idxNode.Clone());
                    }
                }
            });

            // Creating newly created user's directory structure.
            CreateUserDirectory(context.RaiseEvent(".p5.core.application-folder").Get <string> (context), username);
        }
예제 #13
0
        /*
         * Returns all access objects for system.
         */
        public static void ListAccess(ApplicationContext context, Node args)
        {
            // Getting password file in Node format.
            Node pwdFile = AuthFile.GetAuthFile(context);

            // Checking if caller wants to remove GUID IDs of access objects in the system.
            var keepGuids = args.GetExChildValue("guids", context, false);

            // Checking if we have any access rights in system.
            if (pwdFile ["access"] == null)
            {
                return;
            }

            // Checking which role caller requests access objects on behalf.
            string roles = null;

            if (context.Ticket.Role == "root")
            {
                // Checking if caller requested a particular role.
                roles = args.GetExChildValue <string> ("role", context, null);
            }
            else
            {
                // A non-root user is not allowed to request anything besides his own access objects.
                if (args ["role"] != null)
                {
                    throw new LambdaException("A non-root user cannot request access objects for anything but his own role", args, context);
                }

                // Making sure user only retrieves access objects that are relevant for his own role.
                roles = context.Ticket.Role;
            }

            // Looping through each user object in password file, retrieving all roles.
            foreach (var idxAccessNode in pwdFile["access"].Children)
            {
                // Checking what types of access object(s) are relevant to caller.
                if (roles == null)
                {
                    // Cloning access object node.
                    var cur = idxAccessNode.Clone();

                    // Removing GUID IDs if caller specified we should do so.
                    Guid guid;
                    if (!keepGuids && Guid.TryParse(idxAccessNode.Get <string> (context), out guid))
                    {
                        cur.Value = null;
                    }

                    // Caller wants everything.
                    args.Add(cur);
                }
                else
                {
                    // Checking if currently iterated access object is relevant to caller.
                    if (idxAccessNode.Name == "*" || idxAccessNode.Name == roles)
                    {
                        // Cloning access object node.
                        var cur = idxAccessNode.Clone();

                        // Removing GUID IDs if caller specified we should do so.
                        Guid guid;
                        if (!keepGuids && Guid.TryParse(idxAccessNode.Get <string> (context), out guid))
                        {
                            cur.Value = null;
                        }

                        // Adding currently iterated access object.
                        args.Add(cur);
                    }
                }
            }
        }
예제 #14
0
 /*
  * Returns PGP key's fingerprint.
  */
 public static string GetFingerprint(ApplicationContext context)
 {
     // Retrieving "auth" file in node format, for then to return fingerprint back to caller.
     return(AuthFile.GetAuthFile(context).GetChildValue <string> (GnuPgpFingerprintNodeName, context));
 }
예제 #15
0
        /*
         * Tries to login user according to given user credentials.
         */
        public static void Login(ApplicationContext context, Node args)
        {
            // Defaulting result of Active Event to unsuccessful.
            args.Value = false;

            // Retrieving supplied credentials.
            var username = args.GetExChildValue <string> ("username", context);
            var password = args.GetExChildValue <string> ("password", context);

            args.FindOrInsert("password").Value = "xxx";  // In case an exception occurs.
            var persist = args.GetExChildValue("persist", context, false);

            // Retrieving password file as a Node.
            var pwdFile = AuthFile.GetAuthFile(context);

            /*
             * Checking for match on specified username.
             */
            var userNode = pwdFile ["users"] [username];

            if (userNode == null)
            {
                // Username doesn't exist.
                throw new LambdaSecurityException(_credentialsNotAcceptedException, args, context);
            }

            /*
             * Checking if current username has attempted to login just recently, and the
             * configured timespan for each successive login attempt per user, has not passed.
             *
             * This should be able to provide some rudimentary defense from a "brute force password attack".
             *
             * Notice, we do this after we have checked if the username exists, to avoid having an adversary
             * flood the server's cache with bogus usernames associated with DateTime objects.
             * We also us the web cache, which (of course) means the object will only exists for some
             * time, defaulting to the settings of the web cache for your system.
             */
            var cooldown = context.RaiseEvent(
                ".p5.config.get",
                new Node(".p5.config.get", _cooldownPeriodConfigName)) [0]?.Get(context, -1) ?? -1;

            if (cooldown != -1)
            {
                // User has configured the system to have a "cooldown period" for successive login attempts.
                var bruteForceLastAttempt = new Node(".p5.web.cache.get", _bruteForceCacheName + username);
                var lastAttemptNode       = context.RaiseEvent(".p5.web.cache.get", bruteForceLastAttempt);
                if (lastAttemptNode.Count > 0)
                {
                    // Previous attempt has been attempted recently.
                    var date            = lastAttemptNode [0].Get <DateTime> (context, DateTime.MinValue);
                    var timeSpanSeconds = Convert.ToInt32((DateTime.Now - date).TotalSeconds);
                    if (timeSpanSeconds < cooldown)
                    {
                        // Cooldown period has not passed.
                        throw new LambdaException("You need to wait " + (cooldown - timeSpanSeconds) + " seconds before you can try again", args, context);
                    }
                }
            }

            // Checking for match on password.
            if (!Passwords.VerifyPasswordIsCorrect(password, userNode ["password"].Get <string> (context)))
            {
                /*
                 * Making sure we guard against brute force password attacks, before we throw security exception.
                 *
                 * Notice, this prevents the same username from attempting to login more than once every n seconds,
                 * which is configurable in the config file of the app.
                 */
                var bruteForceLastAttempt = new Node(".p5.web.cache.set", _bruteForceCacheName + username);
                bruteForceLastAttempt.Add("src", DateTime.Now);
                context.RaiseEvent(".p5.web.cache.set", bruteForceLastAttempt);
                throw new LambdaSecurityException(_credentialsNotAcceptedException, args, context);
            }

            // Success, creating our context ticket.
            var role = userNode ["role"].Get <string> (context);

            SetTicket(context, new ContextTicket(username, role, false));

            // Signaling success to caller.
            args.Value = true;

            // Checking if we should create persistent cookie on disc to remember username/password for given client.
            if (persist)
            {
                // Caller wants to create persistent cookie to remember username/password.
                var cookie = new HttpCookie(_credentialCookieName);
                cookie.Expires = DateTime.Now.AddDays(context.RaiseEvent(
                                                          ".p5.config.get",
                                                          new Node(".p5.config.get", "p5.auth.credential-cookie-valid")) [0].Get <int> (context));

                // To avoid JavaScript access to credential cookie.
                cookie.HttpOnly = true;

                /*
                 * The value of our cookie is in "username hashed-password" format.
                 *
                 * This is an entropy of roughly 1.1579e+77, making a brute force attack
                 * impossible, at least without a Rainbow/Dictionary attack, which should
                 * be effectively prevented, by having a single static server salt,
                 * which again is cryptographically secured and persisted to disc
                 * in the "auth" file, and hence normally inaccessible for an adversary.
                 *
                 * Notice, we double hash the password we store in our cookie, to make
                 * sure we never expose the parts of our password we store in our "auth" file.
                 */
                cookie.Value = username + " " + Passwords.HashPasswordForCookieStorage(
                    context,
                    userNode ["password"].Get <string> (context));
                HttpContext.Current.Response.Cookies.Add(cookie);
            }

            // Evaluates user's [.onlogin] section, if it exists.
            EvaluateOnLoginIfExisting(context);
        }
예제 #16
0
 /*
  * Returns server-salt for application.
  */
 public static string GetServerSalt(ApplicationContext context)
 {
     // Retrieving "auth" file in node format.
     return(AuthFile.GetAuthFile(context).GetChildValue <string> ("server-salt", context));
 }
예제 #17
0
        /*
         * Edits an existing user.
         */
        public static void EditUser(ApplicationContext context, Node args)
        {
            // Retrieving username, and sanity checking invocation.
            var username = args.GetExValue <string> (context);

            if (args ["username"] != null)
            {
                throw new LambdaSecurityException("Cannot change username for user", args, context);
            }

            // Retrieving new password and role, defaulting to null, which will not update existing values.
            var password = args.GetExChildValue <string> ("password", context, null);
            var role     = args.GetExChildValue <string> ("role", context, null);

            // Sanity checking role name towards guest account name.
            if (role == context.RaiseEvent(".p5.auth.get-default-context-role").Get <string> (context))
            {
                throw new LambdaException("Sorry, but that's the name of your system's guest account role.", args, context);
            }

            // Changing user's password, but only if a [password] argument was explicitly supplied by caller.
            if (!string.IsNullOrEmpty(password))
            {
                // Verifying password conforms to password rules.
                if (!Passwords.IsGoodPassword(context, password))
                {
                    // New password was not accepted, throwing an exception.
                    args.FindOrInsert("password").Value = "xxx";
                    var description = Passwords.PasswordRuleDescription(context);
                    throw new LambdaSecurityException("Password didn't obey by your configuration settings, which are as follows; " + description, args, context);
                }
            }

            // To reduce lock time of "auth" file we execute Blow Fish hashing before we enter lock.
            password = password == null ? null : Passwords.SaltAndHashPassword(context, password);

            // Locking access to password file as we edit user object.
            AuthFile.ModifyAuthFile(
                context,
                delegate(Node authFile) {
                // Checking to see if user exist.
                if (authFile ["users"] [username] == null)
                {
                    throw new LambdaException(
                        "Sorry, that user does not exist",
                        args,
                        context);
                }

                // Updating user's password, but only if a new password was supplied by caller.
                if (!string.IsNullOrEmpty(password))
                {
                    authFile ["users"] [username] ["password"].Value = password;
                }

                // Updating user's role, if a new role was supplied by caller.
                if (role != null)
                {
                    authFile ["users"] [username] ["role"].Value = role;
                }

                // Checking if caller wants to edit settings.
                if (args.Name == "p5.auth.users.edit")
                {
                    // Removing old settings.
                    authFile ["users"] [username].RemoveAll(ix => ix.Name != "password" && ix.Name != "role" && ix.Name != "salt");

                    // Adding all other specified objects to user.
                    foreach (var idxNode in args.Children.Where(ix => ix.Name != "password" && ix.Name != "role" && ix.Name != "salt"))
                    {
                        authFile ["users"] [username].Add(idxNode.Clone());
                    }
                }
            });
        }