Welcome to the CompTIA PenTest+ PT0-001 study notes. You know the type of study guides to expect by now. Prepare for a wall of formatted text.

The information in this guide is organized by the PT0-001 exam objectives and contains information from Michael Solomon’s LinkedIn Learning course (outdated, but good), internet searches, and my own experience.

This certification heavily leans towards practical experience. In addition to reviewing notes, you need to practice! You don’t have to memorize a whole lot of random computer facts, but you still have prep work to do!

I encourage you to follow along with the activities as you learn the course. I wrote up a separate Home Lab Setup guide that details Michael’s practical activities. I also fix and update a good portion of it so that it is relevant to you.

Treat these notes as a review. You should be shaking your head yes as you go through these notes. Learn and retain as many concepts as possible. There’s no shortcut to being a security pro. Put in the work and do great.

Let me know how you do. Good luck!

1. Planning and Scoping

Take a look at the Penetration Testing Execution Standard. There are 7 defined sections of a penetration test:

  1. Pre-engagement interactions
  2. Intelligence gathering
  3. Theat modeling
  4. Vulnerability analysis
  5. Exploitation
  6. Post exploitation
  7. Reporting

Don’t skip steps as you may miss an exploit or scope the entire test improperly. It is easy to waste time and effort on a big project. Experience is beneficial but you need Project management skills. They are important as they keep pen tests on track. Every environment will be different.

Why is there a pentest? Learn the rules of engagement. What are the schedule or temporal restrictions? Who is the target audience? Learn the overall goal and plan accordingly.

Scheduling is very important. A schedule lays out restrictions and further rules of engagement.

What are off limits? Find out how much work you have to do and don’t do more than that. Anything extra, no matter how small, is scope creep. Clearly define the scope to avoid scope creep. What is the technical, physical, or personnel scope? What are the target limits (inclusions, invasiveness, etc.)?

There are risks with pentesting. There is access to confidential information, crashing devices, services, whole servers, corruption, and/or degradation of performance. TOS, regulation, legislation violations.

Learn who to communicate with. Don’t only communicate when things go poorly. Start, stop, finishing milestones are common triggers. Learn other communication expectations, content, triggers, and frequency. Communicate as much as they want.

Know who is sponsoring the pen test and why. What does each party provide regarding resources? Are your activities known or secret?

When does the engagement begin?

Protect the confidentiality of findings. Do not have a lack of administrative oversight.

What does each party (you provide and what does the client) provide?

Don’t underestimate the impact of an accurate budget. How much will each section of the test cost? Every task in the test should have a value. Want to add more tests? That will cost more. One of the most important factors. Directly impacts available resources and time.

Document expected impact of pen tests. provide an estimate of remediation activities. The result of testing. Report vulnerabilities. Report expectations to stakeholders. Estimate of time required to complete remediation recommendations. How should the client respond?

Disclaimers. This is a point in time assessment. It’s only valid now. Comprehensiveness – enterprise, division, department, etc.

Specify any technical constraints. Any technical limitations that reduce test scope. Production (live) Components. Out-of-service devices. Can’t access – physical, geographic access limitations. Legal, regulatory, out of scope.

Support Resources

Black box testers generally don’t have access. Find out if any internal resources are available. Look for artifacts from application development. Also, look for any deployment or support documents.

WSDL/WADL – web services, application description language. XML file with lots of info about web service/application and its interface requirements. Input and output specs.

SOAP project file. Simple Object Access Protocol – used to exchange info for web services. Project file provides low level web service interface details (input/output/server info). Not exposed to the public. Used by developers in a development environment.

  • SDK documentation
    • Software Development Kit docs help provide info on tools used to develop software.
    • Reveals software libraries in use.
  • Swagger document
    • Popular open source framework for developing REST services.
    • Document can provide internal info on REST services exposed to clients.
  • XSD
    • XML Schema Definition – defines XML document content.
  • Sample application requests
    • Well-formed requests, generally to web services.
    • Useful when testing web services/applications of all types.
  • Architectural diagrams
    • Diagrams of networks and connected devices.
    • Helpful when determining targets to attack.
      • May provide physical info too.

Common Contract Types

Pay attention to localization restrictions.

Always get written permission. Find out if you need 3rd party permission as well.

  • Explain key legal concepts.
  • Contracts
    • Statement of Work (SOW)
      • Clearly states what tasks are to be accomplished during an engagement.
    • Master Service Agreement (MSA)
      • High level contract between a service provider and a client that specifies details of the business arrangement.
    • Non-Disclosure Agreement (NDA)
      • Agreement that defines confidential material and restrictions on use and sharing sensitive information with other parties.
  • Export restrictions – restrictions on shipments, transfer of technology, or services outside the U.S.
  • National or local restrictions.
    • Differ among countries.
    • Local customs differ.
  • Corporate policies
    • Differ between most organizations.
  • Obtain signature from proper signing authority.
    • “Get out of jail free” card.
    • Pen tests can reveal sensitive or confidential information.
    • Activities may be illegal without proper permission.
    • Signed permission makes you a white hat pen tester.
  • Third-party authorization when necessary.
    • Ex: from a Cloud service provider.
    • Get permission for any outside resources used.
      • Cloud, Internet (ISP usage), etc.

Types of Assessment

  • Goals-based
    • Goals set up front, testers work to fulfill goals.
  • Objective-based
    • Define a resource to attack.
    • Tests use all angles to attack protected objectives.
  • Compliance-based
    • Mandated by standard, regulation, or legislation.
    • Ex: PCI-DSS

Teams

  • Red team
    • Typically internal.
    • A single compromise is success.
    • Ongoing
  • Blue team
    • Defense against the red team.

Special Considerations

Premerger

  • Part of due diligence prior to mergers.
  • Used to harmonize security efforts.

Supply chain

  • Partners often provide software and/or hardware to interface with an organization.
  • Weaknesses in interfaces can provide unauthorized access.
    • Especially from trusted vendors.

Target Selection

  • Internal (on-site vs. off-site)
  • External
  • First-party vs. third-party hosted
  • Physical
  • Users
  • SSIDs
  • Applications

White-listed

  • No one can access resources unless specifically granted.

Black-listed

  • Everyone can access unless specifically blocked.

Security exceptions

  • IPS (Intrusion Prevention System)/WAF (Web application firewall) whitelist.
  • NAC (Network Access Control)
  • Certificate pinning (public key pinning).
  • Company’s policies
    • Explore company policies to learn about security considerations.

Strategy

Black box

  • Zero prior information.
  • Most similar to real attacker.
  • Test is generally a surprise to all internal personnel.

White box

  • Full access to internal information.
  • Simulates insider attack.

Gray box

  • Some internal information available.
  • Consistent with an insider attack with limited access.

Risk acceptance

  • Service can be interrupted.
  • Devices/servers can become unresponsive.

How much risk is the client willing to accept?

  • Client has identified risks.
  • Acceptance: willing to accept risks, based on likelihood and impact.

Tolerance to impact

  • If risk is realized, what is client’s tolerance to the result?
  • How much disruption is tolerable?

Scheduling

  • When can/should test be run?
  • Who should be notified?
  • When must tests be completed?

Scope creep – common in nearly all projects.

  • Client requests additional tasks after SOW is signed.
  • Many may seem “doable.”
  • Takes resources away from core SOW tasks.
  • Must get authorization for any SOW modifications.

Threat actors

Adversary tier – what role should the pen tester assume?

  • APT (Advanced Persistent Threat)
  • Script kiddies
  • Hacktivist
  • Insider threat

Capabilities

  • What resources does the attacker(s) have?
  • Organized and sponsored attackers have more.
  • Equipment and sophistication

Intent

  • Power/revenge
  • Status/validation
  • Monetary gain
  • Ideology

Threat model

  • Gather information and identify assets.
  • Rank pertinent threats.
  • Map threats to assets.

Compliance based assessment

  • Password policies
  • Data isolation
  • Key management
  • Limitations
  • Clearly defined objectives based on regulations.

2. Information Gathering and Vulnerability Identification

Scanning helps to determine what is “out there.”

  • Process of looking at some number of “things” to determine characteristics.
  • Commonly used in pen testing to uncover target vulnerabilities.
  • Don’t just scan for computers – look for all devices and services.

Many types of scan targets

  • Networks
  • Network devices
  • Computers
  • Applications/services

Enumeration

  • Counting the detected instances of some target class.

Pen testing target classes

  • Hosts
  • Networks
  • Domains
  • Users
  • Groups
  • Network shares
  • Web pages
  • Applications
  • Services
  • Tokens
  • Social networking sites

Start collecting and classifying target information.

  • Use more than just utilities that scan networks.
  • Nmap is the most common tool you’ll see on the exam.
  • Know how to use nmap and what the main options do.
  • Be able to explain nmap output.
  • Know the type of information you can get from a Whois search.

Packet Investigation

  • Creating specific network packets to gather information or carry out attacks.
  • Tools – netcat, nc, ncat, hping.

Packet inspection

  • Capturing and analyzing network packets.
  • Wireshark

netcat, nc, ncat, and hping can all help craft packets.

Crafted packets can help determine where and what a target is.

Wireshark is a common packet capture and inspection tool.

Inspecting Targets

Fingerprinting

  • Determining OS type and version a target is running.

Cryptography

  • Inspecting certificates.

Eavesdropping

  • RF communication monitoring.

Sniffing

Wireshark allows you to inspect network traffic.

Useful to see what is being sent between nodes.

Practice examining network traffic in your lab.

Decompilation

Compiler – translates source code into executable instructions.

Decompiler – attempts to convert executable instructions back into source code.

  • Output is generally awkward to read at best.
    • Sometimes target is not a direct executable (i.e. Java).

Decompilers and debuggers can help to see what a program is doing.

Debugging

Running an executable in a controlled manner.

  • Debuggers make it easy to stop and examine memory at will.
  • Can reveal a program’s secrets and weaknesses.
  • Tools – windbg

Open Source Intelligence Gathering (OSINT)

Sources of research

  • CERT (Computer Emergency Response Team)
  • NIST (National Institute of Standards and Technology)
  • JPCERT (Japan’s CERT)

More sources of research

  • CAPEC (Common Attack Pattern Enumeration & Classification)
  • Full disclosure – Popular mailing list from the folks who brought us nmap
  • CVE (Common Vulnerabilities and Exposures)
  • CWE (Common Weakness Enumeration)

Lots of useful attack information is available online.

Vulnerability Scan

A structured approach to examining targets to identify known weaknesses.

  • Many different types.
  • Determine if any known weaknesses exist.

Use scan output to determine target vulnerabilities.

Credentialed vs. non-credentialed

  • Credentialed (authenticated) – accessing resources using valid credentials.
  • More detailed, accurate information.
  • Non-credentialed (non-authenticated) – anonymous access to exposed resources.
  • Fewer details, often used in early phases of attacks/tests.

Types of scans

Discovery scan – used to find potential targets.

  • Identity/info gathering early on.
  • nmap ping sweep
    • nmap –sP target

Full scan – scans ports, services, and vulnerabilities.

  • Full scan with fingerprinting
    • nmap –A target
    • Not stealthy
    • perl nikto.pl –h target
    • OpenVAS
    • Open-source version of Nessus.
    • Port scan
  • nmap –p ports target

Stealth scan – attempt to avoid tripping defensive control thresholds.

  • nmap –sS target

Compliance – scan for specific known vulnerabilities that would make a system non-compliant.

Container Security

  • Container – scaled-down VM.
  • Instances that run on top of base OS VM.
  • Docker, Puppet, Vagrant.

Application scan

  • Dynamic – target environment is running and responds to queries.
  • Static – scan input consists of post-execution data stores.

Scanning considerations

  • Time to run scans – approved schedule (planning).
  • Protocols used – largely dependent on target selection.
  • Network topology – network layout (diagram) of test targets.
  • Bandwidth limitations – tolerance to impact (affects availability).

Query throttling – slow down test iterations to avoid exceeding bandwidth.

  • nmap -T
  • Fragile systems/non-traditional assets.
  • How to avoid impacting fragile mission critical systems?

Analyze scan results

Asset categorization

  • Identify and rank assets by relative value.
  • Vulnerable assets with little value could be a waste of time.

Adjudication

  • Determine which results are valid.
  • False positives
    • Filter out false positives.

Prioritization of vulnerabilities

  • Highest impact vulnerabilities – ease of exploit vs. payoff.

Common themes

  • Vulnerabilities
  • Observations
  • Lack of best practices

Leveraging information to prepare for exploitation.

  • Map vulnerabilities to potential exploits.
  • Look up vulnerabilities found for possible exploits.
  • Nmap – vulners and vulscan scripts.
  • Metasploit (search vulnerability)

Prioritize activities in preparation for the penetration test.

Common Attack Techniques

  • Cross-compiling code – compile exploit for another OS.
  • Exploit modification – may need to modify for success of evasion.
  • Exploit chaining – compromise one device/system to gain access to another.
  • Proof-of-concept development – exploit development.

Social engineering

  • Help me
  • Urgent
  • Deceptive
    • Credential brute forcing
    • Enlightened Attacks
  • Dictionary
  • Rainbow table

Password cracking

Weaknesses in Specialized Systems

  • ICS (Industrial Control Systems)
    • Environmental conditions.
    • Exposure to real world (live) events.
  • SCADA (Supervisory Control and Data Acquisition)
  • Mobile – lack of updates, compromised settings, dangerous apps, etc.
  • IoT (Internet of Things) – default (weak) security (wide open).
  • Embedded
  • Computers embedded in other systems – IoT, automobiles, industrial devices, etc.

Point-of-sale system

  • Attractive due to connection to payment devices (cash, readers, etc.).

Biometrics – accuracy is still evolving

  • What if primary reader fails to detect?
  • What is the manual process?

Application containers

  • Containers and VMs are not foolproof sandboxes.
  • Compromising (breaking out) may allow access to external resources.

RTOS (Real-time operating system)

  • Designed to provide fast, lightweight services, not security.

Review

  • Efficient penetration testing depends on correlated information.
  • Structured approach to discovering target vulnerabilities.
  • Correlates known vulnerabilities with target characteristics.
  • Scans can be general (fin any weaknesses) or targeted (see if specific weaknesses exist).
  • Scans can range from quiet to very noisy.
  • Practice with various nmap scan options.
  • Use Nikto to perform your worn scans in the lab environment.
  • Try using OpenVAS to perform different scans in your lab.
  • Know how to determine if targets are physical machines or are virtualized (footprinting).
  • Be aware of client restrictions when running scans (bandwidth use, schedule, etc.).
  • Don’t waste time on results that have little value – focus on the most meaningful results.
  • Prioritize the highest impact vulnerabilities.
  • Understand the nmap timing option values (-T 0-5).
  • Be able to explain what actions nmap -A performs.
  • Know how to restrict nmap scans to specific ports.
  • A key step in pent test planning is to map vulnerabilities to potential exploits.
  • Use nmap scripts (vulners and vulscan) to find exploits for detected vulnerabilities.
  • Use metasploit to search for exploits.
  • Some exploits may need tweaking to work in your tests.
  • Be able to recognize exploit chaining.
  • Many exploits involve some social engineering.
  • Credential attacks are time consuming and are rarely carried out as pure brute force attacks.
  • Most credential attacks depend on good dictionaries.
  • Each pen tester must maintain username and password lists for credential attacks.
  • Start with good online resources and modify for your own purposes.
  • ICS and SCADA systems often lack current security patches.
  • Mobile and IoT devices are often configured for convenience over security.
  • Any device that handles payments is an attractive target.

3. Attacks and Exploits

Social engineering

  • Tricking or coercing people into violating security policy.
  • Depends on willingness to be helpful.
  • Human weaknesses can be leveraged.
  • May rely on technical aspects.
  • Bypasses access controls and most detection controls.

Social engineering is all about getting an authorized user to do your dirty work.

Relies on most peoples’ willingness to be helpful.

Successful social engineering can bypass nearly all technical controls.

Phishing

  • Phishing – people are contacted by a seemingly legitimate imposter in an attempt to extract sensitive information.
  • Spear phishing
  • SMS phishing
  • Voice phishing
  • Whaling

Phishing is attempting to get a valid user to click on a link to your exploit.

Spear phishing is all about targeting a specific individual.

Crafting a realistic email is crucial.

The goal is to get a user to click on the link you sent without too much prior thought.

More attacks and exploits

  • Elicitation – Gathering information about a system or environment from authorized users.
  • Business email compromise – Collecting information as if the attacker were an insider.
  • Interrogation – Conducting informal (mostly) interviews with specifically crafted questions to extract as much information as possible.
  • Impersonation – Pretending to be someone with authority, such as technical support.
  • Shoulder surfing – watching as someone enters a username, password, PIN, or other secret to satisfy access controls.

In-person social engineering often works because few people will confront someone face-to-face.

Motivation techniques – why social engineering works.

  • Authority
  • Scarcity
  • Social proof
  • Urgency
  • Likeness
  • Fear
  • The bottom line – People want to be accepted and valued by others.

A good social engineering attacker can smooth-talk their way around many controls.

USB key drop

  • Weaponized USB keys placed where users might pick them up and insert them into their own computers.
  • Many computer users fail to understand how dangerous USB keys can be.
  • Dropped USB keys will often be used for devious access to computers.

Network Based Exploits

Name resolution exploits

  • NETBIOS name service (NBNS)
    • Part of NetBIOS-over-TCP.
    • Similar functionality to DNS – translate host name to IP address.
  • LLMNR (Link-local Multicast Name Resolution)
    • Protocol based on DNS packet format.
    • Allows IPv4 and IPv6 name resolution on the same local link.
  • DNS and ARP poisoning could be in this category as well.

SMB (Server Message Block) exploits

  • Protocol used in Windows to provide file and printer access, and remote service access.
  • Uses TCP ports 139 and 445.
  • Some ransomware (EternalBlue, WannaCry) use SMB to propogate.

SNMP (Simple Network Management Protocol) exploits

  • Used to query and manage IP devices.
  • Multiple versions – SNMPv1 is not secure.
    • Cleartext passwords (default “community string” is “public”).

SMTP (Simple Mail Transport Protocol) exploits

  • Standard protocol for transmitting email.
  • Open relay, local relay, phishing, spam, etc.

FTP (File Transfer Protocol) exploits

  • Overall insecure protocol for transferring files.
  • No encryption for transfers and credentials (i.e. in the clear).
  • Easy for attackers to use for data exfiltration if FTP is available.

Man-in-the-middle

  • Family of attacks where the attack intercepts messages between a sender and receiver.
  • Attack may modify, regenerate, or forward intercepted messages.

ARP spoofing

  • Similar to DNS poisoning, but with local MAC addresses.

Pass the hash

  • Attacker intercepts an NTLM hash (user credential) and reuses it to appear as an authenticated user to Windows.

Replay

  • Relay
  • SSL (Secure Sockets Layer) stripping
  • Downgrade

DoS (Denial of Service)/stress test

  • NAC (Network Access Control) bypass
  • VLAN (Virtual Local Area Network) hopping

Wireless and RF vulnerabilities

  • DNS cache poisoning
  • Broadcast is wide open – anyone with receiver can intercept traffic.
    • Common tool is aircrack-ng (lots of Wi-Fi scanners for all OSs).
    • Aircrack-ng is a complete suite of tools to assess Wi-Fi network security. It focuses on different areas of Wi-Fi security:
      • Monitoring
      • Attacking
      • Testing
      • Cracking
  • Evil twin – rogue Wireless Access Point (WAP) used to eavesdrop.
  • Karma attack (Karma Attacks Radio Machines Automatically)
    • Device that listen for SSID requests and pretends to be valid WAP.
  • Downgrade attack – attempt to negotiate (force) a more insecure protocol.
  • Deauthentication attacks
    • DoS attacks that disrupt communication between a user and WAP.

Fragmentation attacks

  • DoS attack that floods a network with datagram fragments (someone has to reassemble).

Credential harvesting

  • Process of capturing or discovering valid login credentials.
  • Social engineering or other means.

WPS implementation weaknesses

  • Several consumer grade WAPs could allow an attacker to learn the WPS PIN.
  • ESPortalV2

Other wireless vulnerabilities

  • Bluejacking – sending unsolicited messages to a Bluetooth-enabled device.
  • Bluesnarfing – stealing information from a Bluetooth-enabled device.
  • RFID Cloning – unauthorized copy of a device’s RF signal.
  • Jamming – DoS attack that disables communication among devices.
  • Repeating – receiving and retransmitting a signal to increase range.
    • Can provide easier access for an attacker.

Various Wi-Fi scanners and related tools can be found on many platforms including Android.

  • Fake cell phone towers (also called ISMI (International mobile subscriber identity) catchers or Stingrays).
  • Successful redirection attacks can drive victim traffic to your chosen destination.
  • SMB is a popular target for propagating malware.
  • SNMP that is not secure can make many IP devices vulnerable.
  • FTP is often used to place malware and exploit tools.
  • FTP exploits can open a backdoor to a victim’s computer.
  • FTP itself can be vulnerable.
  • MITM attacker intercepts all traffic between sender and receiver.
  • May be part of an attack chain.
  • Multiple MITM possibilities, including ARP spoofing, pass the hash, replay attack.
  • Useful to bypass normal network security controls.
  • Anyone can receive wireless traffic – unencrypted means anyone can read it.
  • Evil twins can trick users into using your access point instead of a valid one.
  • Multiple attacks are emerging for Bluetooth devices.
  • IoT makes wireless vulnerabilities much more prevalent.

Application Based Vulnerabilities

Injections – inserting additional input data beyond what is expected.

  • SQL (Standard Query Language)
    • Adding specially crafted SQL in input to extract/modify data or execute commands.
  • HTML (HyperText Markup Language)
    • Adding HTML code when rendering web pages or submitting data to change the way a page works or how the data is handled.
  • Command
    • Adding command line options that change the way commands operate.
  • Code
    • A generalization of SQL injection – adding code in any language to change a program’s behavior.

Injection attack

  • Inserting additional data into application beyond what is expected.
  • SQL (Structured Query Language)
    • Adding specially crafted SQL input to extract/modify data or execute commands.
  • HTML
    • Adding HTML code/ submitting data to change how a page works or the data is handled.
  • Command
    • Adding command line options that change the way commands operate.
  • Code
    • A generalization of SQL injection – adding code in any language to change a program’s behavior.

Authentication Exploits

Credential brute forcing

  • Offline cracking (Hydra)
    • Session hijacking
  • Intercepting and using a session token (generally) to take over a valid distributed (web) session.
    • Redirect
  • Sending the user to a different site from what they expected (phishing).

Golden tickets are forged Kerberos Ticket-Granting Tickets (TGT) and a Silver tickets are forged Kerberos Ticket Granting Service (TGS) tickets, also called service tickets. Golden tickets allow for gaining access to any Kerberos service, while Silver tickets are limited to targeted service.

Default credentials

  • Out of the box artifacts (you have to clean these up!)
    • Weak credentials
  • This is why password cracking works.
    • Kerberos exploits
  • Forged tickets to allow unauthorized access to resources.

Authorization

Parameter pollution

  • Providing custom input parameters to alter service/API operation.

Insecure direct object reference

  • Programming mistake that can allow an attacker to bypass access controls and access resources or data.

Injection attacks provide specially crafted input to applications.

  • Injection attacks depend on an application’s failure to properly validate input data.
  • Results can include crashing a service or making it unresponsive.
  • Some injection attacks can provide privilege escalation.
  • Hand crafted SQL injection works in some cases.
  • Lack of input validation can make any application that uses SQL vulnerable.
  • Sqlmap and metasploit each make SQL injection attacks easy.
  • Authentication attacks include credential brute forcing, session hijacking, redirecting, and forged Kerberos tickets.
  • If you can acquire valid authentication credentials, you have access to lots of data.
  • Authorization attacks include parameter pollution and insecure direct object reference.

Cross-site scripting (XSS)

  • Injection attack in which an attacker sends malicious code (client-side script) to a web application that a subsequent client runs.
    • Stored/persistent
      • Attack data (script) stored discretely on the server.
    • Reflected
      • Non-persistent attack in which attack code is sent to another client.
    • DOM (Document Object Model)
      • XSS attack that uses XML, not HTML, to transport attack code.
  • XSS can allow an attacker to run almost any script code.
  • If successful, XSS attacks can compromise many client computers and devices.
  • Compromise can include remote control, data exfiltration, and setup for further attacks.

Cross-site request forgery (CSRF/XSRF)

  • Similar to XSS; occurs within an authenticated session.
  • XSRF attacks a user.
  • Attacker can cause authorized user to take some action by clicking a link.

XSS and XSRF both use client/server interaction to launch attacks based on specially crafted links or scripts.

Clickjacking

  • Tricking user into clicking a different link or object that was intended.
  • Attackers can use transparent or opaque layers to embed attack links.

Security Misconfiguration

Directory traversal

  • Allows users to navigate outside a web server’s root directory.

Cookie manipulation

  • Access to cookies can allow an attacker to change the way in which a web application operates in general, or just for a specific user/session.

File inclusion

  • Related to directory traversal.
  • Attacker is allowed to build path to .exe file or a file to access.
  • File can be local or remote.

Unsecure Code Practices

Comments in source code

  • Good for developers and technical personnel.
  • Bad for keeping secrets.
  • Source code comments can provide attackers with valuable insider information.

Lack of error handling

  • Bad things happen – developers don’t think of everything.
  • Unhandled errors can do some cool things.

Overly verbose error handling

  • Error messages can give too much info, serving as guidance to attackers on how to proceed.
  • Bad error message:
    • “Password invalid for this user”
  • Better error message:
    • “User ID or password is invalid”

Hard-coded credentials

  • Happens often – compiled and interpreted (strings command).
  • Attackers can use login credentials.
  • Most web apps connect to some other service.

Race conditions

  • Resource should be validated before it’s used.
    • E.g., checking a file is in place.
  • TOC (Time of Check)/TOU (Time of Use)
    • Gap between checking a condition and using that resource.
    • Attackers can influence other events and affect operation.

Unauthorized use of functions/unprotected APIs (Application Programming Interface).

  • Unintended API usage

Hidden elements

  • HIDDEN attribute in XML and HTML (doesn’t hide data in the source code)
  • Sensitive information in the DOM

Code signing

  • Certificates can authenticate author’s identity, ensure integrity
  • Lack of code signing
    • Lack of signing allows attackers to modify code between deployment and execution

Any software developer shortcuts can make an attacker’s job easier.

Local Host Vulnerabilities

  • Unsecure service and protocol configurations.
  • Cleartext, legacy options, old protocols, default configuration.

OS vulnerabilities

Linux Specific Privilege Escalation

SUID/SGID programs

  • Permission to execute a program as executable’s owner/group.
  • ls -l shows ‘s’ in executable bit of permissions.
    • -r-sr-sr-x (SUID and SGID set)
    • Unsecure SUDO
  • Authorized users execute commands as if logged in a root.

Ret2libc

  • Stack overflow attack
  • Replaces current stack return address with attacker’s chosen address of another subroutine.
  • Libc includes useful calls, such as ‘system’.

Sticky bits

  • Directory permission
  • Multiple users can create, read, and write files, but only the owner can delete.
  • ls shows ‘t’ in the last bit of permissions.
    • drwxrwxrwt

Windows Specific Privilege Escalation

  • Cpassword – Group Policy Preference attribute that contains passwords.
  • SYSVOL folder of the Domain Controller (encrypted XML).
  • Clear text credentials in LDAP (Lightweight Directory Access Protocol).
  • Kerberoasting – domain users can query Kerberos tickets for other users.
  • Credentials in LSASS (Local Security Authority Subsystem Service)
    • Enforces security policy
  • PXE (Preboot Execution Environment) credentials
    • Unattended installation
  • SAM database (Security Account Manager)
    • Database that contains user passwords.
  • DLL hijacking (Dynamic Link Library)
    • Forcing a loader to load a malicious DLL.

Exploitable services

  • Unsecure service and protocol configurations.
  • Cleartext, legacy options, old protocols, default configuration.
  • Unquoted service paths
    • Allow abbreviated attack paths (without spaces).
  • Writable services
    • Allow attacker to replace services with malicious programs.

Privilege escalation

  • Unsecure file/folder permissions – root installs allow read/write by any user.
  • Keylogger
    • Records every keystroke.
  • Scheduled tasks
    • Attacker may add new task to run persistently with elevated privileges.
  • Kernel exploits
    • Unpatched systems are vulnerable.

Misc Local Host Vulnerabilities

  • Default account settings – disable accounts that are not being used.
  • Sandbox escape
  • Shell upgrade – gaining access to a shell with higher privilege.
  • VM – escaping a VM may allow access to underlying environment.
  • Container – similar to VM escape (i.e. Docker).

Physical Device Security

  • Cold boot attack
    • Ability to physically reboot a system (can allow access to encryption keys).
  • JTAG debug (Joint Test Action Group)
    • Can allow attacker to interact with chips.
  • Serial console
    • If not disabled, provides direct access to servers.

Physical Security Related to Facilities

  • Piggybacking/tailgating
    • Unauthorized person following an authorized person through a physical control.
    • Piggybacking is often easy – most people want to be courteous.
  • Fence jumping
    • Physically bypassing a control.
  • Dumpster diving
    • Looking through trash for useful information.
    • More useful than it sounds.
  • Lock picking
    • Opening a lock without a proper key.
  • Lock bypass
    • Defeating a lock mechanism without picking (i.e. bolt cutter, remove hinges).
    • If you can’t open a lock, see if you can get around it easier.
  • Egress sensor
    • Senses a person approaching a door to leave a facility.
    • Opposite of piggybacking.
  • Badge cloning
    • Copying an RFID badge.

Vulnerabilities Review

  • Every operating system has its own specific vulnerabilities.
  • Online vulnerability repositories make it easy to determine which vulnerabilities apply to a specific target.
  • SUID/SGID and sudo make systems easier to use, but can make them easier to compromise.
  • Ret2libc is a potential attack vector for hijacking processes.
  • Sticky bit directories can allow attackers to write files and executables.
  • Cpassword and LDAP credentials may contain valuable credentials.
  • PXE (Preboot Execution Environment) credentials can be used to access system as an authorized user.
  • DLL hijacking is an attack vector that could allow an attacker to load malware.
  • Unquoted service paths and writable services can allow for service exploits.
  • Look for files and folders that allow excessive read/write permissions.
  • Footprinting can provide information on kernel vulnerabilities.
  • Default artifacts left in place are almost always vulnerabilities.
  • A lack of physical security (physical access) always makes attacking easier.
  • Look for easy attack paths – administrators may have overlooked something.

Post Exploitation Techniques

What to do once you’re in.

  • Make it easier next time.
  • Lateral movement
  • RPC/DCOM (Remote Procedure Call / Distributed Component Object Model)
  • PsExec – Utility that supports executing processes on other systems (i.e. telnet).
  • WMI (Windows Management Instrumentation) – Managing devices and applications from remote computers.
  • Scheduled tasks

Lateral Movement

  • PS remoting/WinRM
    • PowerShell remoting/Windows Remote Management.
  • SMB (Server Message Block)
    • Protocol for exposing shares to remote computers (Linux, etc. too).
  • RDP (Remote Desktop Protocol)
    • Ability to access a desktop from a remote computer.
  • Apple Remote Desktop
    • Apple’s RDP
  • VNC (Virtual Network Computing).
  • X-server forwarding
    • X-windows access to Linux desktop.
  • Telnet
    • Unsecure remote access (everything in cleartext).
  • SSH (Secure Shell)
    • More secure remote access to shell.
  • RSH/Rlogin (Remote Shell / Remote login)
    • Legacy secure remote access.

Establishing Persistence

Scheduled jobs

  • Cron or Task Manager
  • Scheduled task
  • Daemons
    • Background processes or services.

Back doors

  • Bypass standard security controls.
  • Trojan
    • Malware that looks like it does something useful.
  • New user creation.
    • Makes later logins easier.

Stealth

  • Clean up files, including tools installed.
  • Hiding files that you need to leave.
  • Sanitize log files (remove entries or entire logs).
  • Remove any traces of activity while accessing the environment.

Post Exploitation Review

  • Don’t reinvent the wheel each time – once you’re in, make it easier next time.
  • Enable remote access if possible.
  • Use remote access to move laterally within a network.
  • Telnet can be helpful when connecting to different devices.
  • Set up persistent processes to maintain a presence.
  • Install low profile tools and malware to make your job easier.
  • Leave artifacts that keep the attack going and make it easier to get back in.
  • Once the attack is over, clean up to avoid post-mortem detection.

4. Penetration Testing Tools

Nmap (Network Mapper)

  • One of the most common and most useful tools for reconnaissance.
  • Nmap cookbook
  • SYN (stealth) scan
    • nmap –sS target
    • Sends SYN packet and examines response (SYN/ACK means the port is open).
    • If SYN/ACK received, nmap sends RST to terminate the connection request.
  • Full connect scan
    • nmap –sT target
    • Completes the handshake steps to establish a connection (more reliable).
  • Port selection -p
    • Scans a range of ports nmap-p <range of ports> target.
    • -p 21
    • -p 1-10000
    • -p U:53,137,161T:21-37,80,8080
    • OR –exclude-port <range of ports>
  • Service identification (-sV)
    • nmap –sV <target>
    • Attempts to determine service and version info.
    • --version-intensity <level>, where level can be 0 (light) to 9 (execute all probes)

Gathering information with Nmap

  • OS fingerprinting (-O)
    • Detects target OS
    • nmap –O <target>
  • Disabling ping (-Pn)
    • Skips host discovery (assumes all are online).
    • nmap –Pn <target>
  • Target input file (-iL)
    • Uses a text file that contains a list of targets
    • nmap –iL <inputFileName>
  • Can also exclude targets from a range
    • nmap –excludefile <execludeFileName>
  • Timing -T
    • Changes how long nmap waits for a response (default is –T 3).
    • Values range from 0 (Paranoid, slow) to 5 (Insane, fast).

Output parameters

  • -oA – Combined format
    • Normal .txt, XML .xml, and grepable .txt
  • -oN
    • Normal output file (.nmap)
  • -oG
    • Grepable output file (.gnmap)
  • -oX
    • XML output format (.xml)

Tools By Category

Reconnaissance

  • Nmap
  • Whois
  • Nslookup
  • Theharvester
  • Shodan
  • Recon-NG
  • Censys
  • Aircrack-NG
  • Kismet
  • WiFite
  • SET
  • Wireshark
  • Hping
  • Metasploit framework

Enumeration

  • Nmap
  • Nslookup
  • Wireshark
  • Hping

Vulnerability scanning

  • Nmap
  • Nikto
  • OpenVAS
  • SQLmap
  • Nessus
  • W3AF
  • OWASP ZAP
  • Metasploit framework

Credential attacks

  • Hashcat
  • John the Ripper
  • Cain and Abel
  • Mimikatz
  • Aircrack-NG

brute-forcing services

  • SQLmap
  • Medusa
  • Hydra
  • Cain and Abel
  • Mimikatz
  • Patator
  • W3AF
  • Aircrack-NG

Persistence

Once you have exploited a target, use these to make sure you can get back in:

  • SET
  • BeEF
  • SSH
  • NCAT
  • NETCAT PERSISTENCE
  • Drozer
  • Powersploit
  • Empire
  • Metasploit framework

Configuration compliance

Used to evaluate a configuration to determine if it’s compliant with a standard or regulation.

  • Nmap
  • Nikto
  • OpenVAS
  • SQLmap
  • Nessus

Evasion

  • SET
  • Proxychains
  • Metasploit framework

Decompilation

  • Immunity debugger
  • APKX
  • APK studio

Penetration Testing Use Cases

  • SAST (Static Application Security Testing)
  • DAST (Dynamic Application Security Testing)

Scanners

ToolDescription
NiktoWeb server vulnerability scanner
OpenVAS (Open Vulnerability Assessment System)Open Source vulnerability scanner and manager
SQLmap (Structured Query Language)Automatic SQL injection and database takeover tool
NessusCommercial vulnerability scanner (free for non-professional use)

Credential testing tools

ToolCategoryDescription
HashcatOfflineAdvanced password recovery
(world’s fastest)
MedusaOnlineParallel network login auditor
HydraOnlineParallelized login cracker
CewlCustom wordlist generator
John the RipperOfflinePassword cracker
Cain and AbelOnline/offlineWindows password recovery tool
MimikatzOnline/offlineA little tool to play with Windows
security
PatatorOnlineMulti-purpose brute-forcer
DirbusterMulti-threaded app to brute force
directories and file names on web
servers
W3AFOnlineWeb Application Attack and Audit
framework

Debuggers

ToolDescription
OLLYDBGWindows 32-bit
Immunity debuggerWrite exploits, analyze malware, and reverse engineer binary files
GDBGNU project debugger
WinDBGWindows debugger
IDACross-platform debugger

Software assurance tools

ToolDescription
Findbugs/findsecbug sAuditor of Java web applications
PeachFuzzer – automated testing
AFLAmerican Fuzzy Lop – fuzzer
SonarQubeContinuous inspection – automated testing
YASCAYet Another Source Code Analyzer

Open source intelligence (OISINT) tools

ToolDescription
WhoisDomain details (contacts, name servers, etc.)
NslookupDNS information, Installed or available on most OSs
FocaFingerprint Organizations with Collected Archives – finds document metadata
TheharvesterGathers info from many sources (email, hosts, open ports, etc.)
ShodanFinds Internet connected devices
MaltegoData mining for investigations
Recon-NGWeb reconnaissance
CensysFinds Internet connected devices

Wireless tools

ToolDescription
Aircrack-NGMonitoring, attacking, testing, cracking
KismetWireless detector, sniffer and intrusion detection system
WiFiteWrapper for other wireless tools (current version is WiFite2)

Web proxies

ToolDescription
OWASP ZAPZed Attack Proxy – Web application security scanner
Burp SuiteGraphical tool for testing web application security

Social engineering tools

ToolDescription
SETSocial Engineering Toolkit – penetration testing using social engineering
BeEFBrowser Exploitation Framework – focus is on web browser

Remote access tools

ToolDescription
SSHSecure shell, Included or available in most OSs
NCATSimilar to nc, but from Nmap developers
NETCATSame as nc, Included or available in most OSs
ProxychainsForces TCP connections through a proxy

NCAT and NETCAT can:

  • Connect to any port
  • Set up bind and reverse shells

Networking tools

ToolDescription
WiresharkPacket sniffer/protocol analyzer
HpingPacket assembler/analyzer

Mobile tools

ToolDescription
DrozerAndroid security and attack framework
APKXAndroid APK decompiler
APK StudioAndroid app decompiler

Miscellaneous tools

ToolDescription
SearchploitSearch tool for exploit database
PowersploitPost-exploitation framework (MS PowerShell)
ResponderMicrosoft network poisoner
ImpacketPython classes for working with network protocols
EmpirePowerShell/Python post-exploitation agent
Metasploit frameworkComprehensive penetration testing framework

Unshadow

unshadow /etc/passwd /etc/shadow > hashfile
john --wordlist=/usr/share/john/password.lst hashfile
ls .john
cat .john/john.pot

Windows

pwdump is a utility that needs to be downloaded.

cd \pwdump7

copy hashed password

msf > search psexec
use windows/smb/psexec
set RHOST 10.10.1.1
set SMBUser Administrator
set SMBPass <pasted hash>

Tools Review

  • Nmap service identification (nmap -sV <target>) attempts to identify the service and version monitoring each port.
  • Stealth scans (nmap -sS <target>) create fewer network packets than full connect scans (nmap -sT <target>).
  • Nmap returns results faster if targets aren’t pinged and are just assumed they’re alive (nmap -Pn <targets>).
  • To avoid detection, use the nmap timing option with a lower number (nmap -T0 <target> or nmap -T1 <target>).
  • Know what each of the tools listed in the objectives are commonly used for.
  • Some tools, such as nmap, can fit into multiple use cases.
  • It’s more important to understand the purpose of a tool than to memorize categories.
  • Kali Linux is only open source Linux distribution targeted at penetration testing.
  • Don’t limit a pen testing toolbox to just Kali Linux.
  • Briefly launch each tool in Kali Linux listed in the exam objectives to explore their uses.
  • Remember that knowing Kali Linux is not a PenTest+ Objective.
  • Scanners are “meta” tools that provide several levels of output.
  • Scanners are powerful, but very noisy and using them risks being detected.
  • Credentials cracking tools run either in online or offline modes.
  • Effective dictionary attacks depend on good user/password lists.
  • Analyze tool output.
  • Debuggers are advanced tools and can reveal how a program works.
  • Debuggers can also allow testers to modify data as the program is running.
  • Software assurance tools can help identify vulnerabilities in applications.
  • OSINT data can help fill in formation gaps.
  • Some information is not based on IP addresses or domain names.
  • Be creative when exploring attack vectors for targets.
  • Targets can be devices, people, user accounts, and even facilities.
  • Wireless attackers can intercept traffic easier than wired network traffic.
  • The rapid IoT growth has resulted in lots of unsecure wireless devices.
  • Web applications are often fertile grounds for finding vulnerabilities.
  • There are multiple ways to leverage remote connections.
  • The PenTest+ exam focuses on commandline tools for remote access.
  • Remote access is often followed by privilege escalation attacks and/or preceded by credential attacks.
  • Bind shell – target starts listening, when target receives appropriate connection, launch shell, attacker reaches out and makes the connection.
  • Reverse shell – attack sets up the listener, target establishes connection and launches the shell.
  • Sniffers show the contents of network packets (may be encrypted).
  • Some tools allow packets to be changed before sending them to the recipient.
  • A proxy allows testers to launch man-in-the-middle exploits.

4.1 Using Scripting in Pen Testing

Why bother with scripts?

  • Automate mundane/repetitive tasks.
  • Faster
  • Less error prone
  • Repeatable

What is a script?

  • Interpreted sequence of commands.
  • Not compiled or assembled.
  • Easy to code.

Pros of Scripts

  • Scripts help automate repetitive actions.
  • Scripts are good for standardizing testing activities.
  • Scripts also reduce typing errors and make tests repeatable, as well as help in documenting test activities.
  • Be effective and consistent. Save time and easily repeat by scripting.
  • Scripts help automate repetitive actions.
  • Scripts are good for standardizing testing activities.
  • Scripts also reduce typing errors and make tests repeatable, as well as help in documenting test activities.

Scripting Basics

  • Variables
    • Temporary data storage.
  • Substitutions
    • Input parameters and environment variables.
  • Common operations
    • Strings and comparisons.
  • Logic
    • Looping and flow control.
  • Basic I/O
    • Read input and write output (file, terminal, and network).
  • Error handling
    • When things don’t work.
  • Arrays
    • Simple data structure.
  • Encoding/decoding
    • Handling special characters.

Bash

Bash – Bourne Again Shell

  • Command shell for most Linux/MAC OS systems.
  • Freely available version of the UNIX Bourne shell (sh).
  • Bash is the default shell in Linux.
  • Bash makes it easy to combine multiple commands that can react to input.
  • Learn basic loops and conditional logic.
  • A few lines of a bash script can automatically execute many commands, such as scans.
  • Redirecting input from stdin and output to stdout is the most common bash I/O technique.
  • Bash scripts can be used with Linux pipes.
  • Arrays can be useful, but aren’t supported in older shells (make sure you’re running bash and not sh).

Potential List of Bash Resources

Portscan Example

#!/bin/bash
target=$1
minPort=$2
maxPort=$3

function scanports
{
for ((counter=$minPort; counter<=$maxPort; counter++))
do
    (echo >/dev/tcp/$target/$counter) > /dev/null 2>$1 && echo "$counter open"
done
}

scanports

Calling the script

bash portscan.sh 10.10.1.10 21 80

PowerShell

PowerShell is a Windows-based admin and automation shell. A powerful scripting language.

  • Available in Windows since 2006.
  • Was Windows PowerShell until 2016.
  • PowerShell is currently open source and available for multiple operating systems.

Potential List of PowerShell Resources

PowerShell scripts are disabled in Windows by default. To enable, open an elevated PowerShell terminal and type:

Set-ExecutionPolicy Unrestricted
y
exit

Right click a script and click edit to edit or press the play button to run.

Portscan Example

  • portscan.ps1
$port = 80
$subnet = "10.10.1"
$range = 1..254
foreach ($r in $range)
{
    $ip = "{0}.{1}" -F $subnet,$r
    if(Test-Connection -BufferSize 32 -Count 1 -Quiet -ComputerName $ip)
    {
        $socket = new-object System.Net.Sockets.TcpClient($ip, $port)
        If($socket.Connected)
        {
            "$port open on $ip"
            $socket.Close()    }
            }
}

Doesn’t handle errors very well as it is a basic script. Scanning Kali box will throw and error as Kali doesn’t accept connections on port 80.

Ruby

Ruby is a powerful object-oriented language that can do far more than just scripting. A powerful multipurpose language.

  • Ruby’s popularity is related to the Ruby on Rails server-side web application framework written in Ruby.
  • Ruby treats everything as an object and relies heavily on methods and attributes.
  • Influenced by Perl, Smalltalk, Ada, Lisp.

Potential List of Ruby Resources

Download and install Ruby

Portscan Example

#! /usr/bin/ruby

require 'socket'

TARGET = ARGV[0] || '10.10.1.10'
MINPORT = ARGV[1] || 22
MAXPORT = ARGV[2] || 80

$i = MINPORT.to_i
while $i <= MAXPORT.to_i do
    begin
        socket = TCPSocket.new(TARGET, $i)
        status = "open"
        puts "Port #{$i} is #{status}."
    rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT
        status = "closed"
    end
    $i = $i + 1
end

Calling the script

ruby portscan.rb 10.10.1.10 22 80

Python

Python is another powerful (multipurpose) object-oriented language. Not just used for scripting. Python is a popular language because it’s easy to write very powerful programs in just a few lines of code.

  • Unlike many other languages, Python depends on indentation to define blocks.
  • Extensive available libraries
  • Great intro language

Potential List of Python Resources

Download and install Python

Portscan Example

import sys, socket

target = sys.argv[1]
minport = int(sys.argv[2])
maxport = int(sys.argv[3])

def porttry(cur_target, port):
    try:
        s.connect((cur_target, port))
        return True
    except:
        return None
for i in range(minport, maxport+1):
    s = socket.socket(2, 1) #socket.AF_INET, socket.SOCK_STREAM
    value = porttry(target, I)
    if value != None:
        print("Port opened on %d" % I)

Not an elegant way to establish targets, kind of a brute force way to match other examples. Would require a little more code to do it right.

Calling the script

python portscan.py 10.10.1.10 20 80

Scripting Languages Review

  • Recognize unique Bash script syntax – output (echo), error-handling (“$?”).
  • Recognize unique PowerShell script syntax – output (Write-Host), flow-control (elseif), error-handling (try/catch).
  • Recognize unique Ruby syntax – output (puts), flow-control (elsif), error-handling (rescue).
  • Recognize unique Python syntax – output (print), error-handling (try/except/finally).

Scripting Languages Comparison

Comments, Variables, and Substitution Comparison

BashPowerShellRubyPython
Comments## or <# #># or =begin =end#
Variables – assignvarName=value$varName=valuevarName=valuevarName=value
Variables – displayecho $varNameWrite-Host $varNameputs varNameprint(varName)
Substitution – environment variables$envVarNameGet-item Env:varNameENV[‘varName’]Os.environ[‘varName’]

String, And/Or, and Comparisons Comparison

BashPowerShellRubyPython
String length${#string}(string).Lengthstring.lengthlen(string)
String – substring${string:position}(string).Substring(start,end)string[1..3]string[start:end+1]
String – replace substring${string/substring/replacement}(string).Replace(substr,replStr)string[1..3] = replStrstring.replace(old, new, count)
AND/OR-a / -o-and, -or, -not !and &&, or ||, not !and, or, not
Comparisons-eq (==), -ne (!=), -lt (<), -le(<=), -gt (>), -ge (>=)-eq, -ne, -gt, -ge, -lt, -le==, !=, >, >=, <, <===, != (<>), >, >=, <,<=

Looping and Flow Control Comparison

BashPowerShellRubyPython
LoopingForFor, While, Do-While, Do-Untilwhile, until, forfor, while
Flow controlif condition
then
commands
elif
commands
else
commands
fi
if (condition) {
statements
} elseif (condition) {
statements
} else {
statements
}
If condition then
statements
elsif
statements
else
statements
end
if condition:
statements
elif condition:
statements
else:
statements

Input File, Terminal, and Network Comparison

BashPowerShellRubyPython
Input – fileInput=“filename”
While IFS=read
-r f1 f2 f3
$lines = Get-Content filename
Out-File –FilePath
filename –InputObject
$lines –Encoding ASCII
inFile = File.new(“filena me”,”r”) inFile.each_line{|line| puts “#{line.dump}” }
inFile.close
f = open(‘inFile.txt’,’ r’)
for line in f:
do something here
f.close()
Input – terminalRead –p “Prompt:” var$firstName = Read- Host –Prompt ‘Enter first name’name = getsname = raw_input(‘Pleas e enter your name’)
Input – networkWhile read –r inline </dev/ttyS1$socket = new-object System.Net.Sockets.Tcp Client($ip, $port)
if($socket.Connected) {}
client = TCPSocket.open(‘ hostname’, ‘port’) Client.send(“strin g”,0)sock = socket.socket(soc ket.AF_INET, socket.SOCK_ST REAM)
If sock.connect_ex( (remoteServerIP, port)) == 0:
print (‘Port {}: is Open’.format(port)

Error Handling Comparison

BashPowerShellRubyPython
Error handlingIf [ “$?” = “0” ] thentry {
Command
}
catch { errHandling
commands
}
begin
statements
rescue
statements if error occurred
else
statements if no error
end
try:
statements
raise customErrorObject except errorObject:
statements
exceptcustomErrorObject:
statements
finally:
statements to clean up

Array Comparison

BashPowerShellRubyPython
ArraysbashArray = (val1, val2, val3)
For I in 1 2 3
Do
echo ${bashArray[$i]}
done
$PSarray=@(1.3.5.7.9);
for ($i = 0; $i –lt
$PSarray.Length; $i++) {
$PSarray[$i]
}
foreach ($element in$PSarray) {
$element
}
rubyArray = [ “val1”, “val2”, “val3” ]
print rubyArray[1] print rubyArray.index(“val2”)
pythonArray = [10,20, 30, 40, 50]
Print(pythonArray[ 1])
len(pythonArray)

Encoding and Decoding Comparison

BashPowerShellRubyPython
EncodingEcho plainText | base64$Text = ‘Hello world’
$Bytes = [System.Text.Encoding]::Un icode.GetByteps($Text)
$EncodedText = [Convert]::ToBase64String.($Bytes)
Require “base64” encString = Base64.encode64(‘ Hello world!”)Import base64 encString = base64.encodestri ng(‘Hello world!’)
DecodingEcho encString | base64 –decode$EncodedText = ‘encodedString’
$DecodedText = [System.Tet.Encoding]::Unic ode.GetString([System.Conv ert]::FromBase64String($EncodedText)
plaintext = Base64.decode(en c)plaintext = base64.decodestri ng(encString)

5. Reporting and Communication

The pen test report

  • Communicate findings AND recommendations.
  • Primary deliverable.
  • Only chance to make your points.
  • Digest of all activities and conclusions.
  • Some conclusions are drawn during tests.
  • Some result from post-test analysis.

Samples and Templates

Tips for writing a report

  • Start writing early.
  • Don’t wait until the end of the project.
  • Write what you can up front.
  • Add to the report as you go – editing is easy.
    • Tell your story.
    • Know your audience(s).
  • Executive 1-page summary.
  • Technical/management.
  • Motivation – audit?
    • Leave the reader with a call to action.
  • Include steps to fix the issues.

Your report will be your voice after you leave

  • Try to answer any questions that may arise.
    • What did you do?
    • Why did you make the choices you made?
    • What did you find, and how did your findings affect your conclusions?
  • After settling on format, you need data.
    • Mostly presentation and summary of data.
    • Collect data.
  • Transform as needed into a common format (normalization).
  • Don’t spend too much time on this, but try to harmonize data format.
    • Use tools like MS Excel.
  • This will make it easier to read and analyze.

Common Report Sections

Executive summary

  • 1 page max – High level summary.
  • Targeted at executives – few details.
  • State the test goals and general findings.

Methodology

  • Your approach to the overall test activities.
  • Tools and techniques.
  • Why you did what you did.
    • And why you didn’t do more.

Findings and remediation

  • Ranked list (more details than Executive summary).
    • What you found (important findings first).
    • What you recommend the client does – provide options as appropriate.
    • Metrics and measures.
  • Details of what you found.
  • How you assessed each finding.
  • Risk rating – http://www.pentest-standard.org/index.php/Reporting.

Conclusion

  • Wrap up, summary, and call to action.

Reporting Best Practices

Risk appetite

  • Amount of risk client is willing to accept.
  • Tone of the entire report is based on the company’s appetite for risk.
  • Risk appetite statement should appear in the report introduction.

Report storage

  • Reports should become part of the organization’s document repository.
  • Used as input for future pen tests and other assessments.
  • Security policy should state how long reports are kept.

Report handling and disposition

  • Security policy should state how assessment reports are stored.
  • At end of life, how are reports disposed of?

Post Report Delivery Activities

  • Delivering the report isn’t the end.
  • There is more work to do.
  • Delivering may include presenting the report.
  • Post-report delivery activities – clean up any changes you made.
    • Removing all of these:
      • Shells
      • Tester-created credentials
      • Tools
  • Clean up history.
  • Leaving artifacts can weaken the client.

Client acceptance

  • Formal cessation of project activities and acceptance of deliverable.
  • The client formally says “You’re done.”
  • Client should sign an statement of acceptance.

Lessons learned

  • Crucial step in project closure.
  • Helps to continuously improve.

Follow-up actions/retest

  • Client may need more actions based on findings.
  • Be careful to avoid extending the project scope here without a change process.

Attestation of findings

  • Independent review and assurance of findings (i.e. third party).

Recommended Mitigation Strategies

  • Nearly every pen test will discover multiple vulnerabilities.
  • A pen test report should contain recommendations to mitigate each vulnerability.
  • Solutions vary, depending on the vulnerability.
  • People – behavior changes.
  • Social engineering
  • Passwords
  • Process – how things are done.
  • Backup media handling.
  • ID management
  • Technology
  • Controls based on hardware and/or software.

Common findings

  • Shared local administrator credentials.
    • Randomize credentials/LAPS.
  • Weak password complexity.
    • Minimum password requirements/password filters.
  • Plain text passwords.
    • Encrypt the passwords.
  • No multifactor authentication.
    • Implement multifactor authentication.
  • SQL injection
    • Sanitize user input/parameterize queries.
  • Unnecessary open services.
    • Disable or remove unneeded services (system hardening).

Importance of Communication

Good communication is critical to the penetration test success.

  • Most penetration tests should be conducted openly.
    • Unless discretion is a stated goal.
  • Cooperation is enhanced with communication.
  • Who authorizes the project and provides funding?
  • Project sponsor
    • Who should be contacted if unexpected consequences occur?
    • Who will resolve conflicts?
    • Who will provide required technical assistance?
    • How will you escalate issues that are not resolved in a timely manner?

Communication timing and frequency

Communication triggers

  • Critical findings – something that really can’t wait.
  • Stages – moving from one phase to another.
  • Indicators of prior compromise – finding evidence that an attacker has already been here.
  • Other defined milestones or events.
    • Periodic reports
    • Critical tests started/completed.
    • Obstacles put in place/removed (i.e. affect on operations).

Reasons for communication

Situational awareness

  • Most common recurring reason.
    • De-escalation
  • Information or action is needed to reduce critical risk.
    • De-confliction
  • Resolve conflict of any type.
    • Pen test team vs. operations/users.
    • Pen test team vs. service provider.
    • Pen test team vs. management.

Goal reprioritization

  • Changes to pen testing plan.
    • Unexpected impact
    • Unexpected findings
    • Organizational changes – management change, merger, or acquisition.
    • Conflict with team, management, resources, etc.
    • All changes must follow change procedures.

The Pentest report is your best opportunity to leave a lasting message.

Reporting Review

  • Start writing your report early in the testing project.
  • Write to your audiences (executive vs. technical).
  • Provide a definite “call to action” with remediation recommendations.
  • Remove all test activity artifacts.
  • Get formal client acceptance.
  • Conduct “lessons learned” sessions with client and capture the findings.
  • Follow up on client add-on requests.
  • Recommend mitigation activities for each identified vulnerability.
  • Suggest different classes of mitigations (technical, administrative, etc.).
  • Know common findings and mitigations for the PenTest+ exam.
  • Good communication is critical to pentest project success.
  • Managing communication expectations, including frequency, reduces conflict.
  • Define triggers that initiate communication.
  • Specify communication paths.
  • Who should you contact for project related tasks? Project sponsor.
  • Who should you contact for issues or questions? Manager or responsive contact.
  • When will you call? Communication frequency. When should they expect to hear from you.
  • Satisfy client expectations.

Conclusion

YEAH. We did it. Over 8K words of CompTIA PenTest+ PT0-001 goodness. Let me know what was easy for you and, of course, what you had trouble with.

If anything needs to be corrected or added, please sound off in the comments below.

Thanks, and good luck with the exam!

Update: This will do it for CompTIA certifications for now. Next up on my list is the CCSP from ISC2!

Pin It on Pinterest