Web Application Pentesting with Bash
local graph
Chapter 9 — Web Application Pentesting with Bash
Section titled “Chapter 9 — Web Application Pentesting with Bash”This chapter explores how to use Bash for web application pentesting. We’ll look at how Bash’s flexibility can help you find vulnerabilities, automate tasks, analyze responses, and manage web data. By the end of this chapter, you’ll be able to use Bash to discover and exploit common web vulnerabilities, extract data efficiently, and integrate with other pentesting tools for a thorough web assessment.
There are generally five use cases for testing web application security:
- Testing a single web application in depth
- Quickly testing (automated scanning) many web applications during a network pentest
- Creating scripts to fuzz for vulnerabilities
- Creating proof-of-concept (PoC) exploits
- Continuous integration and continuous delivery/deployment (CI/CD) testing
This chapter focuses on the second, third, and fourth use cases. If I were testing in the first use case, I would prefer browser proxies such as ZED Attack Proxy (https://www.zaproxy.org), also known as ZAP, or Burp Suite (https://portswigger.net/burp). These tools enable a tester to thoroughly explore an application. In the case of ZAP, it does allow you to run the tool in a Bash terminal without showing the graphical user interface (GUI) to automate scanning. I’ll be showing how to use ZAP in the terminal later in this chapter.
In this chapter, we’re going to cover the following main topics:
- Automating HTTP requests in Bash
- Analyzing web application security with Bash
- Learning advanced data manipulation techniques
Technical requirements
Section titled “Technical requirements”The first prerequisite is that you started reading from Chapter 1 and have access to a Bash shell. You should be using Kali Linux, as discussed in Chapter 1. You will find it difficult to follow along if you’re using a different operating system.
Ensure that you have installed ProjectDiscovery tools before advancing: https://github.com/PacktPublishing/Bash-Shell-Scripting-for-Pentesters/tree/main/Chapter01#install-project-discovery-tools
Run the following commands to configure software prerequisites:
$ sudo apt update && sudo apt install -y zaproxy curl wget parallel chromium$ sudo apt remove python3-httpxThe httpx entry must be removed because the command name clashes with the httpx command from ProjectDiscovery.
The code for this chapter can be found at https://github.com/PacktPublishing/Bash-Shell-Scripting-for-Pentesters/tree/main/Chapter09.
If you want to follow along interactively with the section that shows how to use curl to automate testing for SQL injection (SQLi), you’ll need to install Damn Vulnerable Web Application (DVWA), available at https://github.com/digininja/DVWA. I’ll be running DVWA in Docker, which is the quickest way to start up the application. I’ll also be using Vulhub (https://github.com/vulhub/vulhub) when demonstrating a nuclei scan.
Automating HTTP requests in Bash
Section titled “Automating HTTP requests in Bash”Any serious discussion on making HTTP requests in a terminal must start with curl. The curl tool is a command-line tool used for transferring data to or from a server using various protocols such as HTTP, HTTPS, FTP, and more. It is widely used in pentesting to interact with web applications, sending custom requests to uncover vulnerabilities. You can visit the curl website and learn more by visiting https://curl.se.
I believe that most pentesters would prefer to use a browser proxy such as ZAP or Burp, or Python scripts for web application testing. However, knowledge of using curl in a Bash shell comes in handy. While I was writing this chapter, someone I worked with reached out to me for my help recreating a Metasploit HTTP exploit module in Bash because they couldn’t install Metasploit or any Python modules in the testing environment. The testing environment did have Bash and common command-line tools such as curl installed.
Here are some common curl options that are useful for pentesters:
-Xor--request: Specify the request method (GET,POST,PUT,DELETE, and so on)-dor--data: Send data with aPOSTrequest-Hor--header: Pass custom headers to the server-Ior--head: Show response header info only-uor--user: Include user authentication-oor--output: Write output to a file-sor--silent: Silent mode (no progress bar or error messages)-kor--insecure: Allow insecure server connections when using SSL-Lor--location: Follow redirects-wor--write-out <format>: Makecurldisplay information onstdoutafter a completed transfer The format is a string that may contain plain text mixed with any number of variables.-Zor--parallel: Makescurlperform its transfers in parallel as compared to the regular serial manner
We’ll be covering usage examples of the preceding options throughout this section.
GET and POST requests are the most common HTTP request methods. There are many more. To learn more, see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods.
A GET request is used to retrieve information from a server. Here’s how to use curl to make a GET request: curl -X GET https://example.com.
Here is an explanation of this command:
curl: Invokes thecurlcommand-X GET: Specifies the request method asGEThttps://example.com: The URL of the target server
A POST request is used to send data to a server in the body of a request. Here’s an example: curl -X POST https://example.com/login - d "username=user&password=pass".
The following points explain this command:
-X POST: Specifies the request method asPOST-d "username=user&password=pass": Sends data with the request
The key difference between a GET and a POST request is how data is sent to the server. A GET request sends data in the URL as parameters. A raw GET request looks like the following:

Figure 9.1 – An example GET request
The key area to focus on in the preceding figure is the first line, which starts with the GET method, followed by the relative URL (/admin/report?year=2024&month=7) and HTTP specification (HTTP/2). As you can see in the figure, data is sent to the server in the URL as the year and month parameters.
The POST request method sends data in the request body. A raw POST request looks similar to the one shown in the following figure:

Figure 9.2 – An example POST request
The key point to notice in the preceding figure is that data is sent to the server in the request body (the last line), which follows the headers (keyword: ``value pairs).
Many web applications require authentication headers. Here’s how to include them in your request: curl -X GET https://example.com/protected -H "Authorization: ``Bearer <token>".
You can send data from a file using the --data-binary option: curl -X POST https://example.com/upload -- data-binary @file.txt.
Often, pentesters need to combine multiple options to craft specific requests. Here’s an advanced example: curl -X POST https://example.com/api -H "Authorization: Bearer <token>" -H "Content-Type: application/json" - d @data.json.
The following points explain the preceding command:
-H "Content-Type: application/json": Specifies the content type of the data being sent-d @data.json: Sends the contents ofdata.jsonwith the request
It’s crucial to handle HTTP responses to analyze the behavior of the web application:
#!/usr/bin/env bashresponse=$(curl -s -o /dev/null -w "%{http_code}" https://example.com)if [ "$response" -eq 200 ]; then echo "Request was successful."else echo "Request failed with response code $response."fiLet’s look at the code more closely:
response=$(...): It captures the HTTP response code in a variable.-s -o /dev/null -w "%{http_code}": Silent mode, discard output, and print only the HTTP response code. See https://curl.se/docs/manpage.html#-w for more information about the-woption and its use.- The
ifblock analyzes the response code. If the response code is200, the request was successful.
Pentesters often need to automate multiple requests. Here’s an example using a loop:
for i in {1..10}; do curl -X GET "https://example.com/page$i" -H "Authorization: Bearer <token>"doneLet’s break down the code and understand it:
for i in {1..10}: Loops from 1 to 10"https://example.com/page$i": Dynamically constructs the URL for the page number for each iteration
Sometimes, you just want to check the HTTP response headers and discard the rest: curl - I "https://www.example.com/
Here is an example:

Figure 9.3 – Capturing the headers from an HTTP request
Tip
If you experience errors when creating HTTP requests in the Bash shell, send requests through a proxy or save a packet capture to aid troubleshooting. This will allow you to see what is being sent and received, which may look different from what you intended due to encoding issues.
Now that you have a good foundation of knowledge on using curl to make HTTP requests, let’s put that knowledge to work and examine a real-world use case. The next example will demonstrate how to use Bash scripting for SQLi payloads. The example code can be found in the ch09_sqliscanner.sh file in this chapter’s folder in the GitHub repository. As in previous chapters, I’ll be breaking the script up into sections so that I can explain the code. It may be helpful to open the code from GitHub on another screen or use split-screen to help you follow the script structure at a high level as we examine each line in detail in this text.
The following code is a function to check if curl and parallel dependencies are installed. If not, print an error message and exit:
#!/usr/bin/env bashcheck_dependencies() { for cmd in curl parallel; do if ! command -v $cmd &> /dev/null; then echo "$cmd could not be found. Please install it." exit 1 fi done}The print_usage function contains the usage instructions for the script:
print_usage() { echo "Usage: $0 -u URL -c COOKIE_HEADER" echo " $0 -f URL_FILE -c COOKIE_HEADER" echo "URL must contain 'FUZZ' where payloads should be inserted."}In another part of the script, if the proper command-line arguments are not provided, it calls this function, which prints the usage instructions.
The perform_sql_test function sets two local variables and initializes them to the two provided function arguments:
perform_sqli_test() { local url=$1 local cookie_header=$2In the following code, we ensure the URL contains FUZZ for payload insertion; otherwise, print an error and exit:
if [[ $url != *"FUZZ"* ]]; then echo "Error: URL must contain 'FUZZ' where payloads should be inserted." print_usage exit 1fiHere we define an array of SQLi payloads:
local payloads=( "(SELECT(0)FROM(SELECT(SLEEP(7)))a)" "'XOR(SELECT(0)FROM(SELECT(SLEEP(7)))a)XOR'Z" "' AND (SELECT 4800 FROM (SELECT(SLEEP(7)))HoBG)--" "if(now()=sysdate(),SLEEP(7),0)" "'XOR(if(now()=sysdate(),SLEEP(7),0))XOR'Z" "'XOR(SELECT CASE WHEN(1234=1234) THEN SLEEP(7) ELSE 0 END)XOR'Z")In the following code, we loop through the array of payloads:
for payload in "${payloads[@]}"; do start_time=$(date +%s)The start time is saved to the start_time variable for reference at the end of the loop.
The fuzzed_url variable is assigned the result of the ${url//FUZZ/$payload} parameter expansion:
fuzzed_url=${url//FUZZ/$payload}This is a parameter expansion syntax in Bash used for string manipulation. This tells Bash to replace all occurrences of the FUZZ string within the url variable with the current value of $payload.
Here we send a request to the fuzzed URL with or without the cookie header, depending on command-line arguments:
if [ -n "$cookie_header" ]; then curl -s -o /dev/null --max-time 20 -H "Cookie: $cookie_header" "$fuzzed_url"else curl -s -o /dev/null --max-time 20 "$fuzzed_url"fiThe following code calculates the duration of the request:
end_time=$(date +%s)duration=$((end_time - start_time))The following code checks if the request duration indicates a potential time-based SQLi vulnerability:
if ((duration >= 7 && duration <= 16)); then echo "Potential time-based SQL injection vulnerability detected on $url with payload: $payload" break fi done}export -f perform_sqli_testA value of 7 seconds was included in each payload. We expect the response to take at least 7 seconds or longer based on network conditions and server load. We exported the function so that it can be called in the shell.
Here we process a list of URLs by either reading from a file or using a single URL:
process_urls() { local url_list=$1 local cookie_header=$2 if [ -f "$url_list" ]; then cat "$url_list" | parallel perform_sqli_test {} "$cookie_header" else perform_sqli_test "$url_list" "$cookie_header" fi}Next, we call the check_dependencies function defined at the start of the script:
check_dependenciesThe following code parses the command-line arguments for the URL, URL file, and cookie header:
while getopts "u:f:c:" opt; do case $opt in u) URL=$OPTARG ;; f) URL_FILE=$OPTARG ;; c) COOKIE_HEADER=$OPTARG ;; *) echo "Invalid option: -$OPTARG" ;; esacdoneHere we validate the input and ensure that either a URL or a URL file is provided:
if [ -z "$URL" ] && [ -z "$URL_FILE" ]; then echo "You must provide a URL with -u or a file containing URLs with -f." print_usage exit 1fiNext, we process the URLs based on the provided input:
if [ -n "$URL" ]; then process_urls "$URL" "$COOKIE_HEADER"elif [ -n "$URL_FILE" ]; then process_urls "$URL_FILE" "$COOKIE_HEADER"fiThe following output is found in the terminal after one of the payloads results in a response that takes longer than 7 seconds to complete. The URL and payload that triggered the SQLi is printed to the terminal:

Figure 9.4 – A successful SQLi URL and payload are printed to the terminal
Tip
When including authentication cookies or tokens with a curl request, bear in mind the difference between the -b and -H options. If you use -b, curl inserts Cookie: in the request, followed by the cookie value you specify. If you use -H, supply the full value. See the -b parameter in Figure 9*.4* where I left off the beginning of the Cookie header, and compare that to Figure 9*.5*.

Figure 9.5 – The Cookie header is highlighted to make a point
After learning about curl, I want to briefly mention wget. Both curl and wget are command-line tools for downloading files from the internet, but they have different features and use cases.
The following are features of curl:
- Designed for transferring data with URL syntax
- Supports a wide range of protocols (HTTP, HTTPS, FTP, SFTP, SCP, and so on)
- Can send data to a server using various HTTP methods (
GET,POST,PUT,DELETE, and so on) - Supports uploading files
- More suitable for complex operations such as interacting with APIs
The following are features of wget:
- Primarily designed for downloading files from the web
- Supports HTTP, HTTPS, and FTP protocols
- Can recursively download files, which makes it useful for mirroring websites
- Designed to handle unreliable network connections by retrying downloads
- More suitable for bulk downloading and website mirroring
The most straightforward use of wget is to download a single file from a URL:
$ wget http://example.com/file.zipYou can specify a different name for the downloaded file using the - O option:
$ wget -O newname.zip http://example.com/file.zipIf a download gets interrupted, you can resume it with the - c option:
$ wget -c http://example.com/file.zipYou can download files in the background using the - b option:
$ wget -b http://example.com/file.zipYou can mirror a website using the -r (recursive) and -p (page requisites) options. The -k option converts the links to be suitable for local viewing:
$ wget -r -p -k http://example.com/You can limit the download speed using the -- limit-rate option:
$ wget --limit-rate=100k http://example.com/file.zipYou can download files with a specific file extension using the - A option:
$ wget -r -A pdf http://example.com/In this section, you learned the most commonly used curl and wget options and examined common uses. Using curl and wget in Bash scripts allows pentesters to interact with web applications efficiently, sending customized requests to identify and exploit vulnerabilities. Mastering these options and techniques is essential for effective web application pentesting.
The next section will show how to use more advanced web application pentesting tools that you can use in the Bash shell, such as various ProjectDiscovery tools, as well as running command-line ZAP scans.
Analyzing web application security with Bash
Section titled “Analyzing web application security with Bash”This section will examine common command-line tools that you should have in your toolbox for web application security testing.
ProjectDiscovery
Section titled “ProjectDiscovery”ProjectDiscovery maintains a variety of command-line tools you can run in your Bash shell. They’re designed to accept input and pass output via the shell pipeline, allowing you to chain together multiple tools. Their most popular tools include the following:
nuclei: An open source vulnerability scanner that uses YAML templatesnuclei-templates: Templates for thenucleiengine to find security vulnerabilitiessubfinder: A passive subdomain enumeration toolhttpx: An HTTP toolkit that allows running sending probes to identify HTTP servicescvemap: A CLI to search for CVEkatana: A web crawling and spidering frameworknaabu: A port scanner that integrates easily with other ProjectDiscovery toolsmapcidr: A utility program to perform multiple operations for a given subnet/CIDR range
You can find the ProjectDiscovery tools at https://github.com/projectdiscovery.
An example workflow combining these tools would start with mapcidr to expand a network address into individual IP addresses, piped to naabu to scan for open ports, piped to httpx to discover web services, and piped to nuclei to test for known vulnerabilities.
Let’s examine some of these tools individually before experimenting with how they can be used together in a chain.
The mapcidr tool accepts input via stdin. Here’s an example usage:
$ echo 10.2.10.0/24 | mapcidr -silentExample output is shown in the following figure:

Figure 9.6 – An example of mapcidr usage
In the preceding figure, I use the Bash shell pipe (|) operator to pass the network address to the input of the mapcidr tool. The output contains the network address expanded to individual IP addresses.
Tip
By default, all ProjectDiscovery tools output a banner. Since we’ll be piping the output of each tool to the input of the next tool, this is undesired behavior. Include the -silent option with the ProjectDiscovery tools to suppress the banner.
The naabu tool is a ProjectDiscovery tool that scans for open ports. You can include command-line options that follow up on each open port with an nmap scan, in addition to a large list of other options. Where naabu becomes helpful is its ability to fit in a command pipeline, piping the stdout of one ProjectDiscovery tool to the stdin of the next. In its default configuration, naabu scans a limited number of ports. However, command-line options include the ability to specify a list or range of ports:

Figure 9.7 – An example naabu port scan is executed
The ProjectDiscovery httpx tool probes open ports for listening HTTP servers:

Figure 9.8 – An example httpx scan is executed
In the preceding figure, I use the Bash shell pipe (|) operator to send the IP address 10.2.10.1 to the naabu stdin input. I include the silent option (-silent) to suppress banner output, followed by a list of ports (-p). The output is piped to the httpx tool using the -silent option. The output of https is a list of HTTP URLs.
The ProjectDiscovery nuclei tool scans for known vulnerabilities and misconfigurations. The nuclei templates also include fuzzing templates that scan for unknown vulnerabilities belonging to common vulnerability classes such as cross-site scripting (XSS) and SQLi.
The following figure demonstrates a nuclei scan:

Figure 9.9 – An example nuclei scan is executed in a piped command
Tip
ProjectDiscovery tools have far more capability than I’ve shown here. You really should take the time to explore the documentation. These tools are an important part of any pentester or bug bounty hunter’s toolbox.
The ProjectDiscovery katana tool crawls or spiders web applications and prints discovered URLs. The following figure demonstrates using the katana tool to crawl a website:

Figure 9.10 – The katana tool is used to crawl a website
In the next figure, I demonstrate piping output (|) from a katana crawl to a nuclei scan using the fuzzing templates (-dast option). An XSS vulnerability is detected and displayed in the tool output:

Figure 9.11 – Katana output is piped to a nuclei scan
Tip
When running tools in the Bash shell that connect to websites, always change the user agent, as shown in the preceding figures. You’ll frequently get blocked if you use the default user agent.
Of course, you’re not limited to piping the ProjectDiscovery tool output to other ProjectDiscovery tools. This command uses the Bash pipe to send httpx output to dirsearch to discover content:
$ echo 10.2.10.1 | naabu -silent -p 4712,5005,5555,8080,8090,8111 | httpx -silent | dirsearch --stdin --full-url -q -o dirsearch.csv --format=csvLet’s look at the explanation:
- As before, I echo the IP address and pipe it to the input to
naabuwith the silent option and a list of ports - The output of the
naabuport scan is piped tohttpx - The URL’s output from
httpxis piped todirsearchfor content discovery - The
dirsearchoptions accept input fromstdin(--stdin), output the full URL (--full-url), suppress printing any banners (-q), and save the output (-o) to a file in CSV format (--format=csv)
An awk filter I commonly use to show only 200 or 302 responses from the CSV file uses a comma field separator (-F',') and filters the second field for 200 or 302 responses is shown as follows:
$ awk -F',' '$2 == 200 || $2 == 302 {print $0}' dirsearch.csvThe ProjectDiscovery tools are great for discovering known vulnerabilities and misconfigurations. A recent update extended nuclei ’s ability to fuzz for vulnerabilities. However, for more thorough web application vulnerability scans, I would recommend using ZAP. Think of these tools as complementary. Let’s move forward and explore ZAP scans.
Running command-line scans with ZAP
Section titled “Running command-line scans with ZAP”ZAP is a web application vulnerability scanner and browser proxy.
The GUI component of ZAP can be started from the GUI system menu or the terminal with the zaproxy command. However, this section will focus on running the /usr/share/zaproxy/zap.sh command-line scanner.
Enter this command in your Bash terminal to examine ZAP command-line options:
$ /usr/share/zaproxy/zap.sh -hOne of the commands I run at the beginning of any web application pentest is zapit. This performs a quick reconnaissance scan. The output lists important details about the web application. Before running zapit, you must install the wappalyzer add-on using the following command:
$ /usr/share/zaproxy/zap.sh -cmd -addoninstall wappalyzerYou need to run the add-on installation command only once. Next, run a zapit scan. In this example, I’m scanning an application in my lab:

Figure 9.12 – A zapit scan fingerprints the web application
Tip
You can find a large list of vulnerable web app lications for your lab at https://github.com/vulhub/vulhub.
In the preceding figure, you see that the zapit scan revealed the application frameworks in the Technology section and some interesting information in the Number of alerts section. This is critical information needed for any application pentest.
Next, let’s run a vulnerability scan of the application. For the output parameter value (-quickout), we precede the path with $(pwd) to save the report to the current working directory because we don’t have permission to write to /usr/share/zaproxy:
$ /usr/share/zaproxy/zap.sh -cmd -addonupdate -quickurl http://10.2.10.1:5555/ -quickout $(pwd)/zap.jsonLet’s take a look at the output:

Figure 9.13 – Examining the ZAP quick scan output in JSON format
ZAP scan output can be saved in HTML, JSON, Markdown, and XML formats. For human-readable outputs, stick with HTML reports. For inclusion in an automation framework that relies on using Bash scripting to parse the output, use either JSON or XML.
This section covered common use cases for using ProjectDiscovery and ZAP in your Bash shell. We’ve just scratched the surface here. There are many more options available in ProjectDiscovery tools and ZAP, including configuring automated scanning with credentials.
The next section will explore using Bash aliases and functions to transform data related to web application pentesting.
Learning advanced data manipulation techniques
Section titled “Learning advanced data manipulation techniques”In this section, we’ll explore various data encoding, encryption, and hashing algorithms that are common to testing web application security. You can put these functions in your .bashrc file and call them in your scripts. The following functions can be found in this chapter’s GitHub repository as ch09_data_functions.sh.
Base64 encoding is a method for converting binary data into an ASCII string format by encoding it into a Base64 representation. This encoding uses a set of 64 characters, including uppercase and lowercase letters (A-Z, a-z), digits (0-9), and the symbols + and /, to represent the data. The primary purpose of Base64 encoding is to ensure that binary data, such as images or files, can be safely transmitted over media that are designed to handle textual data, such as email and URLs, without corruption. Base64 encoding also adds padding with the = character to ensure the encoded data is a multiple of 4 bytes, maintaining data integrity during transport and storage. Base64 encoding in Bash is very simple.
Here is a Base64 encoding example:
$ echo -n hello | base64aGVsbG8=And the following is a Base64 decoding example:
$ echo -n aGVsbG8= | base64 -dhelloBase64 encoding and Base64 URL-safe encoding are methods for converting binary data into text strings, but they differ in their character sets and intended use cases. Base64 encoding uses a set of 64 characters, including uppercase and lowercase letters (A-Z, a-z), digits (0-9), and two special characters (+ and /). This encoding is often used to encode data that needs to be stored or transmitted over media designed to handle textual data. However, the + and / characters are not URL-safe, which can cause issues when used in URLs or filenames. To address this, Base64 URL-safe encoding modifies the character set by replacing + with - (hyphen) and / with _ (underscore), and it typically omits padding characters (=). This ensures that the encoded data can be safely included in URLs and filenames without the risk of being misinterpreted or causing errors.
This function encodes data to a URL-safe Base64 representation:
url_safe_base64_encode() { base64 | tr '+/' '-_' | tr -d '='}An example of URL-safe Base64 decoding is demonstrated here:
url_safe_base64_decode() { tr '-_' '+/' | base64 --decode}The gzip data format is extensively utilized in HTTP communications to compress data transferred between web servers and clients, enhancing the efficiency of data transmission. When a web server sends data to a client, such as a web browser, it can use gzip to compress the content, significantly reducing the file size and thereby speeding up the download process. The compressed data includes a header with metadata, the compressed content, and a footer with a Cyclic Redundancy Check 32 (CRC-32) checksum for verifying data integrity. Clients that support gzip, indicated via the Accept-Encoding: gzip HTTP header, can decompress the received content using gunzip to display or process the original data. This method of compression helps to improve load times, reduce bandwidth usage, and enhance overall web performance.
The gzip program is commonly installed on Linux systems by default. Here are some examples showing how to compress and uncompress data in the Bash shell:

Figure 9.14 – A demonstration of compressing and uncompressing data
Message-Digest Algorithm 5 (MD5) hashing is a widely used cryptographic hash function that produces a 128-bit (16-byte) hash value, typically rendered as a 32-character hexadecimal number. MD5 takes an input (or message) and returns a fixed-size string of characters, which is unique to the input data. However, MD5 is considered weak due to its susceptibility to hash collisions, where two different inputs produce the same hash output. MD5 is no longer recommended for security-critical applications, with more secure algorithms such as Secure Hash Algorithm 256-bit (SHA-256) being preferred for hashing purposes.
The following function creates an MD5 hash of a string:
md5_hash() { md5sum | awk '{print $1}'}The following is another example:
$ echo helloworld | md5_hashd73b04b0e696b0945283defa3eee4538SHA-256 is a cryptographic hash function that generates a fixed-size 256-bit (32-byte) hash value from any input data, often represented as a 64-character hexadecimal number. Developed by the National Security Agency (NSA) and part of the SHA-2 family, SHA-256 takes an input and produces a unique output, acting like a digital fingerprint of the data. It’s designed to be computationally infeasible to reverse the process or find two different inputs that produce the same hash (a collision). This makes SHA-256 highly secure and reliable for verifying data integrity and authenticity, which is why it’s widely used in various security applications, including SSL/TLS certificates, digital signatures, and blockchain technology.
This function prints a SHA-256 hash of an input:
sha256_hash() { sha256sum | awk '{print $1}'}See the following example:
$ echo helloworld | sha256_hash8cd07f3a5ff98f2a78cfc366c13fb123eb8d29c1ca37c79df190425d5b9e424dAdvanced Encryption Standard with a 256-bit key (AES-256) is a symmetric encryption algorithm widely used to secure data. It works by taking plaintext data and transforming it into ciphertext using a secret key, ensuring that only someone with the same key can decrypt and access the original information. The 256 in AES-256 refers to the length of the encryption key, which is 256 bits long, making it extremely difficult to break using brute-force attacks. AES-256 is known for its strong security and efficiency, which is why it is commonly used for protecting sensitive data in applications such as secure file storage, internet communications, and financial transactions.
The following is an AES encryption function:
aes_encrypt() { local password="$1" openssl enc -aes-256-cbc -base64 -pbkdf2 -pass pass:"$password"}This function must be called as follows: echo "data to be encrypted" | aes_encrypt "password".
This is an AES decryption function:
aes_decrypt() { local password="$1" openssl enc -aes-256-cbc -d -base64 -pbkdf2 -pass pass:"$password"}The openssl command specifies the AES algorithm with a 256-bit key size in Cipher Block Chaining (CBC) mode. The -d option means to decrypt. The -pbkdf2 option indicates that the Password-Based Key Derivation Function 2 (PBKDF2) algorithm is used to derive the encryption key from a password. This enhances security by making brute-force attacks more difficult, as it applies a computationally intensive function iteratively.
Similar to the encryption function, the data to decrypt must be passed in via a stdin pipe, and the decryption password must follow: echo "data to be decrypted" | aes_decrypt "password".
Here is an AES-256 encryption and decryption example:
$ echo "data to be encrypted" | aes_encrypt 'Passw0rd!' | aes_decrypt 'Passw0rd!'data to be encryptedHTML encoding is the process of converting special characters in HTML into their corresponding character entities to ensure they are displayed correctly in web browsers. This is necessary because certain characters, such as <, >, &, and ", have specific meanings in HTML syntax and can disrupt the structure of the HTML document if not properly encoded. For instance, < is used to start a tag, so encoding it as < prevents it from being interpreted as the start of an HTML tag. Conversely, HTML decoding converts these character entities back into their original characters. This process is crucial for web security and functionality, as it prevents HTML injection attacks and ensures that content is rendered correctly without unintended formatting or behavior. By encoding special characters, developers can safely include user-generated content, code snippets, or other data within HTML documents without risking the integrity of the web page.
The following HTML function encodes the input:
html_encode() { local input input=$(cat) input="${input//\&/\&}" input="${input//\</\<}" input="${input//\>/\>}" input="${input//\"/\"}" input="${input//\'/\'}" echo "$input"}Reminder
The following characters must be escaped when included as part of a string, as seen in the html_encode and html_encode functions: \, $,`, ', ", &, *, ?, (, ), {, }, [, ], |, ;, <, >, !, #, ~, ^.
It is not necessary to escape them when the characters are used inside single quotes.
Here is an example of escaping these characters:
$ echo 'hello<script>world' | html_encodehello<script>worldHere’s the corresponding decoding function:
html_decode() { local input input=$(cat) input="${input//\'/\'}" input="${input//\"/\"}" input="${input//\>/\>}" input="${input//\</\<}" input="${input//\&/\&}" echo "$input"}Here is an example of HTML decoding data:
$ echo 'hello<script>world' | html_decodehello<script>worldThe section demonstrated how to use Bash to convert common data formats found in web application pentesting. Populate your .bashrc file with these functions in advance, and you’ll be prepared to solve even the most advanced data manipulation tasks in your pentests.
Summary
Section titled “Summary”You can’t always depend on having the ability to install tools or programming libraries in the testing environment. Bash scripting provides a way to use the built-in shell and tools to accomplish almost any task. In hindsight, there were many times in my career when I felt that I was hindered in my ability to accomplish a test without installing additional tools, or resorted to writing the tool in another language such as Python. This was due to my lack of knowledge of Bash scripting. Armed with this knowledge, you’re ready to tackle the most complex web application testing challenges using Bash.
In the next chapter, we’ll explore network and infrastructure pentesting with Bash.