Exemple #1
0
        public ActionResult Authenticator(OtpModel model)
        {
            ViewBag.IsOtpBySmsEnabled   = _configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.OtpNotificationMediumSms) == "True";
            ViewBag.IsOtpByEmailEnabled = _configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.OtpNotificationMediumEmail) == "True";
            ViewBag.IsOtpByAppEnabled   = _configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.OtpByGoogleAuthenticator) == "True";

            model.IsAllowSafeComputerEnabled = _configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.AllowSafeComputerRemember) == "True";
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var userId        = (long)Session["UserId"];
            var loginSettings = _loginSettingRepository.Get(userId);
            var isValid       = TimeBasedOneTimePassword.IsValid(loginSettings.GoogleAuthenticatorSecretKey, model.Otp, 50);

            if (!isValid)
            {
                model.IsOtpVerified   = false;
                model.FeedbackMessage = FeedbackMessageModel.CreateFailureMessage("The OTP entered is wrong. Please try again.");
                return(View(model));
            }
            if (model.MarkAsSafe)
            {
                var browserName  = Request.Browser.Browser + " " + Request.Browser.Version;
                var requestingIp = Request.UserHostAddress;
                var safeComputer = new SafeComputerHistory()
                {
                    BrowserType = browserName, ComputerIp = requestingIp, DateCreated = DateTime.Now, DateModified = DateTime.Now, IsActive = true, UserLoginId = userId
                };
                _safeComputerHistoryService.Save(safeComputer);
            }

            return(GoToDashboard(userId));
        }
Exemple #2
0
        //
        // POST: /Account/LogOn

        private void DoLogOn(LogOnModel model, string returnUrl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (Membership.ValidateUser(model.UserName, model.Password))
                    {
                        var profile = TwoFactorProfile.GetByUserName(model.UserName);

                        if (profile != null && !string.IsNullOrEmpty(profile.TwoFactorSecret))
                        {
                            // Prevent the user from attempting to brute force the two factor secret.
                            // Without this, an attacker, if they know your password already, could try to brute
                            // force the two factor code. They only need to try 1,000,000 distinct codes in 3 minutes.
                            // This throttles them down to a managable level.
                            if (profile.LastLoginAttemptUtc.HasValue && profile.LastLoginAttemptUtc > DateTime.UtcNow - TimeSpan.FromSeconds(1))
                            {
                                System.Threading.Thread.Sleep(5000);
                            }

                            profile.LastLoginAttemptUtc = DateTime.UtcNow;

                            if (TimeBasedOneTimePassword.IsValid(profile.TwoFactorSecret, model.TwoFactorCode))
                            {
                                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                                    !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                                {
                                    AsyncManager.Parameters["returnUrl"] = returnUrl;
                                }
                                else
                                {
                                    AsyncManager.Parameters["action"]     = "Index";
                                    AsyncManager.Parameters["controller"] = "Home";
                                }
                            }
                            else
                            {
                                ModelState.AddModelError("", "The two factor code is incorrect.");
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("", "The two factor code is incorrect.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    }
                }

                AsyncManager.Parameters["model"] = model;
            }
            finally
            {
                AsyncManager.OutstandingOperations.Decrement();
            }
        }
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    var profile = TwoFactorProfile.GetByUserName(model.UserName);

                    if (profile != null && !string.IsNullOrEmpty(profile.TwoFactorSecret))
                    {
                        if (TimeBasedOneTimePassword.IsValid(profile.TwoFactorSecret, model.TwoFactorCode))
                        {
                            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                                !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                            {
                                return(Redirect(returnUrl));
                            }
                            else
                            {
                                return(RedirectToAction("Index", "Home"));
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("", "The two factor code is incorrect.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "The two factor code is incorrect.");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        } // end LogOn
Exemple #4
0
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(HashedOneTimePassword.GeneratePassword("12345678901234567890", i));
            }

            long[] seconds = new long[] { 59, 1111111109, 1111111111, 1234567890, 2000000000, 20000000000 };

            foreach (var second in seconds)
            {
                Console.WriteLine(TimeBasedOneTimePassword.GetPassword("12345678901234567890", TimeBasedOneTimePassword.UNIX_EPOCH + TimeSpan.FromSeconds(second), TimeBasedOneTimePassword.UNIX_EPOCH, 30, 8));
            }

            Base32Encoder enc = new Base32Encoder();

            string secret = enc.Encode(Encoding.ASCII.GetBytes("1234567890"));

            Console.WriteLine(secret);

            Console.WriteLine("Enter your password: "******"1234567890", password))
            {
                Console.WriteLine("Success!");
            }
            else
            {
                Console.WriteLine("ERROR!");
            }

            return;

            while (true)
            {
                Console.WriteLine(TimeBasedOneTimePassword.GetPassword("1234567890"));
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
            }
        }
Exemple #5
0
        // <summary> Check if the username and password are the same as in the database </summery>
        public void Login()
        {
            // Run model through sql injection prevention
            var username      = SqlInjection.SafeSqlLiteral(StringManipulation.ToLowerFast(Username));
            var savedPassword = String.Empty;
            var savedSalt     = String.Empty;
            var savedId       = String.Empty;
            var code          = String.Empty;

            // MySql query
            const string result = "SELECT Id, Password, Salt, Owner, Secret, Tfa " +
                                  "FROM users " +
                                  "WHERE Username = ?";

            using (var empConnection = DatabaseConnection.DatabaseConnect())
            {
                using (var showResult = new MySqlCommand(result, empConnection))
                {
                    // Bind parameters
                    showResult.Parameters.Add("Username", MySqlDbType.VarChar).Value = username;

                    try
                    {
                        DatabaseConnection.DatabaseOpen(empConnection);
                        // Execute command
                        using (var myDataReader = showResult.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (myDataReader.Read())
                            {
                                savedId          = myDataReader.GetValue(0).ToString();
                                savedPassword    = myDataReader.GetString(1);
                                savedSalt        = myDataReader.GetString(2);
                                Owner            = Convert.ToInt16(myDataReader.GetValue(3));
                                code             = myDataReader.GetString(4);
                                TwoFactorEnabled = Convert.ToInt16(myDataReader.GetValue(5));
                            }
                        }

                        // Hash the password and check if the hash is the same as the saved password
                        if (Crypt.ValidatePassword(Password, savedPassword, savedSalt))
                        {
                            if (TwoFactorEnabled == 0 && PluginModel.PluginStatus("1"))
                            {
                                if (TimeBasedOneTimePassword.IsValid(code, TwoFactorCode))
                                {
                                    Cookies.MakeCookie(username, savedId, Owner.ToString(CultureInfo.InvariantCulture));
                                    Done = true;
                                }
                                else
                                {
                                    ErrorCode = true;
                                }
                            }
                            else
                            {
                                Cookies.MakeCookie(username, savedId, Owner.ToString(CultureInfo.InvariantCulture));
                                Done = true;
                            }
                        }
                    }
                    catch (MySqlException)
                    {
                        // MySqlException bail out
                        Error = true;
                    }
                    finally
                    {
                        // Always close the connection
                        DatabaseConnection.DatabaseClose(empConnection);
                    }
                }
            }
            Error = true;
        }