Shell Scripting for Hacking: Linking Tools Through Pipes
The power of bash is in its pipes. Each utility does one thing well, and bash glues them together into a chain. According to hadess.io, "the real power of Bash in security is piping output between tools." Let's look at some common connections.
nmap → nikto. After discovering the HTTP ports, you need to check the web server for known vulnerabilities. The chain: grep '/tcp.*http' nmap.txt | grep -oE '^[0-9]+' | while read -r port; do nikto -h "http://$IP:$port" -o "nikto_$port.txt"; doneEach HTTP port from nmap output is automatically passed through nikto. The output is a separate file for each port.
Bulk flag search in the archive. CTFs often require combing through the downloaded archive: find . -type f -exec grep -lH "flag{" {} \; 2>/dev/null. findrecursively finds files, grep -lHoutputs the file name of the match. Redirection 2>/dev/nullSuppresses errors in binary files.
File integrity check. In forensics tasks: find /etc -type f -exec sha256sum {} \; creates a base snapshot, and diff baseline.txt current.txt | grep "^[<>]"detects changes. This technique also works in real-world incident response—hadess.io describes a similar script for File Integrity Check.
Certificate Monitoring. During a long-term penetration test, it's useful to track the expiration dates of TLS certificates: echo | openssl s_client -servername "$domain" -connect "$domain:443" 2>/dev/null | openssl x509 -noout -enddate | cut -d= -f2Extracts the expiration date. Wrap it in a loop over the list of domains – ready-made monitoring.
Subdomain enumeration → live check. For CTFs with realistic infrastructure: subfinder -d target.com -silent | sort -u | while read -r sub; do curl -s -o /dev/null --max-time 5 -w "%{http_code} $sub\n" "http://$sub"; done | grep -v "^000". subfinderfinds subdomains, curl -w "%{http_code}"checks the response code, grep -v "^000"filters unavailable hosts.
Bash Scripting for Hackers: Five Rookie Mistakes
Each of these mistakes cost me or someone I know anywhere from 20 minutes to an hour on CTFs. I've compiled the five most painful ones.
1. Forgotten quotes around variables. Command grep $PATTERN file.txtwill break if PATTERNcontains a space. Correct: grep "$PATTERN" file.txt. Similarly with paths: cd $DIR at DIR="my folder"will try to go to myHabit: Always wrap variables in double quotes.
2. for line in $(cat file)instead of while read -r line. Construction forloads the entire file into memory and splits it on spaces - line hello worldwill become two iterations. while read -r line; do ...; done < fileReads line by line, preserving spaces. On wordlists tens of megabytes in size, this is the difference between a working script and a dead one.
3. Ignoring return codes If nmapThe script terminated with an error, but it continues to run—you're parsing an empty file and can't figure out why nothing's found. Solution: set -eat the beginning of the script or manual checking $?after critical commands. set -euo pipefailcovers three types of failures simultaneously.
4. Unescaped special characters in regex. A period in regex is any character. Search grep 192.168.1.1 will coincide with 192X168Y1Z1. Correct: grep -F '192.168.1.1'(fixed string) or grep '192\.168\.1\.1'(escaped dots). In CTFs with log parsing, this error leads to false matches and wasted time.
5. Useless Use of Cat. cat file | grep pattern- an extra process. greptakes a file as an argument: grep pattern fileIn a single call the difference is imperceptible, but in a loop over 14 million rows rockyou.txtThe total losses are significant. If the utility accepts a file as an argument, don't feed it through cat.
Automating CTF tasks: what does the protection see?
Bash scripts for CTFs are an attack technique, but it's useful to understand what your activity looks like from a different perspective. Sigma rules from the SigmaHQ repository cover the detection of suspicious shell activity: lnx_shell_susp_commands.ymlcatches typical reconnaissance commands (user enumeration, network reconnaissance). lnx_shell_susp_rev_shells.yml— attempts to create reverse shells. lnx_shell_priv_esc_prep.yml— preparation for privilege escalation: searching for SUID binaries, reading /etc/shadow, enumeration of sudo privileges. There are 20 detection rules in SigmaHQ for the T1059.004 tag.
For T1082 System Information Discovery - 36 rules, including lnx_auditd_system_info_discovery.yml, tracking the launch uname, hostname, cat /etc/os-releasevia auditd. These are the same commands that are run first during CTFs.
Knowing what's being detected helps you better navigate a protected infrastructure. CTF setups typically don't have EDR, and these rules aren't active. But in a real pentest, understanding the detection changes the approach: instead of a noisy nmap -sV -sCfor all ports - targeted checks of specific services.
Countermeasures from MITRE D3FEND complete the picture. Countermeasures against T1059.004 Unix Shell: Executable Allowlisting (D3-EAL) — allow only approved binaries to run; File Analysis (D3-FA) — analyze file contents before execution; File Integrity Monitoring (D3-FIM) — monitor changes to critical files. Countermeasures against T1110.001 Password Guessing: Password Rotation (D3-PR), One-time Password (D3-OTP), Operational Process Monitoring (D3-OPM) — monitor authentication logs for abnormally high numbers of attempts.
Contact AbuseIPDB: If your IP has been detected by a mass port scan (category #14 Port Scan) or SSH brute force (category #22 SSH), it will be added to the database with a specific abuseConfidenceScoreIf the value is above 75, many organizations automatically block such IPs. This isn't a problem at CTFs—the booths are isolated. But if you accidentally point a script to a real host instead of the target, there will be consequences.
Bash automation at CTFs is the entry threshold, not the ceiling. I see two extremes: some solve each problem manually, wasting time copy-pasting between terminals, while others try to put together a universal Python framework before the competition. The former are constrained by speed, the latter by overengineering.
The working path is a set of 5-7 Bash scripts, each for a specific task: reconnaissance, brute force, log parsing, file processing. Not a framework, but a collection of tailored tools.
The power of bash is in its pipes. Each utility does one thing well, and bash glues them together into a chain. According to hadess.io, "the real power of Bash in security is piping output between tools." Let's look at some common connections.
nmap → nikto. After discovering the HTTP ports, you need to check the web server for known vulnerabilities. The chain: grep '/tcp.*http' nmap.txt | grep -oE '^[0-9]+' | while read -r port; do nikto -h "http://$IP:$port" -o "nikto_$port.txt"; doneEach HTTP port from nmap output is automatically passed through nikto. The output is a separate file for each port.
Bulk flag search in the archive. CTFs often require combing through the downloaded archive: find . -type f -exec grep -lH "flag{" {} \; 2>/dev/null. findrecursively finds files, grep -lHoutputs the file name of the match. Redirection 2>/dev/nullSuppresses errors in binary files.
File integrity check. In forensics tasks: find /etc -type f -exec sha256sum {} \; creates a base snapshot, and diff baseline.txt current.txt | grep "^[<>]"detects changes. This technique also works in real-world incident response—hadess.io describes a similar script for File Integrity Check.
Certificate Monitoring. During a long-term penetration test, it's useful to track the expiration dates of TLS certificates: echo | openssl s_client -servername "$domain" -connect "$domain:443" 2>/dev/null | openssl x509 -noout -enddate | cut -d= -f2Extracts the expiration date. Wrap it in a loop over the list of domains – ready-made monitoring.
Subdomain enumeration → live check. For CTFs with realistic infrastructure: subfinder -d target.com -silent | sort -u | while read -r sub; do curl -s -o /dev/null --max-time 5 -w "%{http_code} $sub\n" "http://$sub"; done | grep -v "^000". subfinderfinds subdomains, curl -w "%{http_code}"checks the response code, grep -v "^000"filters unavailable hosts.
Bash Scripting for Hackers: Five Rookie Mistakes
Each of these mistakes cost me or someone I know anywhere from 20 minutes to an hour on CTFs. I've compiled the five most painful ones.
1. Forgotten quotes around variables. Command grep $PATTERN file.txtwill break if PATTERNcontains a space. Correct: grep "$PATTERN" file.txt. Similarly with paths: cd $DIR at DIR="my folder"will try to go to myHabit: Always wrap variables in double quotes.
2. for line in $(cat file)instead of while read -r line. Construction forloads the entire file into memory and splits it on spaces - line hello worldwill become two iterations. while read -r line; do ...; done < fileReads line by line, preserving spaces. On wordlists tens of megabytes in size, this is the difference between a working script and a dead one.
3. Ignoring return codes If nmapThe script terminated with an error, but it continues to run—you're parsing an empty file and can't figure out why nothing's found. Solution: set -eat the beginning of the script or manual checking $?after critical commands. set -euo pipefailcovers three types of failures simultaneously.
4. Unescaped special characters in regex. A period in regex is any character. Search grep 192.168.1.1 will coincide with 192X168Y1Z1. Correct: grep -F '192.168.1.1'(fixed string) or grep '192\.168\.1\.1'(escaped dots). In CTFs with log parsing, this error leads to false matches and wasted time.
5. Useless Use of Cat. cat file | grep pattern- an extra process. greptakes a file as an argument: grep pattern fileIn a single call the difference is imperceptible, but in a loop over 14 million rows rockyou.txtThe total losses are significant. If the utility accepts a file as an argument, don't feed it through cat.
Automating CTF tasks: what does the protection see?
Bash scripts for CTFs are an attack technique, but it's useful to understand what your activity looks like from a different perspective. Sigma rules from the SigmaHQ repository cover the detection of suspicious shell activity: lnx_shell_susp_commands.ymlcatches typical reconnaissance commands (user enumeration, network reconnaissance). lnx_shell_susp_rev_shells.yml— attempts to create reverse shells. lnx_shell_priv_esc_prep.yml— preparation for privilege escalation: searching for SUID binaries, reading /etc/shadow, enumeration of sudo privileges. There are 20 detection rules in SigmaHQ for the T1059.004 tag.
For T1082 System Information Discovery - 36 rules, including lnx_auditd_system_info_discovery.yml, tracking the launch uname, hostname, cat /etc/os-releasevia auditd. These are the same commands that are run first during CTFs.
Knowing what's being detected helps you better navigate a protected infrastructure. CTF setups typically don't have EDR, and these rules aren't active. But in a real pentest, understanding the detection changes the approach: instead of a noisy nmap -sV -sCfor all ports - targeted checks of specific services.
Countermeasures from MITRE D3FEND complete the picture. Countermeasures against T1059.004 Unix Shell: Executable Allowlisting (D3-EAL) — allow only approved binaries to run; File Analysis (D3-FA) — analyze file contents before execution; File Integrity Monitoring (D3-FIM) — monitor changes to critical files. Countermeasures against T1110.001 Password Guessing: Password Rotation (D3-PR), One-time Password (D3-OTP), Operational Process Monitoring (D3-OPM) — monitor authentication logs for abnormally high numbers of attempts.
Contact AbuseIPDB: If your IP has been detected by a mass port scan (category #14 Port Scan) or SSH brute force (category #22 SSH), it will be added to the database with a specific abuseConfidenceScoreIf the value is above 75, many organizations automatically block such IPs. This isn't a problem at CTFs—the booths are isolated. But if you accidentally point a script to a real host instead of the target, there will be consequences.
Bash automation at CTFs is the entry threshold, not the ceiling. I see two extremes: some solve each problem manually, wasting time copy-pasting between terminals, while others try to put together a universal Python framework before the competition. The former are constrained by speed, the latter by overengineering.
The working path is a set of 5-7 Bash scripts, each for a specific task: reconnaissance, brute force, log parsing, file processing. Not a framework, but a collection of tailored tools.