예제 #1
0
        public ActionResult Edit(long id, Roles roleId)
        {
            var currentSession = _sessionContext.UserSession.CurrentOrganizationRole;

            if (currentSession.UserId == id && currentSession.RoleId == (long)roleId)
            {
                var profileEditModel = _userProfileService.GetProfileEditModel(id);
                if (string.IsNullOrEmpty(profileEditModel.Secret))
                {
                    string secret = "", enc = "";
                    secret = TimeBasedOneTimePassword.GenerateSecret(out enc);
                    TempData["EncodedSecret"]      = secret;
                    profileEditModel.EncodedSecret = enc;
                }
                else
                {
                    TempData["EncodedSecret"]      = profileEditModel.Secret;
                    profileEditModel.EncodedSecret = TimeBasedOneTimePassword.EncodeSecret(profileEditModel.Secret);
                }

                if (roleId == Roles.Technician)
                {
                    var technicianProfile = _technicianRepository.GetTechnician(currentSession.OrganizationRoleUserId);
                    profileEditModel.TechnicianPin = technicianProfile != null ? technicianProfile.Pin : "0000";
                }

                return(View(profileEditModel));
            }
            Response.RedirectUser("/Home/UnauthorizeAccess");
            return(null);
        }
예제 #2
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));
        }
예제 #3
0
        private void Test(string sharedSecret, long seconds, string expected)
        {
            var calculated = TimeBasedOneTimePassword.GetPassword(sharedSecret, TimeBasedOneTimePassword.UNIX_EPOCH + TimeSpan.FromSeconds(seconds), TimeBasedOneTimePassword.UNIX_EPOCH, 30, 8);

            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(expected, calculated);
            NUnit.Framework.Assert.AreEqual(expected, calculated);
        }
예제 #4
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 void Generate_DefaultsToHmacSha1Algorithm()
        {
            byte[]   secretKey = new byte[] { 0 };
            DateTime dt        = DateTime.Now;
            string   result1   = TimeBasedOneTimePassword.Generate(secretKey, new HMACSHA1());
            string   result2   = TimeBasedOneTimePassword.Generate(secretKey);

            Assert.AreEqual(result1, result2);
        }
예제 #6
0
        public ActionResult Setup()
        {
            //to do : if user pastes the url then move him to dashboard based on condition if the entry is present in the database
            if (_sessionContext.UserSession == null)
            {
                return(RedirectToAction("Index"));
            }
            var IsOnGlobalSettingChange = false;
            var loginSettings           = _loginSettingRepository.Get(_sessionContext.UserSession.UserId);

            if (TempData["IsOnGlobalSettingChange"] != null)
            {
                IsOnGlobalSettingChange = (bool)TempData["IsOnGlobalSettingChange"];
            }

            var setPinOnly = TempData["setPinOnly"];

            if (loginSettings != null && loginSettings.IsFirstLogin == false && IsOnGlobalSettingChange == false && (setPinOnly == null || (bool)setPinOnly == false))
            {
                Response.RedirectUser("/Users/Role/Switch?roleId=" + _sessionContext.UserSession.CurrentOrganizationRole.RoleId + "&organizationId=" + _sessionContext.UserSession.CurrentOrganizationRole.OrganizationId);
                return(null);
            }


            var isTwoFactorAuthrequired = (bool)TempData["IsTwoFactorAuthrequired"];

            string secret = "", enc = "";

            secret = TimeBasedOneTimePassword.GenerateSecret(out enc);
            TempData["EncodedSecret"] = secret;

            var role  = _roleRepository.GetByRoleId(_sessionContext.UserSession.CurrentOrganizationRole.RoleId);
            var model = new SetupViewModel()
            {
                EncodedSecret = enc,
                IsPinRequired = role.IsPinRequired,
                UserLoginId   = _sessionContext.UserSession.CurrentOrganizationRole.UserId
            };

            if (isTwoFactorAuthrequired)
            {
                model.IsOtpBySmsEnabled   = _configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.OtpNotificationMediumSms) == "True";
                model.IsOtpByEmailEnabled = _configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.OtpNotificationMediumEmail) == "True";
                model.IsOtpByAppEnabled   = _configurationSettingRepository.GetConfigurationValue(ConfigurationSettingName.OtpByGoogleAuthenticator) == "True";
            }
            if (setPinOnly != null && (bool)setPinOnly)
            {
                model.IsOtpBySmsEnabled   = false;
                model.IsOtpByEmailEnabled = false;
                model.IsOtpByAppEnabled   = false;
            }
            TempData.Keep("setPinOnly");
            TempData.Keep("IsTwoFactorAuthrequired");
            TempData.Keep("IsOnGlobalSettingChange");
            return(View(model));
        }
예제 #7
0
        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
예제 #8
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));
            }
        }
        public void Generate_YieldsExpectedResults()
        {
            //Values taken from RFC specification

            byte[] secret = Encoding.ASCII.GetBytes("12345678901234567890");

            //Item1 is the datetime to generate password for
            //Item2 is the expected result
            //item3 is the hmac algorithm to use.
            List <Tuple <DateTime, string, HMAC> > testValues = new List <Tuple <DateTime, string, HMAC> >()
            {
                new Tuple <DateTime, string, HMAC>(new DateTime(1970, 1, 1, 0, 0, 59), "94287082", new HMACSHA1()),
                new Tuple <DateTime, string, HMAC>(new DateTime(1970, 1, 1, 0, 0, 59), "32247374", new HMACSHA256()),
                new Tuple <DateTime, string, HMAC>(new DateTime(1970, 1, 1, 0, 0, 59), "69342147", new HMACSHA512()),

                new Tuple <DateTime, string, HMAC>(new DateTime(2005, 3, 18, 1, 58, 29), "07081804", new HMACSHA1()),
                new Tuple <DateTime, string, HMAC>(new DateTime(2005, 3, 18, 1, 58, 29), "34756375", new HMACSHA256()),
                new Tuple <DateTime, string, HMAC>(new DateTime(2005, 3, 18, 1, 58, 29), "63049338", new HMACSHA512()),

                new Tuple <DateTime, string, HMAC>(new DateTime(2005, 3, 18, 1, 58, 31), "14050471", new HMACSHA1()),
                new Tuple <DateTime, string, HMAC>(new DateTime(2005, 3, 18, 1, 58, 31), "74584430", new HMACSHA256()),
                new Tuple <DateTime, string, HMAC>(new DateTime(2005, 3, 18, 1, 58, 31), "54380122", new HMACSHA512()),

                new Tuple <DateTime, string, HMAC>(new DateTime(2009, 2, 13, 23, 31, 30), "89005924", new HMACSHA1()),
                new Tuple <DateTime, string, HMAC>(new DateTime(2009, 2, 13, 23, 31, 30), "42829826", new HMACSHA256()),
                new Tuple <DateTime, string, HMAC>(new DateTime(2009, 2, 13, 23, 31, 30), "76671578", new HMACSHA512()),

                new Tuple <DateTime, string, HMAC>(new DateTime(2033, 5, 18, 3, 33, 20), "69279037", new HMACSHA1()),
                new Tuple <DateTime, string, HMAC>(new DateTime(2033, 5, 18, 3, 33, 20), "78428693", new HMACSHA256()),
                new Tuple <DateTime, string, HMAC>(new DateTime(2033, 5, 18, 3, 33, 20), "56464532", new HMACSHA512())
            };

            foreach (var testValue in testValues)
            {
                string result = TimeBasedOneTimePassword.Generate(secret, testValue.Item3, testValue.Item1, TimeSpan.Zero, TimeBasedOneTimePassword.DEFAULT_TIME_STEP, OneTimePasswordLength.EightDigits);

                Assert.AreEqual(result, testValue.Item2.ToString());
            }
        }
예제 #10
0
        public ActionResult GetQrCode(long userId)
        {
            var loginSettings = _loginSettingRepository.Get(userId);

            if (loginSettings != null)
            {
                var secret = loginSettings.GoogleAuthenticatorSecretKey;
                Session["EncodedSecret"] = secret;
                if (string.IsNullOrEmpty(secret))
                {
                    string enc = "";
                    secret = TimeBasedOneTimePassword.GenerateSecret(out enc);
                    Session["EncodedSecret"] = secret;
                    ViewBag.EncodedSecret    = enc;
                }
                else
                {
                    Session["EncodedSecret"] = secret;
                    ViewBag.EncodedSecret    = TimeBasedOneTimePassword.EncodeSecret(secret);
                }
            }
            return(View());
        }
        public void Generate_DefaultsToSixDigitCode()
        {
            string result = TimeBasedOneTimePassword.Generate(new byte[] { 0 });

            Assert.IsTrue(result.Length == 6);
        }
 public void Generate_NegativeTimeStepThrowsException()
 {
     TimeBasedOneTimePassword.Generate(new byte[] { 0 }, new HMACSHA1(), TimeSpan.FromSeconds(0), OneTimePasswordLength.SixDigits);
 }
 public void Generate_UndefinedHOTPLengthThrowsException()
 {
     TimeBasedOneTimePassword.Generate(new byte[] { 0 }, new HMACSHA1(), 0);
 }
 public void Generate_EmptySecretKeyThrowsException()
 {
     TimeBasedOneTimePassword.Generate(new byte[0], new HMACSHA1());
 }
 public void Generate_NullSecretKeyThrowsException()
 {
     TimeBasedOneTimePassword.Generate(null, new HMACSHA1());
 }
 public void Generate_NullHmacThrowsException()
 {
     TimeBasedOneTimePassword.Generate(new byte[] { 0 }, null);
 }
        public void Generate_CanGenerateEightDigitCodes()
        {
            string result = TimeBasedOneTimePassword.Generate(new byte[] { 0 }, new HMACSHA1(), OneTimePasswordLength.EightDigits);

            Assert.IsTrue(result.Length == 8);
        }
예제 #18
0
        public ActionResult Edit(ProfileEditModel profileEditModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _userProfileService.SaveProfile(profileEditModel);
                    if (profileEditModel.IsOtpByAppEnabled || profileEditModel.IsOtpByEmailEnabled || profileEditModel.IsOtpBySmsEnabled || profileEditModel.IsPinRequiredForRole)
                    {
                        var loginSettings = _loginSettingRepository.Get(profileEditModel.Id);
                        loginSettings = loginSettings ?? new LoginSettings {
                            UserLoginId = profileEditModel.Id
                        };

                        loginSettings.DownloadFilePin = profileEditModel.IsPinRequiredForRole ? (string.IsNullOrEmpty(profileEditModel.DownloadFilePin) ? loginSettings.DownloadFilePin : profileEditModel.DownloadFilePin) : null;
                        if (profileEditModel.UseAuthenticator)
                        {
                            loginSettings.AuthenticationModeId         = (long)AuthenticationMode.AuthenticatorApp;
                            loginSettings.GoogleAuthenticatorSecretKey = (string)TempData["EncodedSecret"];
                        }
                        else
                        {
                            loginSettings.GoogleAuthenticatorSecretKey = null;
                            loginSettings.AuthenticationModeId         = profileEditModel.UseSms && profileEditModel.UseEmail ? (long)AuthenticationMode.BothSmsEmail : (profileEditModel.UseSms ? (long)AuthenticationMode.Sms : (long)AuthenticationMode.Email);
                        }
                        _loginSettingRepository.Save(loginSettings);
                    }

                    if (_sessionContext.UserSession.CurrentOrganizationRole.RoleId == (long)Roles.Technician)
                    {
                        var technicianProfile = _technicianRepository.GetTechnician(_sessionContext.UserSession.CurrentOrganizationRole.OrganizationRoleUserId);
                        if (technicianProfile != null)
                        {
                            technicianProfile.Pin = profileEditModel.TechnicianPin;
                        }
                        else
                        {
                            technicianProfile = new Technician
                            {
                                TechnicianId  = _sessionContext.UserSession.CurrentOrganizationRole.OrganizationRoleUserId,
                                CanDoPreAudit = false,
                                IsTeamLead    = false,
                                Pin           = profileEditModel.TechnicianPin
                            };
                        }
                        var repository = ((IRepository <Technician>)_technicianRepository);
                        repository.Save(technicianProfile);
                    }

                    profileEditModel = _userProfileService.GetProfileEditModel(profileEditModel.Id);

                    profileEditModel.FeedbackMessage = FeedbackMessageModel.CreateSuccessMessage("Profile Updated Successfully.");
                    return(View(profileEditModel));
                }

                var secret = (string)TempData["EncodedSecret"];
                profileEditModel.EncodedSecret = TimeBasedOneTimePassword.EncodeSecret(secret);
                TempData.Keep("EncodedSecret");
                return(View(profileEditModel));
            }
            catch (Exception ex)
            {
                profileEditModel.FeedbackMessage = FeedbackMessageModel.CreateFailureMessage(ex.Message);
                return(View(profileEditModel));
            }
        }
예제 #19
0
        private void Test(string sharedSecret, long seconds, string expected)
        {
            var calculated = TimeBasedOneTimePassword.GetPassword(sharedSecret, TimeBasedOneTimePassword.UNIX_EPOCH + TimeSpan.FromSeconds(seconds), TimeBasedOneTimePassword.UNIX_EPOCH, 30, 8);

            Assert.AreEqual(expected, calculated);
        }
예제 #20
0
파일: UserModel.cs 프로젝트: TMTKT5/cms69
        // <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;
        }