├── .gitignore ├── LICENSE ├── README.md ├── http.json └── mythic2modrewrite.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Threat Express 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mythic2modrewrite 2 | Generate Apache mod_rewrite rules for Mythic C2 profiles 3 | 4 | **Work in progress** 5 | Currently only supports ruleset generation for the "http" C2 profile type 6 | 7 | This project converts a Mythic payload config to a functional mod_rewrite `.htaccess` to support HTTP reverse proxy redirection to a Cobalt Strike teamserver. The use of reverse proxies provides protection to backend C2 servers from profiling, investigation, and general internet background radiation. 8 | 9 | As of [Mythic 2.2.12](https://bloodhoundhq.slack.com/archives/CHG769BL2/p1626822877094500) redirect rule creation is enabled automatically for the `http` C2 profile. Futhermore, you can now [add these to your own custom C2 profiles](https://docs.mythic-c2.net/customizing/c2-related-development/c2-profile-code/server-side-coding/redirect-rules). 10 | 11 | ***Note***: You should test and tune the output as needed before deploying, but this script should handle the heavy lifting. 12 | 13 | ## Features 14 | 15 | - Mythic "http" C2 Profile config parsing 16 | 17 | 18 | ## Quick start 19 | 20 | A `http.json` config example is included for a quick test. 21 | 22 | 0) Export Payload Config - Once you generate a Mythic agent with whatever config you want, you can go to the "Created Payloads" page, select the dropdown next to your payload, and click "Export Payload Config". You'll get something like: 23 | ```{ 24 | "payload_type": "apfell", 25 | "c2_profiles": [ 26 | { 27 | "c2_profile": "http", 28 | "c2_profile_parameters": { 29 | "callback_port": "80", 30 | "killdate": "2022-06-23", 31 | "encrypted_exchange_check": "T", 32 | "callback_jitter": "23", 33 | "headers": [ 34 | { 35 | "name": "User-Agent", 36 | "key": "User-Agent", 37 | "value": "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko", 38 | "custom": false 39 | }, 40 | { 41 | "name": "Host", 42 | "key": "Host", 43 | "value": "asdf", 44 | "custom": false 45 | }, 46 | { 47 | "name": "*", 48 | "key": "my key", 49 | "value": "my value", 50 | "custom": true 51 | } 52 | ], 53 | "AESPSK": "aes256_hmac", 54 | "callback_host": "https://domain.com", 55 | "get_uri": "index", 56 | "post_uri": "data", 57 | "query_path_name": "q", 58 | "proxy_host": "", 59 | "proxy_port": "", 60 | "proxy_user": "", 61 | "proxy_pass": "", 62 | "callback_interval": "10" 63 | } 64 | } 65 | ], 66 | "commands": [ 67 | "cat",..... 68 | ``` 69 | 1) Run the script against a payload config 70 | 2) Save the output to `.htaccess` on your redirector 71 | 3) Modify as needed 72 | 4) Reload/restart the web server 73 | 74 | ## Apache mod_rewrite Example Usage 75 | 76 | ``` 77 | python3 mythic2modrewrite.py -i http.json -c https://TEAMSERVER -r https://GOHERE > /var/www/html/.htaccess 78 | #### Save the following as .htaccess in the root web directory (i.e. /var/www/html/.htaccess) 79 | 80 | ######################################## 81 | ## .htaccess START 82 | RewriteEngine On 83 | ## Uncomment to enable verbose debugging in /var/logs/apache2/error.log 84 | # LogLevel alert rewrite:trace5 85 | ## (Optional) 86 | ## Scripted Web Delivery 87 | ## Uncomment and adjust as needed 88 | #RewriteCond %{REQUEST_URI} ^/css/style1.css?$ 89 | #RewriteCond %{HTTP_USER_AGENT} ^$ 90 | #RewriteRule ^.*$ "http://TEAMSERVER%{REQUEST_URI}" [P,L] 91 | 92 | 93 | ## C2 Traffic (HTTP-GET, HTTP-POST, HTTP-STAGER URIs) 94 | ## Logic: If a requested URI AND the User-Agent matches, proxy the connection to the Teamserver 95 | ## Consider adding other HTTP checks to fine tune the check. (HTTP Cookie, HTTP Referer, HTTP Query String, etc) 96 | ## Refer to http://httpd.apache.org/docs/current/mod/mod_rewrite.html 97 | ## Profile URIs 98 | RewriteCond %{REQUEST_URI} ^(/include/template/isx.php.*|/wp06/wp-includes/po.php.*|/wp08/wp-includes/dtcla.php.*|/modules/mod_search.php.*|/blog/wp-includes/pomo/src.php.*|/includes/phpmailer/class.pop3.php.*|/api/516280565958.*|/api/516280565959.*)$ 99 | ## Profile UserAgent 100 | RewriteCond %{HTTP_USER_AGENT} "Mozilla/5.0 \(Windows; U; MSIE 7.0; Windows NT 5.2\) Java/1.5.0_08" 101 | RewriteRule ^.*$ "https://TEAMSERVER%{REQUEST_URI}" [P,L] 102 | 103 | ## Redirect all other traffic here (Optional) 104 | RewriteRule ^.*$ HTTPS://GOHERE/ [L,R=302] 105 | 106 | ## .htaccess END 107 | ######################################## 108 | ``` 109 | ## Apache Rewrite Setup and Tips 110 | 111 | ### Enable Rewrite and Proxy 112 | apt-get install apache2 113 | a2enmod rewrite headers proxy proxy_http ssl cache 114 | a2dismod -f deflate 115 | service apache2 reload 116 | 117 | **Note:** https://bluescreenofjeff.com/2016-06-28-cobalt-strike-http-c2-redirectors-with-apache-mod_rewrite/ 118 | "e0x70i pointed out in the comments below that if your Cobalt Strike Malleable C2 profile contains an Accept-Encoding header for gzip, your Apache install may compress that traffic by default and cause your Beacon to be unresponsive or function incorrectly. To overcome this, disable mod_deflate (via a2dismod deflate and add the No Encode ([NE]) flag to your rewrite rules. (Thank you, e0x70i!)" 119 | 120 | ### Enable SSL support 121 | 122 | Ensure the following entries are in the site's config (i.e. `/etc/apache2/available-sites/*.conf`) 123 | 124 | # Enable SSL 125 | SSLEngine On 126 | # Enable SSL Proxy 127 | SSLProxyEngine On 128 | # Trust Self-Signed Certificates generated by CobaltStrike 129 | SSLProxyVerify none 130 | SSLProxyCheckPeerCN off 131 | SSLProxyCheckPeerName off 132 | SSLProxyCheckPeerExpire off 133 | ### .HTACCESS 134 | 135 | If you plan on using mod_rewrite in .htaccess files (instead of the site's config file), you also need to enable the use of `.htaccess` files by changing `AllowOverride None` to `AllowOverride All`. For all websites, edit `/etc/apache2/apache.conf` 136 | 137 | 138 | Options FollowSymLinks MultiViews 139 | AllowOverride All 140 | Order allow,deny 141 | allow from all 142 | 143 | 144 | Finally, restart apache once more for good measure. 145 | 146 | `service apache2 restart` 147 | 148 | ### Troubleshooting 149 | 150 | If you need to troubleshoot redirection rule behavior, enable detailed error tracing in your site's configuration file by adding the following line. 151 | 152 | `LogLevel alert rewrite:trace5` 153 | 154 | Next, reload apache, and monitor `/var/log/access.log` `/var/log/error.log` to see which rules are matching. 155 | 156 | ---------------------------------------------- 157 | 158 | 159 | ## Final Thoughts 160 | 161 | Once redirection is configured and functioning, ensure your C2 servers only allow ingress from the redirector and your trusted IPs (VPN, office ranges, etc). 162 | 163 | Consider adding additional redirector protections using GeoIP restrictions (mod_maxmind) and blacklists of bad user agents and IP ranges. Thanks to [@curi0usJack](https://twitter.com/curi0usJack) for the ideas. 164 | 165 | ## References 166 | 167 | - [Joe Vest and Andrew Chiles - cs2modrewrite.py blog post](https://posts.specterops.io/automating-apache-mod-rewrite-and-cobalt-strike-malleable-c2-profiles-d45266ca642) 168 | 169 | - [@bluescreenofjeff - Cobalt Strike HTTP C2 Redirectors with Apache mod_rewrite](https://bluescreenofjeff.com/2016-06-28-cobalt-strike-http-c2-redirectors-with-apache-mod_rewrite/) 170 | 171 | - [Adam Brown - Resilient Red Team HTTPS Redirection Using Nginx](https://coffeegist.com/security/resilient-red-team-https-redirection-using-nginx/) 172 | 173 | - [Apache - Apache mod_rewrite Documentation](http://httpd.apache.org/docs/current/mod/mod_rewrite.html) 174 | -------------------------------------------------------------------------------- /http.json: -------------------------------------------------------------------------------- 1 | { 2 | "payload_type": "apfell", 3 | "c2_profiles": [ 4 | { 5 | "c2_profile": "http", 6 | "c2_profile_parameters": { 7 | "callback_port": "80", 8 | "killdate": "2022-06-23", 9 | "encrypted_exchange_check": "T", 10 | "callback_jitter": "23", 11 | "headers": [ 12 | { 13 | "name": "User-Agent", 14 | "key": "User-Agent", 15 | "value": "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko", 16 | "custom": false 17 | }, 18 | { 19 | "name": "Host", 20 | "key": "Host", 21 | "value": "asdf", 22 | "custom": false 23 | }, 24 | { 25 | "name": "*", 26 | "key": "my key", 27 | "value": "my value", 28 | "custom": true 29 | } 30 | ], 31 | "AESPSK": "aes256_hmac", 32 | "callback_host": "https://domain.com", 33 | "get_uri": "index", 34 | "post_uri": "data", 35 | "query_path_name": "q", 36 | "proxy_host": "", 37 | "proxy_port": "", 38 | "proxy_user": "", 39 | "proxy_pass": "", 40 | "callback_interval": "10" 41 | } 42 | } 43 | ], 44 | "commands": [ 45 | "cat", 46 | "cd", 47 | "chrome_bookmarks", 48 | "chrome_js", 49 | "chrome_tabs", 50 | "clipboard", 51 | "current_user", 52 | "download", 53 | "exit", 54 | "get_config", 55 | "hostname", 56 | "iTerm", 57 | "ifconfig", 58 | "jscript", 59 | "jsimport", 60 | "jsimport_call", 61 | "launchapp", 62 | "list_apps", 63 | "list_users", 64 | "load", 65 | "ls", 66 | "persist_emond", 67 | "persist_folderaction", 68 | "persist_launch", 69 | "persist_loginitem_allusers", 70 | "plist", 71 | "prompt", 72 | "pwd", 73 | "rm", 74 | "run", 75 | "screenshot", 76 | "security_info", 77 | "shell", 78 | "sleep", 79 | "spawn_download_cradle", 80 | "spawn_drop_and_execute", 81 | "system_info", 82 | "terminals_read", 83 | "terminals_send", 84 | "upload" 85 | ], 86 | "selected_os": "macOS", 87 | "tag": "Created on...", 88 | "wrapper": false, 89 | "build_parameters": [], 90 | "filename": "apfell.js" 91 | } -------------------------------------------------------------------------------- /mythic2modrewrite.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # mythic2modrewrite.py 3 | 4 | ## Title: mythic2modrewrite.py 5 | ## Author: Joe Vest, Andrew Chiles 6 | 7 | import argparse 8 | import sys 9 | import re 10 | import json 11 | 12 | description = ''' 13 | Python 3.0+ 14 | Converts Mythic (2.2.0+) profiles to Apache mod_rewrite .htaccess file format by using the User-Agent and URI Endpoint to create rewrite rules. 15 | ''' 16 | 17 | parser = argparse.ArgumentParser(description=description) 18 | parser.add_argument('-i', dest='inputfile', help='C2 Profile file', required=True) 19 | parser.add_argument('-c', dest='c2server', help='C2 Server (http://teamserver)', required=True) 20 | parser.add_argument('-r', dest='redirect', help='Redirect to this URL (http://google.com)', required=True) 21 | parser.add_argument('-o', dest='out_file', help='Write .htaccess contents to target file', required=False) 22 | 23 | args = parser.parse_args() 24 | 25 | # Make sure we were provided with vaild URLs 26 | # https://stackoverflow.com/questions/7160737/python-how-to-validate-a-url-in-python-malformed-or-not 27 | regex = re.compile( 28 | r'^(?:http|ftp)s?://' # http:// or https:// 29 | r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... 30 | r'localhost|' #localhost... 31 | r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip 32 | r'(?::\d+)?' # optional port 33 | r'(?:/?|[/?]\S+)$', re.IGNORECASE) 34 | 35 | if re.match(regex, args.c2server) is None: 36 | parser.print_help() 37 | print("[!] c2server is malformed. Are you sure {} is a valid URL?".format(args.c2server),file=sys.stderr) 38 | sys.exit(1) 39 | 40 | if re.match(regex, args.redirect) is None: 41 | parser.print_help() 42 | print("[!] redirect is malformed. Are you sure {} is a valid URL?".format(args.redirect),file=sys.stderr) 43 | sys.exit(1) 44 | 45 | # Read in the Mythic Payload Config 46 | configFile = open(args.inputfile,"r") 47 | contents = configFile.read() 48 | contents = json.loads(contents) 49 | 50 | # Errors 51 | errorfound = False 52 | errors = "\n##########\n[!] ERRORS\n" 53 | 54 | # Make sure a C2 profile exists in the payload config before we continue 55 | if "c2_profiles" in contents: 56 | c2profiles = contents["c2_profiles"] 57 | else: 58 | print("[!] Could not find a c2profile in the provided JSON file",file=sys.stderr) 59 | sys.exit(1) 60 | 61 | # Iterate over C2 profiles 62 | # for profile in c2profiles: 63 | 64 | # Pick the first item in the list of c2profiles 65 | profile = c2profiles[0]["c2_profile_parameters"] 66 | 67 | print("#### C2 Profile Details\n#{}\n".format(str(profile))) 68 | 69 | # Get User-Agent 70 | if "headers" in profile: 71 | for header in profile["headers"]: 72 | if header["name"] == "User-Agent": 73 | ua = header["value"] 74 | else: 75 | ua = '' 76 | errors += "[!] User-Agent Not Found\n" 77 | errorfound = True 78 | 79 | uris = [] 80 | 81 | # Get all profile URIs 82 | if "get_uri" in profile: 83 | uris.append("/" + profile["get_uri"]) 84 | # Remove any duplicate URIs 85 | else: 86 | uris = "" 87 | errors += "[!] No GET URI found\n" 88 | errorfound = True 89 | 90 | if "post_uri" in profile: 91 | uris.append("/" + profile["post_uri"]) 92 | 93 | else: 94 | uris = "" 95 | errors += "[!] No POST URI found\n" 96 | errorfound = True 97 | 98 | # Create UA in modrewrite syntax. No regex needed in UA string matching, but () characters must be escaped 99 | ua_string = ua.replace('(','\(').replace(')','\)') 100 | 101 | # Create URI string in modrewrite syntax. "*" are needed in regex to support GET and uri-append parameters on the URI 102 | uris_string = ".*|".join(uris) + ".*" 103 | 104 | 105 | htaccess_template = ''' 106 | ######################################## 107 | ## .htaccess START 108 | RewriteEngine On 109 | 110 | ## C2 Traffic (HTTP-GET, HTTP-POST, HTTP-STAGER URIs) 111 | ## Logic: If a requested URI AND the User-Agent matches, proxy the connection to the Teamserver 112 | ## Consider adding other HTTP checks to fine tune the check. (HTTP Cookie, HTTP Referer, HTTP Query String, etc) 113 | ## Refer to http://httpd.apache.org/docs/current/mod/mod_rewrite.html 114 | ## Only allow GET and POST methods to pass to the C2 server 115 | RewriteCond %{{REQUEST_METHOD}} ^(GET|POST) [NC] 116 | ## Profile URIs 117 | RewriteCond %{{REQUEST_URI}} ^({uris})$ 118 | ## Profile UserAgent 119 | RewriteCond %{{HTTP_USER_AGENT}} "{ua}" 120 | RewriteRule ^.*$ "{c2server}%{{REQUEST_URI}}" [P,L] 121 | 122 | ## Redirect all other traffic here 123 | RewriteRule ^.*$ {redirect}/? [L,R=302] 124 | 125 | ## .htaccess END 126 | ######################################## 127 | ''' 128 | print("#### Save the following as .htaccess in the root web directory") 129 | print("## Profile User-Agent Found:") 130 | print("# {}".format(ua)) 131 | print("## Profile URIS Found ({}):".format(str(len(uris)))) 132 | for uri in uris: 133 | print("# {}".format(uri)) 134 | 135 | htaccess = htaccess_template.format(uris=uris_string, ua=ua_string, c2server=args.c2server, redirect=args.redirect) 136 | if args.out_file: 137 | with open(args.out_file, 'w') as outfile: 138 | outfile.write(htaccess) 139 | else: 140 | print(htaccess) 141 | 142 | # Print Errors Found 143 | if errorfound: 144 | print(errors, file=sys.stderr) 145 | --------------------------------------------------------------------------------