public void EnumerateAccountRights_NoRightsFails() { LsaHandle handle = AuthenticationMethods.LsaOpenLocalPolicy(PolicyAccessRights.POLICY_READ); SID sid = AuthorizationMethods.CreateWellKnownSid(WELL_KNOWN_SID_TYPE.WinBuiltinAnyPackageSid); SecurityMethods.LsaEnumerateAccountRights(handle, ref sid).Should().BeEmpty(); }
private bool LoginUser(string username, string password) { List <User> _user = new List <User>(); var path = FullPath(); string folderPath = path[0].ToString(); string fullPath = path[1].ToString(); string getUser = path[2].ToString(); var array = JArray.Parse(getUser); foreach (var item in array) { try { _user.Add(item.ToObject <User>()); } catch (Exception ex) { } } password = SecurityMethods.Encrypt(password); _user = _user.Where(c => c.UserName.Trim().Equals(username.Trim()) && c.Password.Trim().Equals(password.Trim()) && c.IsDelete.Equals(false)).ToList(); if (_user.Count == 1) { return(true); } else { return(false); } }
[HttpGet] // Контроллер для отправки входных параметров :) public string[] Get() { string[] result = null; string token = Request.Headers["Authorization"]; int id = new SecurityMethods().ParseToken(token); if (id < 0) { result = DpDataBase.Inputs.Where(p => p.Id == 1).Select(x => x.NAME).ToArray(); } else { result = DpDataBase.Inputs.Where(p => p.UserId == id || p.Id == 1).Select(x => x.NAME).ToArray(); } if (result.Length == 0) { string sw = new System.IO.StreamReader("log.txt", true).ReadToEnd(); var dt = JsonConvert.DeserializeObject <DPInputData>(sw.ToString()); dt.NAME = "Ознакомительный вариант расчета"; dt.UserId = 0; DpDataBase.Inputs.Add(dt); DpDataBase.SaveChanges(); return(DpDataBase.Inputs.Where(p => p.Id == 1).Select(x => x.NAME).ToArray()); } return(result); }
public IActionResult UpdateUser(UserModel userModel) { if (!ModelState.IsValid) { Response.StatusCode = 400; return(View(userModel)); } var userList = GetUserList(); var fullPath = FullPath(); var userRemove = userList.Single(r => r.Id == userModel.Id); userList.Remove(userRemove); userModel.Password = SecurityMethods.Encrypt(userModel.Password); userList.Add(new User() { Id = userRemove.Id, FirstName = userModel.FirstName, LastName = userModel.LastName, UserName = userModel.UserName, Password = userModel.Password, Authority = userModel.Authority, IsDelete = false }); string JSONresult = JsonConvert.SerializeObject(userList.ToArray(), Formatting.Indented); System.IO.File.WriteAllText(fullPath, JSONresult); return(RedirectToAction("Index")); }
/** This function creates objects and calls their methods. First the security methods are called and if they return false call the points updating * methods */ private async void AddPointsClicked(object sender, EventArgs e) { SecurityMethods checks = new SecurityMethods(); Task <bool> myTask = checks.DayLimitLock(); await myTask; Task <bool> myTaskTwo = checks.TimeLimitLock(); await myTaskTwo; if (myTask.Result) { await DisplayAlert("Daily Limit Reached", "You can only log 15 Actions per day.", "OK"); await Navigation.PushAsync(new MainMenu()); } else if (myTaskTwo.Result) { await DisplayAlert("Too soon", "You must wait 1 minute before logging the next Action.", "OK"); await Navigation.PushAsync(new MainMenu()); } else { PointsUpdate helper = new PointsUpdate(); helper.UpdateBySixPoints(); ShoppingPointsUpdate helper2 = new ShoppingPointsUpdate(); helper2.ReBattereisPoints(); await DisplayAlert("Points Added", AppConstants.sixPointsMsg, "OK"); await Navigation.PushAsync(new MainMenu()); } }
public void EnumerateAccountRights_BadSidFails() { LsaHandle handle = AuthenticationMethods.LsaOpenLocalPolicy(PolicyAccessRights.POLICY_READ); SID sid = new SID(); Action action = () => SecurityMethods.LsaEnumerateAccountRights(handle, ref sid); action.ShouldThrow <ArgumentException>(); }
public void EnumerateAccountRights_ReadRightsFails() { LsaHandle handle = AuthenticationMethods.LsaOpenLocalPolicy(PolicyAccessRights.POLICY_READ); SID sid = AuthorizationMethods.CreateWellKnownSid(WELL_KNOWN_SID_TYPE.WinBuiltinUsersSid); Action action = () => SecurityMethods.LsaEnumerateAccountRights(handle, ref sid); action.ShouldThrow <UnauthorizedAccessException>(); }
public void EnumerateAccountRights_UserGroup() { LsaHandle handle = AuthenticationMethods.LsaOpenLocalPolicy(PolicyAccessRights.POLICY_EXECUTE); SID sid = AuthorizationMethods.CreateWellKnownSid(WELL_KNOWN_SID_TYPE.WinBuiltinUsersSid); var rights = SecurityMethods.LsaEnumerateAccountRights(handle, ref sid); rights.Should().NotBeEmpty(); rights.Should().Contain("SeChangeNotifyPrivilege"); }
public void Ensure(SecurityEntityTypes entityType, SecurityMethods method) { string rightToCheck = GetDummyRightName(entityType, method); string currentIdentityName = this.GetCurrentIdentityName(); if (!this.dummyUserRights.ContainsKey(currentIdentityName) || !this.dummyUserRights[currentIdentityName].Contains(rightToCheck)) { throw new SecurityException(); } }
public bool Post(DeleteData dd) { string token = Request.Headers["Authorization"]; int userid = new SecurityMethods().ParseToken(token); DPInputData a = DpDataBase.Inputs.First(p => p.NAME == dd.ParamsName && p.UserId == userid); DpDataBase.Inputs.Remove(a); DpDataBase.SaveChanges(); return(true); }
private void kbtnGeneratePasword_Click(object sender, EventArgs e) { if (ktxtOutput.Text == string.Empty) { ktxtOutput.Text = SecurityMethods.CreatePassword(Convert.ToInt32(knudPasswordLength.Value)); } else { ktxtOutput.Text = ""; ktxtOutput.Text = SecurityMethods.CreatePassword(Convert.ToInt32(knudPasswordLength.Value)); } }
public async System.Threading.Tasks.Task <ActionResult> NovaPessoa([Bind(Include = "PrimeiroNome, Sobrenome, CPF, RG, Sexo, DtNascimento, TelPrincipal, TelOpcional, Email, CEP, Logradouro, Complemento, Numero, Bairro, Cidade, Estado, Pais, PerfilID")] RegistrarComumViewModel novaPessoa) { if (ModelState.IsValid) { //Criando pessoa int pID = _userStore.AddPessoa(novaPessoa); //Criando usuario RBAC_Usuario RU = new RBAC_Usuario(); RU.Pessoa_ID = pID; RU.Username = novaPessoa.Email; //Gernado Senha tempraria e salt string tempToken = SecurityMethods.GenerateTempTokenAccess(); string tempSalt = SecurityMethods.GenerateSalt(); string tempPass = SecurityMethods.HashPasswordPBKDF2(tempToken, tempSalt); //Criando usuario RU.Senha_Hash = tempPass; RU.Salt = tempSalt; RU.Dt_Criacao = DateTime.Now.Date; RU.Dt_Ultima_Modif = DateTime.Now.Date; RU.Bloqueado = false; db.RBAC_Usuario.Add(RU); db.SaveChanges(); //Enviando Email da senha EmailMessage message = new EmailMessage(novaPessoa.Email, "Bem-vindo ao NimbusAcad!", "Olá, seja bem-vindo ao NimbusAcad \n Esta é sua senha: " + tempToken + "\nRecomenda-se que altere a senha para uma, com fácil memorização."); await _emailService.Send(message); //Enviando Email de confirmação de email var callbackUrl = Url.Action("ConfirmarEmail", "Account", new { novaPessoa.Email }, null); EmailMessage confirmacao = new EmailMessage(novaPessoa.Email, "Confirmar email", "Por favor, confirme seu email clicando neste link: <a href=\"" + callbackUrl + "\">Confirmar</a>"); await _emailService.Send(confirmacao); //Assimilando perfil de acesso int uID = _userStore.GetUsuarioID(novaPessoa.Email); //VinculoPerfilUsuarioViewModel VPUVM = new VinculoPerfilUsuarioViewModel(); //VPUVM.UsuarioID = uID; //VPUVM.PerfilID = novaPessoa.PerfilID; RBAC_Link_Usuario_Perfil linkUP = new RBAC_Link_Usuario_Perfil(); linkUP.Usuario_ID = uID; linkUP.Perfil_ID = novaPessoa.PerfilID; _roleStore.AddUsuarioPerfil(linkUP); return(RedirectToAction("RegistrarDocumento", "Funcionario", new { id = pID })); } PopulatePerfilDropDownList(novaPessoa.PerfilID); return(View(novaPessoa)); }
public bool Patch(SaveParams sp) { string token = Request.Headers["Authorization"]; int userid = new SecurityMethods().ParseToken(token); DPInputData a = DpDataBase.Inputs.First(p => p.NAME == sp.name && p.UserId == userid); a.NAME = sp.name; a.InputIndicators = sp.dpi.InputIndicators; a.InputData2 = sp.dpi.InputData2; DpDataBase.Inputs.Attach(a); DpDataBase.SaveChanges(); return(true); }
/// <summary> /// Checks if the license key file has been modified by an unauthorized person. /// This method will only return true if the license key information is exactly /// the same as the one that was provided and signed by SKM. /// </summary> /// <param name="rsaPublicKey"></param> /// <returns>Returns true if the signature is valid. False otherwise.</returns> private static bool IsLicenceseKeyGenuine(this LicenseKey licenseKey, string rsaPublicKey) { if (licenseKey?.RawResponse != null) { var license = LicenseKey.FromResponse(rsaPublicKey, licenseKey.RawResponse); if (license == null) { return(false); } return(license.Equals(licenseKey)); } if (licenseKey?.Signature != "") { var prevSignature = licenseKey.Signature; try { licenseKey.Signature = ""; var rawResult = licenseKey.AsDictionary(); #if NET40 || NET46 || NET35 || NET47 || NET471 || NET45 RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048); rsa.FromXmlString(rsaPublicKey); #else RSA rsa = RSA.Create(); rsa.ImportParameters(SecurityMethods.FromXMLString(rsaPublicKey)); #endif byte[] signature = Convert.FromBase64String(prevSignature); // the signature should not be included into the signature :) #if NET40 || NET46 || NET35 || NET47 || NET471 || NET45 return(rsa.VerifyData(HelperMethods.GetBytes(String.Join(",", rawResult.Where(x => x.Key != "RawResponse").Select(x => x.Value).ToArray())), "SHA256", signature)); #else return(rsa.VerifyData(HelperMethods.GetBytes(String.Join(",", rawResult.Where(x => x.Key != "RawResponse").Select(x => x.Value))), signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)); #endif } catch { } finally { licenseKey.Signature = prevSignature; } } return(false); }
public string Post(UserRegistrition ur) { //Если такой логин уже зареган if (db.Users.FirstOrDefault(user => user.Login == ur.Login) != null) { return("Такой логин уже существует"); } RegistrationData rd = SecurityMethods.DBWrapper(ur); rd.Token = SecurityMethods.CreateToken(rd); db.Users.Add(rd); db.SaveChanges(); return("Пользователь успешно создан"); }
public IActionResult UpdateUser(string Id) { var userList = GetUserList(); var user = userList.Where(c => c.Id.Trim().Equals(Id.Trim())).FirstOrDefault(); user.Password = SecurityMethods.Decrypt(user.Password); UserModel userModel = new UserModel() { Id = user.Id, FirstName = user.FirstName, LastName = user.LastName, UserName = user.UserName, Password = user.Password, Authority = user.Authority, IsDelete = false }; return(View("UpdateUser", userModel)); }
/// <summary> /// Creates a license key from a <see cref="RawResponse"/> object that can be obtained when calling /// <see cref="Key.Activate(string, int, string, string, bool, int, int)"/>. /// </summary> public static LicenseKey FromResponse(string RSAPubKey, RawResponse response) { if (response == null || response.Result == ResultType.Error) { return(null); } var licenseBytes = Convert.FromBase64String(response.LicenseKey); var signatureBytes = Convert.FromBase64String(response.Signature); bool verificationResult = false; try { #if NET40 || NET46 || NET35 || NET47 || NET471 RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048); rsa.FromXmlString(RSAPubKey); #else RSA rsa = RSA.Create(); rsa.ImportParameters(SecurityMethods.FromXMLString(RSAPubKey)); #endif #if NET40 || NET46 || NET35 || NET47 || NET471 verificationResult = rsa.VerifyData(licenseBytes, "SHA256", signatureBytes); #else verificationResult = rsa.VerifyData(licenseBytes, signatureBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); #endif } catch (Exception ex) { } if (!verificationResult) { return(null); } var license = JsonConvert.DeserializeObject <LicenseKeyPI>(System.Text.UTF8Encoding.UTF8.GetString(licenseBytes)).ToLicenseKey(); license.RawResponse = response; return(license); }
[HttpPost] // Контроллер для принятия и сейва входных параметров :) public bool Post([FromBody] SaveParams sp) { string token = Request.Headers["Authorization"]; int userid = new SecurityMethods().ParseToken(token); if (DpDataBase.Inputs.Where(p => p.UserId == userid).Select(x => x.NAME).ToList().Contains(sp.name)) { return(false); } var dataInput = new DPInputData() { UserId = userid, NAME = sp.name, InputIndicators = sp.dpi.InputIndicators, InputData2 = sp.dpi.InputData2 }; DpDataBase.Inputs.Add(dataInput); DpDataBase.SaveChanges(); return(true); }
public OperationStatus ChangePassword(int usuarioID, AlterarSenhaViewModel model) { using (NimbusAcad_DB_Entities db = new NimbusAcad_DB_Entities()) { var usuario = db.RBAC_Usuario.Find(usuarioID); if (usuario != null) { string newSalt = SecurityMethods.GenerateSalt(); string newEncrypted = SecurityMethods.HashPasswordPBKDF2(model.Senha, newSalt); usuario.Senha_Hash = newEncrypted; usuario.Salt = newSalt; db.Entry(usuario).State = EntityState.Modified; db.SaveChanges(); return(OperationStatus.Success); } else { return(OperationStatus.Failure); } } }
public string ForgotPassword(int usuarioID) { using (NimbusAcad_DB_Entities db = new NimbusAcad_DB_Entities()) { var usuario = db.RBAC_Usuario.Find(usuarioID); if (usuario != null) { string newSalt = SecurityMethods.GenerateSalt(); string newToken = SecurityMethods.GenerateTempTokenAccess(); string newTokenEncrypted = SecurityMethods.HashPasswordPBKDF2(newToken, newSalt); usuario.Senha_Hash = newTokenEncrypted; usuario.Salt = newSalt; db.Entry(usuario).State = EntityState.Modified; db.SaveChanges(); return(newToken); } else { return(string.Empty); } } }
public static string GetHashPassword(string userName, string password) { return(SecurityMethods.Hashing(userName, password)); }
public static void Initialise(TestContext testcontext) { SecuritySettings = (SecuritySection)ConfigurationManager.GetSection("passwordPolicies"); security = new SecurityMethods(); }
protected override bool ReleaseHandle() { SecurityMethods.LsaClose(handle); return(true); }
/// <summary> /// This method will access the license keys that belong to the user by asking them to /// login into their account and authorize this application to get a token that will /// return them. In rare cases, we may get a successful authorization but not successful /// retrieval of license keys. In this case, the value tuple that is returned by this /// method will contain a token (Item3/licenseKeyToken). Next time you try to repeat /// the attempt, pass in the returned token into "existingToken" parameter. /// </summary> /// <param name="machineCode">The machine code you want to authorize.</param> /// <param name="token">The token to access the "GetToken" method.</param> /// <param name="appName">A user friendly name of your application.</param> /// <param name="tokenExpires">Sets the number of days the token should be valid.</param> /// <param name="RSAPublicKey">The RSA public key can be found here: /// https://app.cryptolens.io/User/Security </param> /// <param name="existingToken">If you have already called this method once /// and received a token as a result (despite an error), you can enter it here /// to avoid duplicate authorization by the user.</param> public static GetLicenseKeysResult GetLicenseKeys(string machineCode, string token, string appName, int tokenExpires, string RSAPublicKey, string existingToken = null) { string tokenNew = existingToken; if (string.IsNullOrEmpty(existingToken)) { var auth = AuthMethods.CreateAuthRequest(new Scope { GetLicenseKeys = true }, appName, machineCode, AuthMethods.GetTokenId(token), tokenExpires); for (int i = 0; i < 100; i++) { try { tokenNew = AuthMethods.GetToken(auth, token); } catch (Exception ex) { } if (tokenNew != null) { break; } Thread.Sleep(3000); } if (tokenNew == null) { return(new GetLicenseKeysResult { Error = "Timeout reached. The user took too long time to authorize this request." }); } } GetLicenseKeysResultLinqSign result = null; try { result = HelperMethods.SendRequestToWebAPI3 <GetLicenseKeysResultLinqSign>(new GetLicenseKeysModel { Sign = true, MachineCode = machineCode }, "/User/GetLicenseKeys", tokenNew); } catch (Exception ex) { return(new GetLicenseKeysResult { LicenseKeyToken = tokenNew, Error = "Could not contact SKM: " + ex.InnerException }); } if (result == null || result.Result == ResultType.Error) { return(new GetLicenseKeysResult { LicenseKeyToken = tokenNew, Error = "An error occurred in the method: " + result?.Message }); } var licenseKeys = Convert.FromBase64String(result.Results); var activatedMachines = Convert.FromBase64String(result.ActivatedMachineCodes); var date = BitConverter.GetBytes(result.SignDate); if (!BitConverter.IsLittleEndian) { Array.Reverse(date); } var toSign = licenseKeys.Concat(activatedMachines.Concat(date)).ToArray(); // only if sign enabled. #if NET40 || NET46 || NET35 using (var rsaVal = new RSACryptoServiceProvider()) { rsaVal.FromXmlString(RSAPublicKey); if (!rsaVal.VerifyData(toSign, "SHA256", Convert.FromBase64String(result.Signature))) { // verification failed. return(new GetLicenseKeysResult { LicenseKeyToken = tokenNew, Error = "Verification of the signature failed." }); } } #else using (var rsaVal = RSA.Create()) { rsaVal.ImportParameters(SecurityMethods.FromXMLString(RSAPublicKey)); if (!rsaVal.VerifyData(toSign, Convert.FromBase64String(result.Signature), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) { // verification failed. return(new GetLicenseKeysResult { LicenseKeyToken = tokenNew, Error = "Verification of the signature failed." }); } } #endif var machineCodes = JsonConvert.DeserializeObject <List <String> >(System.Text.UTF8Encoding.UTF8.GetString(activatedMachines)); if (machineCodes?.Count != 0 && !machineCodes.Contains(machineCode)) { return(new GetLicenseKeysResult { LicenseKeyToken = tokenNew, Error = "This machine code has not been authorized." }); } return(new GetLicenseKeysResult { Licenses = JsonConvert.DeserializeObject <List <KeyInfoResult> >(System.Text.UTF8Encoding.UTF8.GetString((licenseKeys))).Select(x => x.LicenseKey).ToList(), LicenseKeyToken = tokenNew }); }
private static string GetDummyRightName(SecurityEntityTypes entityType, SecurityMethods method) => $"{Enum.GetName(entityType.GetType(), entityType)}_{Enum.GetName(method.GetType(), method)}";
public FrontUser Post(UserAuth user) { var trueuser = db.Users.FirstOrDefault(dbUser => user.Login == dbUser.Login && SecurityMethods.GetSHA1Hash(user.Password) == dbUser.Password); if (trueuser == null) { FrontUser fr = new FrontUser(trueuser); fr.isAuth = false; return(fr); } FrontUser ddd = new FrontUser(trueuser); ddd.isAuth = true; return(ddd); }
public void Ensure(SecurityEntityTypes contact, SecurityMethods create) { }
protected override bool ReleaseHandle() { SecurityMethods.LsaFreeMemory(handle); return(true); }