public void VerifyCodeReturnsFalseOnIncorrectCodes()
        {
            var target = new TwoFactorAuth();

            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 0, 1426847190));
            Assert.IsFalse(target.VerifyCode("VMR466AB62ZBOKHE", "543161", 0, 1426847190));     //Incorrect code
            Assert.IsFalse(target.VerifyCode("VMR466AB62ZBOKHE", "543159", 0, 1426847190));     //Incorrect code
            Assert.IsFalse(target.VerifyCode("VMR466AB62ZBOKHE", "54316", 0, 1426847190));      //Incorrect length
            Assert.IsFalse(target.VerifyCode("VMR466AB62ZBOKHE", "5431600", 0, 1426847190));    //Incorrect length
        }
Ejemplo n.º 2
0
        public async Task <ActionResult <ApiResponse <UserProperties> > > VerifyMfaEnable([FromBody] VerifyMfa mfaEnable)
        {
            try
            {
                if (mfaEnable is null || string.IsNullOrWhiteSpace(mfaEnable.MfaCode))
                {
                    return(BadRequest(RequestResponse.BadRequest("Mfa code is required for verification.")));
                }

                var userName = User?.Identity?.Name;
                var userId   = User?.Claims.Where(x => x.Type == CustomClaims.USER_ID).FirstOrDefault()?.Value;

                if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(userId))
                {
                    return(BadRequest(RequestResponse.BadRequest("Something went wrong trying to validate your request.")));
                }

                string secret;
                var    cacheKey   = $"{MFA_CACHE_KEY}{userId}";
                bool   doesExists = memoryCache.TryGetValue(cacheKey, out secret);

                if (!doesExists)
                {
                    return(BadRequest(RequestResponse.BadRequest("Something went wrong. Please try restart the Mfa process.")));
                }

                var verified = twoFactorAuth.VerifyCode(secret, mfaEnable.MfaCode);

                if (!verified)
                {
                    return(BadRequest(RequestResponse.BadRequest("Invalid Mfa code provided. Please try again.")));
                }

                var cacheResult          = new UserProperties(userId, secret, true);
                var currentPropertiesKey = await firebaseDbService.GetUserPropertiesKey(userId);

                if (!string.IsNullOrWhiteSpace(currentPropertiesKey))
                {
                    await firebaseDbService.UpdateUserProperties(currentPropertiesKey, cacheResult);
                }
                else
                {
                    await firebaseDbService.CreateUserProperties(cacheResult);
                }

                memoryCache.Remove(cacheKey);
                return(Ok(new ApiResponse <UserProperties>(cacheResult)));
            }
            catch (Exception)
            {
                return(BadRequest(RequestResponse.BadRequest("Something went wrong trying to enable Mfa.")));
            }
        }
Ejemplo n.º 3
0
        public void VerifyCorrectTimeSliceIsReturned()
        {
            var target = new TwoFactorAuth();

            // We test with discrapancy 3 (so total of 7 codes: c-3, c-2, c-1, c, c+1, c+2, c+3
            // Ensure each corresponding timeslice is returned correctly
            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "534113", 3, 1426847190, out long timeslice1));
            Assert.AreEqual(47561570, timeslice1);
            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "819652", 3, 1426847190, out long timeslice2));
            Assert.AreEqual(47561571, timeslice2);
            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "915954", 3, 1426847190, out long timeslice3));
            Assert.AreEqual(47561572, timeslice3);
            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 3, 1426847190, out long timeslice4));
            Assert.AreEqual(47561573, timeslice4);
            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "348401", 3, 1426847190, out long timeslice5));
            Assert.AreEqual(47561574, timeslice5);
            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "648525", 3, 1426847190, out long timeslice6));
            Assert.AreEqual(47561575, timeslice6);
            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "170645", 3, 1426847190, out long timeslice7));
            Assert.AreEqual(47561576, timeslice7);

            // Incorrect code should return false and a 0 timeslice
            Assert.IsFalse(target.VerifyCode("VMR466AB62ZBOKHE", "111111", 3, 1426847190, out long timeslice8));
            Assert.AreEqual(0, timeslice8);
        }
        public async Task <IActionResult> VerifyQrCode(string UserName, string key)
        {
            try
            {
                TwoFactorAuth TFAuth = new TwoFactorAuth();

                string sCode = UserName;
                string sKey  = string.Empty;

                sKey = key; //TFAuth.CreateSecret(160);
                bool st = TFAuth.VerifyCode(sKey, sCode, 5);
                if (st)
                {
                    return(Ok(new BizResponseClass {
                        ReturnCode = enResponseCode.Success, ReturnMsg = "Success"
                    }));
                }
                else
                {
                    return(Ok(new BizResponseClass {
                        ReturnCode = enResponseCode.Success, ReturnMsg = "Fail"
                    }));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(new BizResponseClass {
                    ReturnCode = enResponseCode.InternalError, ReturnMsg = ex.ToString(), ErrorCode = enErrorCode.Status500InternalServerError
                }));
            }
        }
Ejemplo n.º 5
0
    protected void Unnamed1_Click(object sender, EventArgs e)
    {
        tfa = new TwoFactorAuth(WWWVars.SiteName);
        Accounts useracc = null;
        string   userid  = (string)Session["userid"];

        using (VendingModelContainer dc = new VendingModelContainer())
        {
            var useraccs = dc.Set <Accounts>();
            useracc = useraccs.First(x => x.UserID == userid);
        }
        if (useracc.TOTPSecret != "" && totp.Text != null)
        {
            if (tfa.VerifyCode(useracc.TOTPSecret, totp.Text))
            {
                Session["userid"] = "";
                FormsAuthentication.RedirectFromLoginPage(useracc.UserID, false);
                Logger.AccountLog(Request.UserHostAddress, "Доступ предоставлен", "Введен правильный одноразовый код", useracc.ID);
                Logger.SystemLog(Request.UserHostAddress, "Доступ в систему предоставлен", useracc.UserID, "Server");
            }
            else
            {
                totpmsg.Text     = "Неверный одноразовый пароль";
                loginbox.Visible = false;
                totpbox.Visible  = true;
                Logger.AccountLog(Request.UserHostAddress, "Доступ запрещен", "Введен неправильный одноразовый код", useracc.ID);
                Logger.SystemLog(Request.UserHostAddress, "Ошибка: неверный одноразовый код", useracc.UserID, "Server");
            }
        }
    }
Ejemplo n.º 6
0
        public async Task ExecuteAsync(RequestData <GuriPacket> requestData)
        {
            if (requestData.ClientSession.MfaValidated != false || requestData.ClientSession.Account.MfaSecret == null)
            {
                return;
            }

            var tfa = new TwoFactorAuth();

            if (tfa.VerifyCode(requestData.ClientSession.Account.MfaSecret, requestData.Data.Value))
            {
                requestData.ClientSession.MfaValidated = true;
                await requestData.ClientSession.HandlePacketsAsync(new[] { new EntryPointPacket() });
            }
            else
            {
                await requestData.ClientSession.SendPacketAsync(new NosCore.Packets.ServerPackets.UI.GuriPacket
                {
                    Type     = GuriPacketType.Effect,
                    Argument = 3,
                    EntityId = 0
                }).ConfigureAwait(false);

                await requestData.ClientSession.SendPacketAsync(new InfoiPacket { Message = Game18NConstString.IncorrectPassword }).ConfigureAwait(false);
            }
        }
        public ActionResult Step2(string code)
        {
            if (string.IsNullOrEmpty((string)Session["secret"]))
            {
                return(View(new VerificationResult {
                    Success = false, Message = "Your session must have expired!? Did you visit step 1?"
                }));
            }

            if (!string.IsNullOrEmpty(code))
            {
                var result = new VerificationResult {
                    Success = tfa.VerifyCode((string)Session["secret"], code)
                };
                if (result.Success)
                {
                    result.Message = "Yay! Code verified!";
                }
                else
                {
                    result.Message = "Uh oh! The code did not verify :(";
                }

                return(View(result));
            }
            else
            {
                return(View(new VerificationResult {
                    Success = false, Message = "You need to enter a code..."
                }));
            }
        }
Ejemplo n.º 8
0
        public IActionResult confirmTFA([FromBody] string tfaCode, [FromHeader] string token)
        {
            // Check if the user managed to login with user and password but don't check 2fa here
            if (Logins.Verify(token, false, false) != null)
            {
                // Check if the user has 2fa enabled
                List <LoginSession> v = Program.db.Query <LoginSession>($"SELECT * FROM LoginSession WHERE id = '{token}';");
                LoginSession        u = v.Count > 0 ? v.First() : null;

                // Get the user that owns this session
                List <User> users = Program.db.Query <User>($"SELECT * FROM User WHERE id='{u.userId}';");
                User        user  = users.Last();

                if (u.passed2FA)
                {
                    return(BadRequest("2FA is already validated for this session."));
                }

                if (users.Count > 0)
                {
                    if (!string.IsNullOrEmpty(user.twoFactorSecret))
                    {
                        var tfa = new TwoFactorAuth("Cashier API"); //TODO: Change org to company name from global settings (WIP)

                        // Verify if 2FA code is valid
                        if (tfa.VerifyCode(user.twoFactorSecret, tfaCode))
                        {
                            // Code seems legit, update db and return session info.
                            u.passed2FA = true;
                            Program.db.Update(u);

                            // If 2FA was never confirmed let's make it confirmed as we validated a code.
                            if (!user.twoFactorConfirmed)
                            {
                                user.twoFactorConfirmed = true;
                                Program.db.Update(user);
                            }

                            return(Ok(u));
                        }
                        else
                        {
                            return(Unauthorized("Incorrect 2FA code"));
                        }
                    }
                    else
                    {
                        return(BadRequest("2FA is not enabled for this account."));
                    }
                }
                else
                {
                    return(BadRequest("No user found with this login token."));
                }
            }
            else
            {
                return(Unauthorized());
            }
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> ConnectUserAsync(ApiSession session)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.AUTH_ERROR)));
            }

            var account = await _accountDao.FirstOrDefaultAsync(s => s.Name == session.Identity).ConfigureAwait(false);

            if (account == null)
            {
                return(BadRequest(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.AUTH_ERROR)));
            }
            var tfa = new TwoFactorAuth();

            if (!string.IsNullOrEmpty(account.MfaSecret) && !tfa.VerifyCode(account.MfaSecret, session.Mfa))
            {
                return(BadRequest(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.MFA_INCORRECT)));
            }

            if (account.Password !.ToLower(CultureInfo.CurrentCulture) != (_hasher.Hash(session.Password)) &&
                account.NewAuthPassword !.ToLower(CultureInfo.CurrentCulture) != (_hasher.Hash(session.Password, account.NewAuthSalt !)))
            {
                return(BadRequest(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.AUTH_INCORRECT)));
            }

            account.Language = Enum.Parse <RegionType>(session.GfLang?.ToUpper(CultureInfo.CurrentCulture) ?? "");

            account = await _accountDao.TryInsertOrUpdateAsync(account).ConfigureAwait(false);

            var platformGameAccountId = Guid.NewGuid();
            var claims = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.NameIdentifier, session.Identity),
                new Claim(ClaimTypes.Sid, platformGameAccountId.ToString()),
                new Claim(ClaimTypes.Role, account.Authority.ToString())
            });
            var password = _hasher.Hash(_apiConfiguration.Value.Password !, _apiConfiguration.Value.Salt);

            var keyByteArray  = Encoding.Default.GetBytes(password);
            var signinKey     = new SymmetricSecurityKey(keyByteArray);
            var handler       = new JwtSecurityTokenHandler();
            var securityToken = handler.CreateToken(new SecurityTokenDescriptor
            {
                Subject            = claims,
                Issuer             = "Issuer",
                Audience           = "Audience",
                SigningCredentials = new SigningCredentials(signinKey, SecurityAlgorithms.HmacSha256Signature)
            });

            _logger.Information(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.AUTH_API_SUCCESS),
                                session.Identity, platformGameAccountId, session.Locale);
            return(Ok(new
            {
                token = handler.WriteToken(securityToken),
                platformGameAccountId
            }));
        }
Ejemplo n.º 10
0
 public async Task<ActionResult> Validate([FromBody] JObject validation)
 {
     var group = (await this.groupRepository.GetById(this.GroupId().Value));
     var tfa = new TwoFactorAuth(group.Name); 
     if (tfa.VerifyCode(group.Secret, validation.Property("token").Value.ToString()))
     {
         return Ok("Correct, klaar om te gebruiken");
     }
     return Ok("Validatie is incorrect");
 } 
Ejemplo n.º 11
0
        public async Task <ActionResult <ApiResponse <ExportPrivateKey> > > ExportPrivKey([FromBody] VerifyMfa mfaEnable)
        {
            try
            {
                if (mfaEnable is null || string.IsNullOrWhiteSpace(mfaEnable.MfaCode))
                {
                    return(BadRequest(RequestResponse.BadRequest("Mfa code is required in order to export your private key.")));
                }

                var userName = User?.Identity?.Name;
                var userId   = User?.Claims.Where(x => x.Type == CustomClaims.USER_ID).FirstOrDefault()?.Value;

                if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(userId))
                {
                    return(BadRequest(RequestResponse.BadRequest("Something went wrong trying to validate your request.")));
                }

                var userProperties = await firebaseDbService.GetUserProperties(userId);

                if (userProperties is null)
                {
                    return(NotFound(RequestResponse.NotFound("Error trying to find your Mfa data. Please try again.")));
                }

                if (!userProperties.IsMfaEnabled)
                {
                    return(BadRequest(RequestResponse.BadRequest("You must first enable Mfa in order to use this function.")));
                }

                var verified = twoFactorAuth.VerifyCode(userProperties.Secret, mfaEnable.MfaCode);

                if (!verified)
                {
                    return(BadRequest(RequestResponse.BadRequest("Invalid Mfa code provided. Please try again.")));
                }

                var result = await walletManagementService.GetWallets(userId, userName);

                if (!result.Any())
                {
                    return(NotFound(RequestResponse.NotFound($"No wallets found.")));
                }

                var wallet        = result.FirstOrDefault();
                var exportPrivKey = new ExportPrivateKey(wallet.PrivateKey, wallet.Addresses.FirstOrDefault()?.MyAddress);
                return(Ok(new ApiResponse <ExportPrivateKey>(exportPrivKey)));
            }
            catch (Exception)
            {
                return(BadRequest(RequestResponse.BadRequest("Something went wrong trying to export you private key.")));
            }
        }
Ejemplo n.º 12
0
 private void CheckQrCode(TwoFactorAuth tfa, string secret)
 {
     Console.WriteLine(((DateTimeOffset)GetTimeServer()).ToUnixTimeSeconds());
     if (tfa.VerifyCode(secret, maskedTextBox3.Text.Replace(maskedTextBox3.PromptChar.ToString(), ""), 1, timestamp: ((DateTimeOffset)GetTimeServer()).ToUnixTimeSeconds() + 30)) //Code must be enter in 30 seconds before expire on google auth.
     {
         label3.Text = "Login Successful";
         Console.WriteLine("true");
     }
     else
     {
         label3.Text = "Password Timeout";
         Console.WriteLine("false");
     }
 }
Ejemplo n.º 13
0
        public async Task <IActionResult> ValidateToken([FromBody] JObject payload)
        {
            var group = (await this.groupRepository.GetById(this.GroupId().Value));
            var tfa   = new TwoFactorAuth(group.Name);

            if (tfa.VerifyCode(group.Secret, payload.Property("token").Value.ToString()))
            {
                return(Ok("ok"));
            }
            else
            {
                return(Ok("We konden de token niet valideren, probeer het opnieuw"));
            }
        }
Ejemplo n.º 14
0
 private void checkotpbutton_Click(object sender, EventArgs e)
 {
     if (tfa.VerifyCode(otpsecret, otptextbox.Text))
     {
         MessageBox.Show("Двухфакторная авторизация успешно настроена.", "ОК", MessageBoxButtons.OK, MessageBoxIcon.Information);
         wizardPage2.AllowNext  = true;
         checkotpbutton.Enabled = false;
         otpsecretpicture.Image = null;
     }
     else
     {
         MessageBox.Show("НЕПРАВИЛЬНЫЙ ОДНОРАЗОВЫЙ ПАРОЛЬ!!!", "ОШИБКА", MessageBoxButtons.OK, MessageBoxIcon.Stop);
     }
     otptextbox.Text = "";
 }
Ejemplo n.º 15
0
 private void checkotpbutton_Click(object sender, EventArgs e)
 {
     if (tfa.VerifyCode(otpsecret, otptextbox.Text))
     {
         MessageBox.Show("Two-factor authentication setup complete. Proceed to next page.", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information);
         wizardPage2.AllowNext  = true;
         checkotpbutton.Enabled = false;
         otpsecretpicture.Image = null;
     }
     else
     {
         MessageBox.Show("WRONG ONE-TIME CODE!!!", "FAIL", MessageBoxButtons.OK, MessageBoxIcon.Stop);
     }
     otptextbox.Text = "";
 }
Ejemplo n.º 16
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        tfa = new TwoFactorAuth(WWWVars.SiteName);
        string   totpsecret = "";
        Accounts useracc    = null;

        using (VendingModelContainer dc = new VendingModelContainer())
        {
            var useraccs = dc.Set <Accounts>();
            useracc = useraccs.First(x => x.UserID == User.Identity.Name);
        }
        totpsecret = (string)Session["totps"];
        if (totpsecret != "" && (string)Request.Form["totp"] != null)
        {
            if (tfa.VerifyCode(totpsecret, (string)Request.Form["totp"]))
            {
                using (VendingModelContainer dc = new VendingModelContainer())
                {
                    try
                    {
                        var      useraccs = dc.Set <Accounts>();
                        Accounts useracc2 = useraccs.First(x => x.UserID == User.Identity.Name);
                        useracc2.TOTPSecret = (string)Session["totps"];
                        Session["totps"]    = "";
                        dc.SaveChanges();
                        twofasetupbox.Visible         = false;
                        twofasetupcompletebox.Visible = true;
                        Logger.AccountLog(Request.UserHostAddress, "Завершена настройка двухфакторной авторизации", "", useracc2.ID);
                        Logger.SystemLog(Request.UserHostAddress, "Пользователь настроил двухфакторную авторизацию", useracc2.UserID, "Server");
                    }
                    catch (Exception ex)
                    {
                        totpmsg.Text = "Произошла ошибка, попробуйте еще раз!";
                        Logger.SystemLog(Request.UserHostAddress, "Ошибка: " + ex.Message, ex.InnerException?.Message, User.Identity.Name);
                    }
                }
            }
            else
            {
                totpmsg.Text = "Неверный одноразовый пароль!";
            }
        }
    }
Ejemplo n.º 17
0
        public async Task <IActionResult> JoinByName([FromBody] JObject payload)
        {
            if (!string.IsNullOrWhiteSpace(payload.Property("name").Value.ToString()))
            {
                var group = await this.groupRepository.GetByName(payload.Property("name").Value.ToString());

                if (group != null &&
                    !string.IsNullOrWhiteSpace(payload.Property("token").Value.ToString()))
                {
                    var tfa = new TwoFactorAuth(group.Name);
                    if (tfa.VerifyCode(group.Secret, payload.Property("token").Value.ToString()))
                    {
                        if (group != null && group.GroupId.HasValue)
                        {
                            var jwt = JoinGroupJwtBased(group);
                            group.RefreshToken = GenerateRefreshToken();
                            await this.groupRepository.Save(group);

                            return(new JsonResult(new
                            {
                                name = group.Name,
                                token = jwt,
                                refreshToken = group.RefreshToken
                            }));
                        }
                    }
                    else
                    {
                        return(Ok("Je token is niet geledig"));
                    }
                }
                else
                {
                    return(Ok("Vul ook de token van je authenticator in"));
                }
            }

            return(Ok("Helaas kennen we deze groep niet"));
        }
        public void VerifyCodeAllowsNegativeDiscrepancy()
        {
            var target = new TwoFactorAuth(digits: 6, period: 30, algorithm: Algorithm.SHA1);

            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", -2, 1426847205 - 65));    // Test negative discrepancy
        }
Ejemplo n.º 19
0
        public async Task <IActionResult> twoFaAuth(csgo.postModels.twoFactor obj)
        {
            if (csgo.Controllers.adminController.tokenAccess.validateToken(Request, adminController.tokenType.twofactor))
            {
                if (csgo.core.requestsHelper.processRequest(Request))
                {
                    return(Json(new { success = "false", message = "You are sending to many requests. Blacklist will expire in 30 seconds." }));
                }
                var a = TempData["userId"];
                if (a == null)
                {
                    TempData["toast"] = "{type:'error',message:'You are not authorized. An error occured try again later 1.'}";
                    return(this.Redirect(@Url.Action("index", "home")));
                }
                int userId       = (int)a;
                var temp2FAToken = TempData["temp2FAToken"];
                if (temp2FAToken != null)
                {
                    if (obj.code != null && tfa.VerifyCode((string)temp2FAToken, obj.code.Replace(" ", "")))
                    {
                        await databaseManager.updateQuery($"UPDATE users SET twofaToken = '{temp2FAToken}', loginIP = '' WHERE id = @id LIMIT 1").addValue("@id", TempData["userId"]).Execute();

                        TempData["toast"] = "{type:'success',message:'You successully configured the authentificator.'}";
                        return(this.Redirect(@Url.Action("index", "login")));
                    }
                    else
                    {
                        TempData["userId"] = (int)userId;


                        TempData["temp2FAToken"] = (string)temp2FAToken;
                        TempData["token2FA"]     = "";
                        csgo.Controllers.adminController.tokenAccess.createToken(Request, adminController.tokenType.twofactor);
                        return(this.Redirect("https://localhost/2fa"));
                    }
                }
                var token2FA = TempData["token2FA"];
                if (token2FA == null)
                {
                    TempData["toast"] = "{type:'error',message:'You are not authorized.'}";
                    return(this.Redirect(@Url.Action("index", "home")));
                }
                Console.WriteLine($"TOKEN FROM DATABASE {(string)token2FA} AND CODE {obj.code} TIME ON THE SERVER {DateTime.Now}");
                Console.WriteLine($"TOKEN SERVERSIDE {tfa.GetCode((string)token2FA, tfa.TimeProvider.GetTimeAsync().Result)}");
                Console.WriteLine(tfa.VerifyCode((string)token2FA, obj.code, 1, DateTime.UtcNow));
                Console.WriteLine($"UTC NOW {DateTime.UtcNow.ToString()}");
                Console.WriteLine($"GENERATED 2FA CODE {tfa.GetCode((string)token2FA)}");
                if (tfa.VerifyCode((string)token2FA, obj.code.Replace(" ", "")))
                {
                    Guid   g          = Guid.NewGuid();
                    string GuidString = Convert.ToBase64String(g.ToByteArray());
                    GuidString = GuidString.Replace("=", "");
                    GuidString = GuidString.Replace("+", "");

                    string cookiegenerated = GuidString;
                    string ip = Request.getIPAddress();

                    userData userDetails = new userData();
                    userDetails.loginIP = ip;
                    await databaseManager.selectQuery("SELECT * FROM users WHERE id = @id LIMIT 1", delegate(DbDataReader reader)
                    {
                        if (reader.HasRows)
                        {
                            userDetails.balance        = (decimal)reader["balance"];
                            userDetails.username       = (string)reader["username"];
                            userDetails.id             = (int)reader["id"];
                            userDetails.cookie         = cookiegenerated;
                            userDetails.registerDate   = (DateTime)reader["registerDate"];
                            userDetails.seller         = (bool)reader["seller"];
                            userDetails.negativeRates  = (int)reader["negativeRates"];
                            userDetails.positiveRates  = (int)reader["positiveRates"];
                            userDetails.soldAccounts   = (int)reader["soldAccounts"];
                            userDetails.boughtAccounts = (int)reader["boughtAccounts"];
                            userDetails.confirmed      = (bool)reader["confirmed"];
                            userDetails.admin          = (bool)reader["admin"];
                            userDetails.email          = (string)reader["email"];
                            userDetails.lastConfirm    = (DateTime)reader["lastConfirm"];
                            userDetails.validateToken  = (string)reader["validateToken"];
                            userDetails.lastUpdate     = DateTime.Now;
                            userDetails.banned         = (bool)reader["banned"];
                            userDetails.banReason      = (string)reader["banReason"];
                            userDetails.twofa          = (bool)reader["twofa"];
                            userDetails.twofaToken     = (string)reader["twofaToken"];
                            userDetails.lastLogin      = (DateTime)reader["lastLogin"];
                        }
                    }).addValue("@id", userId).Execute();

                    if (userDetails.banned)
                    {
                        TempData["toast"] = "{type:'error',message:'" + $"Your account is banned on this site. Reason: {userDetails.banReason}" + "'}";
                        return(this.Redirect(@Url.Action("index", "home")));
                    }

                    if (!userDetails.confirmed)
                    {
                        if (userDetails.email.Contains("yahoo"))
                        {
                            TempData["toast"]  = "{type:'warning',message:'Yahoo isn't fully supported. Please change your email in order to use this site.'}";
                            TempData["userId"] = userDetails.id;
                            Console.WriteLine("email recovery");
                            csgo.Controllers.adminController.tokenAccess.createToken(Request, adminController.tokenType.changeemail);
                            return(this.Redirect(@Url.Action("changeEmail")));
                        }
                        else
                        {
                            if ((int)(DateTime.Now - userDetails.lastConfirm).TotalMinutes > 30)
                            {
                                if (userDetails.validateToken.Length < 3)
                                {
                                    userDetails.validateToken = csgo.core.emailManager.randomToken(new Random().Next(10, 30));
                                }
                                Console.WriteLine(csgo.core.emailManager.sendConfirmationEmail(userDetails.email, userDetails.validateToken).Content);
                                await databaseManager.updateQuery($"UPDATE users SET lastConfirm = CURRENT_TIMESTAMP, validateToken = @validateToken WHERE id = @id LIMIT 1").addValue("@validateToken", userDetails.validateToken).addValue("@id", userId).Execute();

                                TempData["toast"] = "{type:'success',message:'And confirmation code was send to your email.'}";
                            }
                            else
                            {
                                TempData["toast"] = "{type:'success',message:'Account isn`t confirmed yet. Check your email.'}";
                            }
                        }
                        return(this.Redirect(@Url.Action("index", "home")));
                    }

                    CookieOptions option = new CookieOptions();



                    option.Expires = new DateTimeOffset?(DateTime.Now.AddDays(5));

                    Response.Cookies.Append("sessionid", cookiegenerated, option);

                    await databaseManager.updateQuery($"UPDATE users SET cookie = '{cookiegenerated}', loginIP = '{ip}', lastLogin = CURRENT_TIMESTAMP WHERE id = @id LIMIT 1").addValue("@id", userId).Execute();

                    var index = csgo.usersManager.users.FindIndex(a => a.id == userId);

                    if (index != -1)
                    {
                        var b = csgo.usersManager.users[index];
                        if (b.connectionId != null)
                        {
                            await b.sendNotify(core.notifyManager.notifyType.warning, $"Someone just connected on your account using 2FA. IP: {ip}. You will be log out.");

                            await csgo.core.ChatHub.Current.Clients.Client(b.connectionId).SendAsync("logout");
                        }
                        csgo.usersManager.users[index] = userDetails;
                    }
                    else
                    {
                        csgo.usersManager.users.Add(userDetails);
                    }

                    var s = TempData["loginRequest"];

                    TempData.Remove("loginRequest");
                    TempData["toast"] = "{type:'success',message:'You succesfully logged in using 2FA.'}";

                    return(this.Redirect(@Url.Action("index", "home")));
                }
                else
                {
                    TempData["userId"]   = (int)userId;
                    TempData["token2FA"] = (string)token2FA;
                    TempData["toast"]    = "{type:'error',message:'Your 2FA code is invalid. You have more 2 chances.'}";
                    csgo.Controllers.adminController.tokenAccess.createToken(Request, adminController.tokenType.twofactor);
                    return(this.Redirect("https://localhost/2fa/"));
                }



                TempData["toast"] = "{type:'success',message:'And confirmation code was send to your new email.'}";
                return(this.Redirect(@Url.Action("index", "home")));
            }
            TempData["toast"] = "{type:'error',message:'You are not authorized 2.'}";
            return(this.Redirect(@Url.Action("index", "home")));
        }
    protected void changedevmodetotpbutton_Click(object sender, EventArgs e)
    {
        TwoFactorAuth tfa     = new TwoFactorAuth(WWWVars.SiteName);
        Accounts      useracc = null;

        using (VendingModelContainer dc = new VendingModelContainer())
        {
            useracc = dc.Accounts.First(x => x.UserID == HttpContext.Current.User.Identity.Name && x.Valid && !x.Suspended);
            if (useracc.TOTPSecret != "" && changedevmodetotp.Text != "")
            {
                if (tfa.VerifyCode(useracc.TOTPSecret, changedevmodetotp.Text))
                {
                    DateTime cdt      = DateTime.Now;
                    long     cdtlong  = Convert.ToInt64(cdt.ToString("yyyyMMddHHmmss"));
                    string   cdtstr   = cdt.ToString("dd.MM.yyyy HH:mm:ss");
                    WDCmd    tmpwdcmd = null;
                    string   cmddescr = "";
                    switch (devmodecb.SelectedValue)
                    {
                    case "salesmode":
                    {
                        tmpwdcmd = WDCmdSet.GoToSalesMode;
                        cmddescr = "Переход в РЕЖИМ ПРОДАЖ";
                        break;
                    }

                    case "oosmode":
                    {
                        tmpwdcmd = WDCmdSet.GoToOOSMode;
                        cmddescr = "Переход в режим НЕ ОБСЛУЖИВАЕТ";
                        break;
                    }

                    case "servicemode":
                    {
                        tmpwdcmd = WDCmdSet.GoToServiceMode;
                        cmddescr = "Переход в СЛУЖЕБНЫЙ РЕЖИМ";
                        break;
                    }

                    case "shutdown":
                    {
                        tmpwdcmd = WDCmdSet.Shutdown;
                        cmddescr = "ВЫКЛЮЧЕНИЕ";
                        break;
                    }

                    case "reboot":
                    {
                        tmpwdcmd = WDCmdSet.Reboot;
                        cmddescr = "ПЕРЕЗАГРУЗКА";
                        break;
                    }

                    case "incasso":
                    {
                        tmpwdcmd = WDCmdSet.Incassation;
                        cmddescr = "ИНКАССАЦИЯ";
                        break;
                    }

                    case "KKTCloseStage":
                    {
                        tmpwdcmd = WDCmdSet.KKTCloseStage;
                        cmddescr = "ЗАКРЫТИЕ СМЕНЫ";
                        break;
                    }

                    case "KKTRegistrationMode":
                    {
                        tmpwdcmd = WDCmdSet.KKTRegistrationMode;
                        cmddescr = "ККТ: РЕЖИМ РЕГИСТРАЦИИ";
                        break;
                    }

                    case "KKTOpenStage":
                    {
                        tmpwdcmd = WDCmdSet.KKTOpenStage;
                        cmddescr = "ККТ: ОТКРЫТЬ СМЕНУ";
                        break;
                    }

                    case "KKTCancelReceipt":
                    {
                        tmpwdcmd = WDCmdSet.KKTCancelReceipt;
                        cmddescr = "ККТ: ОТМЕНА ТЕКУЩЕГО ЧЕКА";
                        break;
                    }

                    case "Unregister":
                    {
                        tmpwdcmd = WDCmdSet.Unregister;
                        cmddescr = "Удаление устройства (отмена регистрации)";
                        break;
                    }
                    }
                    //формируем команду
                    WaterDeviceCommands tmpcmd = new WaterDeviceCommands()
                    {
                        AckDatetime          = 0,
                        AckDatetimeStr       = "",
                        Command              = tmpwdcmd.Command,
                        FormedDatetime       = cdtlong,
                        FormedDatetimeStr    = cdtstr,
                        WaterDeviceID        = wvdid,
                        RequestedDatetime    = 0,
                        RequestedDatetimeStr = "",
                        Result = ""
                    };
                    dc.WaterDeviceCommands.Add(tmpcmd);
                    dc.SaveChanges();
                    Logger.AccountLog(Request.UserHostAddress, "Новая команда устройству №" + tmpcmd.WaterDeviceID, tmpcmd.Command, tmpcmd.WaterDeviceID);
                    Logger.SystemLog(Request.UserHostAddress, "Новая команда устройству №" + tmpcmd.WaterDeviceID, tmpcmd.Command, "Server");
                    changedevmodetotpbox.Visible = false;
                    changedevmodebutton.Visible  = true;
                    changedevmodemsg.Text        = "";
                    //devmodecb.SelectedIndex = 0;
                    devmodecb.Enabled = true;
                    ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", "alert('Команда \"" + cmddescr + "\" сформирована. Дождитесь ее выполнения на устройстве.')", true);
                }
                else
                {
                    changedevmodetotpmsg.Text    = "Неверный одноразовый пароль";
                    changedevmodebutton.Visible  = false;
                    changedevmodetotpbox.Visible = true;
                }
            }
        }
        FillTablesWithData();
    }
Ejemplo n.º 21
0
        public BusinessViewModelContainer <bool> LoginCheckDyCode(PasswordLoginViewModel model)
        {
            BusinessViewModelContainer <bool> viewModel = new BusinessViewModelContainer <bool>();

            try
            {
                if (model.CheckCode.IsNullOrEmpty())
                {
                    return(viewModel);
                }
                if (model.Sign.IsNullOrEmpty())
                {
                    viewModel.SetFalied("签名不能为空!");
                    return(viewModel);
                }
                string deSign = string.Empty;
                try
                {
                    deSign = DESEncrypt.Decrypt(model.Sign);
                }
                catch
                { }
                if (deSign.IsNullOrEmpty())
                {
                    viewModel.SetFalied("签名错误!");
                    return(viewModel);
                }
                string[] arrSign   = deSign.Split('|');
                long     timeSnamp = arrSign[0].ToLong();
                int      step      = arrSign[1].ToInt();

                //时间戳之间的间隔不能过长-不可超过5分钟
                if ((DateTime.Now.ToTimeStampMilliseconds() - timeSnamp) / 1000 > 5 * 60)
                {
                    viewModel.SetFalied("登录超时!请重新输入用户名密码!");
                    return(viewModel);
                }

                if (step != 2 || arrSign.Length < 4)
                {
                    viewModel.SetFalied("登录必须输入密码!请重新输入用户名密码!");
                    return(viewModel);
                }
                string uName = arrSign[2];
                string pwd   = arrSign[3];
                if (string.IsNullOrEmpty(uName) || string.IsNullOrEmpty(pwd))
                {
                    viewModel.SetFalied("登录必须输入密码!请重新输入用户名密码!");
                    return(viewModel);
                }


                var sysUser = Singleton <SysAdminService> .Instance
                              .GetSysAdminFirstOrDefaultByCondition(x => x.Uname == uName &&
                                                                    x.Upassword == pwd && x.State == true);

                if (null == sysUser)
                {
                    viewModel.SetFalied("未知用户!");
                    return(viewModel);
                }
                if (string.IsNullOrEmpty(sysUser.PublicKey))
                {
                    viewModel.SetFalied("用户密钥已经失效!请联系管理员!");
                    return(viewModel);
                }


                //进行谷歌身份验证,如果验证通过,那么写入系统用户Cookie
                //写入凭证
                //todo:进行谷歌二阶验证
                var tfaProvider = new TwoFactorAuth();

                bool validateResult = false;
                try
                {
                    validateResult = tfaProvider.VerifyCode(sysUser.PublicKey, model.CheckCode);
                }
                catch
                { }

                if (true == validateResult)
                {
                    //验证通过
                    //1 记录登录日志:
                    var logModel = new SysLogModel
                    {
                        Level     = 1,
                        SysUserId = sysUser.Id,
                        //LogType = (int)SysLogTypeEnum.Login,
                        LogContent = $"超管账号:{sysUser.Uname} , 登录系统!",
                        CreateTime = DateTime.Now,
                        IpAddress  = base.IpAddress
                    };
                    Singleton <SysLogService> .Instance.AddOneSysLogModel(logModel);

                    //2 客户端授权并进入后台页面
                    viewModel.Msg  = "成功登录!";
                    viewModel.Data = true;


                    var sysUserLoginModel = new LoginSystemAdminResultViewModel
                    {
                        AdminUserId = sysUser.Id,
                        IsSuccess   = true,
                        Step        = 3,
                        Sign        = model.Sign//自定义签名
                    };


                    string authJson = sysUserLoginModel.ToJson();
                    //写入用户基本信息Cookie
                    HttpContext.SetCookie(Contanst.Global_Site_Domain_Cookie, Contanst.Login_Cookie_SystemAdminUserInfo, authJson);
                }
                else
                {
                    viewModel.SetFalied("口令已经过期,请重新输入!");
                }
            }
            catch (Exception ex)
            {
                viewModel.SetFalied("验证失败!");
                Logger.Error(ex);
            }

            return(viewModel);
        }
 public void VerifyCodeAllowsNegativeDiscrepancy()
 {
     var target = new TwoFactorAuth(null, 6, 30, Algorithm.SHA1);
     Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", -2, 1426847205 - 65));	    // Test negative discrepancy
 }
        public void VerifyCodeWorksCorrectly()
        {
            var target = new TwoFactorAuth(digits: 6, period: 30, algorithm: Algorithm.SHA1);

            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 1, 1426847190));
            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 0, 1426847190 + 29));     // Test discrepancy
            Assert.IsFalse(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 0, 1426847190 + 30));    // Test discrepancy
            Assert.IsFalse(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 0, 1426847190 - 1));     // Test discrepancy
            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 1, 1426847205 + 0));      // Test discrepancy
            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 1, 1426847205 + 35));     // Test discrepancy
            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 1, 1426847205 - 35));     // Test discrepancy
            Assert.IsFalse(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 1, 1426847205 + 65));    // Test discrepancy
            Assert.IsFalse(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 1, 1426847205 - 65));    // Test discrepancy
            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 2, 1426847205 + 65));     // Test discrepancy
            Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 2, 1426847205 - 65));     // Test discrepancy
        }
        Task <bool> IUserTokenProvider <BackOfficeIdentityUser, int> .ValidateAsync(string purpose, string token, UserManager <BackOfficeIdentityUser, int> manager, BackOfficeIdentityUser user)
        {
            var tfa = new TwoFactorAuth("CustomSection");

            return(Task.FromResult(tfa.VerifyCode("XANIK3POC23RCRYN", token)));
        }
Ejemplo n.º 25
0
 public static bool Verify(string secret, string code)
 {
     return(tfa.VerifyCode(secret, code));
 }
 public void VerifyCodeWorksCorrectly()
 {
     var target = new TwoFactorAuth(null, 6, 30, Algorithm.SHA1);
     Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 1, 1426847190));
     Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 0, 1426847190 + 29));	    // Test discrepancy
     Assert.IsFalse(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 0, 1426847190 + 30));	// Test discrepancy
     Assert.IsFalse(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 0, 1426847190 - 1));	    // Test discrepancy
     Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 1, 1426847205 + 0));	    // Test discrepancy
     Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 1, 1426847205 + 35));	    // Test discrepancy
     Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 1, 1426847205 - 35));	    // Test discrepancy
     Assert.IsFalse(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 1, 1426847205 + 65));	// Test discrepancy
     Assert.IsFalse(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 1, 1426847205 - 65));	    // Test discrepancy
     Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 2, 1426847205 + 65));	    // Test discrepancy
     Assert.IsTrue(target.VerifyCode("VMR466AB62ZBOKHE", "543160", 2, 1426847205 - 65));	    // Test discrepancy
 }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            // inicializa le autenticador multifactor, el argumento es
            // el nombre de la aplicación que se muestra, por ejmeplo «Facebook»
            // en este caso es «Aplicación Tal»
            var tfa = new TwoFactorAuth(ConfigurationManager.AppSettings["appname"]);

            // pregunta quién es el usaurio
            Console.WriteLine("teclee su identificación de usaurio");
            var _userInput = Console.ReadLine();

            // localiza el usuario en la base de datos
            var _user = Users.FindUser(_userInput);

            // si el usuario no existe no existe se crea y se genera el código Qr
            if (_user == null)
            {
                Console.WriteLine($"tu eres nuevo por aquí, cual es tu nombre completo");
                var _realname = Console.ReadLine();

                // crea un nuevo usuario
                _user = new UserModel {
                    UserName = _userInput, RealName = _realname
                };

                // genera el secreto y almacenalo junto con el usuario
                _user.Secret = tfa.CreateSecret(160);


                // el html contiene el qrcode generado en un <img>
                // toma como argumento el realname que pondremos en la tag y el secre del usuario
                var _html = $"<p>{_user.RealName} ({_user.UserName})</p>";
                _html += $"<p><img src=\"{tfa.GetQrCodeImageAsDataUri(_user.RealName,_user.Secret)}\" ></p>";
                _html += $"<p>{_user.Secret}</p>";

                // escribe un html con el QrCode en una imagen
                File.WriteAllText(QrCodeFile, _html);
                Console.WriteLine($"escanea el código qr en file:///{QrCodeFile}");

                // guarda el usuario
                Users.AddUser(_user);
            }
            else
            {
                Console.WriteLine($"verificando credenciales de acceso para «{_user.RealName}»");
            }

            if (_user.LastLogin != null)
            {
                Console.WriteLine($"el último acceso fue {_user.LastLogin.ToString()}");
            }
            else
            {
                Console.WriteLine("no se han registrado accesos al sistema");
            }

            // toma el código que escriba en el usuario
            Console.WriteLine("teclee el código que se muestra en la app de autenticación");
            var _code = Console.ReadLine();

            // verifica que código dado
            Console.WriteLine($"verificando «{_code}»");
            if (tfa.VerifyCode(_user.Secret, _code))
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("correcto! acceso consedido");
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("nop... eso no pinchó, te vas pal carajo");
            }

            // refresca el last login del usuario
            _user.LastLogin = DateTime.Now;
            Users.UpdateUser(_user);

            // el resto sale invisible
            Console.ForegroundColor = Console.BackgroundColor;

            // elimina el html si existe
            if (File.Exists(QrCodeFile))
            {
                File.Delete(QrCodeFile);
            }
        }