Bash Command Injection Cheat Sheet

Command Injection vulnerabilities are a class of application security issue where an attacker can cause the application to execute an underlying operating system command. For that reason it’s generally a high impact issue. It can be exploited simply by chaining commands along with the expected input by using shell control characters such as:

  1. Kali Linux Cheat Sheet NMAP COMMAND DESCRIPTION nmap –v –sS –A –T4 target Nmap verbose scan, runs syn stealth, T4 timing (should be ok on LAN), OS and service version info, traceroute and scripts against services nmap -v -sS -p–A -T4 target As above but scans all TCP ports (takes a lot longer).
  2. SYSTEM INFORMATION. # Display Linux system information uname -a # Display kernel release.

Developers have a variety of reasons why they might want their web applications to execute underlying operating system commands. One example could be an application that allows a user to check if a host is online by pinging its IP address. The URL for this function could look something like this:

and the output on the screen could be:

Sure, Linux command line tools have help features, but they can be pretty cumbersome. That’s why cheat sheets exist, folks, and they can be a real life saver. Well, maybe a cheat sheet won’t save your life, but it can certainly save you oodles of time, headaches, frustration, and invalid commands. Command Injection. Test HTTP options using curl. Meterpreter Linux Reverse Payload; Meterpreter Cheat Sheet. Upload file c: windows. See full list on

However if user input is insecurely passed to this function a user could chain a command on the end, such as ” && id” and this would be executed along with the main command, changing the input in our example to this:

and so the output on the screen would be:

As you might guess from above, the user gains the permissions that the affected application has, so if it’s running as www-data or root you’d get that privilege level! An easy way to compromise a box and potentially allow an attacker to take over the webserver, deface the application or steal confidential data!

However things get more complicated for the attacker is the system does not show the output in the application itself, it might just silently execute the command and output something generic like “Success” or “done”. If this is the case an attacker can still determine the existance of the vulnerability and blindly exploit it through inference.

For example imaging chaining to the end of the input the linux command “sleep”, such as:

With this request the output, if vulnerable, would come through as expected with the “Success” message, however it would take a noticable about of time to return – something around 10 seconds longer than without the payload. To determine if this was just a laggy server or not you could try multiple different delay levels to see if the received delay matches the expected amount. So sleep 10 causes approximately a 10 second delay and sleep 30 causes approximately a 30 second delay, reducing the likelihood that this is a false positive.

At this point you’ve got a successful Blind Command Injection vulnerability! Before I get on to how to utilise that as an attacker however, there’s one more type to deal with. Blind injection with out-of-band detection. This class occurs is a vulnerability is vulnerable but no change in output can be perceived through the application, for example if the application executes the request in a new thread, so delaying the server through the “sleep” command doesn’t work (or at least can’t be perceived through the application itself).

In this case we can get our “noticable change” by calling out to another server and monitoring that server for requests. For example you could try a payload like the following:

This would cause an affected (Linux) server to call out to the attacker’s machine. The wget command online requests the server download a web page. Therefore the attacker could see that the payload worked successfully as their logs would show a GET request to the file: /?attacksuccessful

Now to turn that into a viable attack payload to, for example, steal confidential files the attacker could try chaining the contents of the file in the request to the attackers server! A payload like this would be effective:

Here the attacker is taking the contents of the confidential file /etc/password, encoding it with base64 so that it’s possible to transmit it in a URL and then using the wget command again to send that file in a HTTP GET request to the atttacker controlled server! One thing to remember is that the base64 command will line wrap by default after 76 characters, but you can use -w 0 parameter to disable this, like this:

As you can imagine, this is a pretty bad vulnerability which I’ve seen multiple times during Penetration Testing engagements but I’ve seen little in the way of content online about the issue, so I thought I’d throw a few notes down in a post. The important part though: there are specific ways to secure command execution depending on your underlying language and programming framework however one thing that’ll work for general cases is effective user input filtering! Luckily, I’ve written about that here!
Again, the minimum characters to consider dangerous in regards to this issue are:

Payloads can be incredibly varied as the attacker has an awful lot of flexibility, but a few simple ones are things like:

The Following Penetration Testing Cheat Sheet Linux System is for usage during local enumeration,post exploitation or when performing command injection etc.

netstat -tulpnShow Linux network ports with process ID’s (PIDs)
watch ss -stpluWatch TCP, UDP open ports in real time with socket summary.
lsof -iShow established connections.
macchanger -m MACADDR INTRChange MAC address on KALI Linux.
ifconfig eth0 IP address in Linux.
ifconfig eth0:1 IP address to existing network interface in Linux.
ifconfig eth0 hw ether MACADDRChange MAC address in Linux using ifconfig.
ifconfig eth0 mtu 1500Change MTU size Linux using ifconfig, change 1500 to your desired MTU.
dig -x Dig reverse lookup on an IP address.
host Reverse lookup on an IP address, in case dig is not installed.
dig @ -t AXFRPerform a DNS zone transfer using dig.
host -l nameserverPerform a DNS zone transfer using host.
nbtstat -A x.x.x.xGet hostname for IP address.
ip addr add dev eth0Adds a hidden IP address to Linux, does not show up when performing an ifconfig.
tcpkill -9 host google.comBlocks access to from the host machine.
echo '1' > /proc/sys/net/ipv4/ip_forwardEnables IP forwarding, turns Linux box into a router – handy for routing traffic through a box.
echo '' > /etc/resolv.confUse Google DNS.

System Information Commands

Useful for local enumeration.

whoamiShows currently logged in user on Linux.
idShows currently logged in user and groups for the user.
lastShows last logged in users.
mountShow mounted drives.
df -hShows disk usage in human readable output.
echo 'user:passwd' | chpasswdReset password in one line.
getent passwdList users on Linux.
strings /usr/local/bin/blahShows contents of none text files, e.g. whats in a binary.
uname -arShows running kernel version.
PATH=$PATH:/my/new-pathAdd a new PATH, handy for local FS manipulation.
historyShow bash history, commands the user has entered previously.

Redhat / CentOS / RPM Based Distros

cat /etc/redhat-releaseShows Redhat / CentOS version number.
rpm -qaList all installed RPM’s on an RPM based Linux distro.
rpm -q --changelog openvpnCheck installed RPM is patched against CVE, grep the output for CVE.

YUM Commands

Package manager used by RPM-based systems, you can pull some useful information about installed packages and or install additional tools.

yum updateUpdate all RPM packages with YUM, also shows whats out of date.
yum update httpdUpdate individual packages, in this example HTTPD (Apache).
yum install packageInstall a package using YUM.
yum --exclude=package kernel* updateExclude a package from being updates with YUM.
yum remove packageRemove package with YUM.
yum erase packageRemove package with YUM.
yum list packageLists info about yum package.
yum provides httpdWhat a packages does, e.g Apache HTTPD Server.
yum info httpdShows package info, architecture, version etc.
yum localinstall blah.rpmUse YUM to install local RPM, settles deps from repo.
yum deplist packageShows deps for a package.
yum list installed | moreList all installed packages.
yum grouplist | moreShow all YUM groups.
yum groupinstall 'Development Tools'Install YUM group.

Debian / Ubuntu / .deb Based Distros

cat /etc/debian_versionShows Debian version number.
cat /etc/*-releaseShows Ubuntu version number.
dpkg -lList all installed packages on Debian / .deb based Linux distro.

Linux User Management

useradd new-userCreates a new Linux user.
passwd usernameReset Linux user password, enter just passwd if you are root.
deluser usernameRemove a Linux user.

Linux Decompression Commands

How to extract various archives (tar, zip, gzip, bzip2 etc) on Linux and some other tricks for searching inside of archives etc.

unzip archive.zipExtracts zip file on Linux.
zipgrep *.txt archive.zipSearch inside a .zip archive.
tar xf archive.tarExtract tar file Linux.
tar xvzf archive.tar.gzExtract a tar.gz file Linux.
tar xjf archive.tar.bz2Extract a tar.bz2 file Linux.
tar ztvf file.tar.gz | grep blahSearch inside a tar.gz file.
gzip -d archive.gzExtract a gzip file Linux.
zcat archive.gzRead a gz file Linux without decompressing.
zless archive.gzSame function as the less command for .gz archives.
zgrep 'blah' /var/log/maillog*.gzSearch inside .gz archives on Linux, search inside of compressed log files.
vim file.txt.gzUse vim to read .txt.gz files (my personal favorite).
upx -9 -o output.exe input.exeUPX compress .exe file Linux.

CWE-78: OS CommandInjection

Linux Compression Commands

zip -r /dir/*Creates a .zip file on Linux.
tar cf archive.tar filesCreates a tar file on Linux.
tar czf archive.tar.gz filesCreates a tar.gz file on Linux.
tar cjf archive.tar.bz2 filesCreates a tar.bz2 file on Linux.
gzip fileCreates a file.gz file on Linux.

Linux File Commands

df -h blahDisplay size of file / dir Linux.
diff file1 file2Compare / Show differences between two files on Linux.
md5sum fileGenerate MD5SUM Linux.
md5sum -c blah.iso.md5Check file against MD5SUM on Linux, assuming both file and .md5 are in the same dir.
file blahFind out the type of file on Linux, also displays if file is 32 or 64 bit.
dos2unixConvert Windows line endings to Unix / Linux.
base64 < input-file > output-fileBase64 encodes input file and outputs a Base64 encoded file called output-file.
base64 -d < input-file > output-fileBase64 decodes input file and outputs a Base64 decoded file called output-file.
touch -r ref-file new-fileCreates a new file using the timestamp data from the reference file, drop the -r to simply create a file.
rm -rfRemove files and directories without prompting for confirmation.

Samba Commands

Connect to a Samba share from Linux.


Breaking Out of Limited Shells

Credit to G0tmi1k for these (or wherever he stole them from!).

Pentesting Cheatsheet | Hausec

The Python trick:

Misc Commands

init 6Reboot Linux from the command line.
gcc -o output.c input.cCompile C code.
gcc -m32 -o output.c input.cCross compile C code, compile 32 bit binary on 64 bit Linux.
unset HISTORYFILEDisable bash history logging.
rdesktop X.X.X.XConnect to RDP server from Linux.
kill -9 $$Kill current session.
chown user:group blahChange owner of file or dir.
chown -R user:group blahChange owner of file or dir and all underlying files / dirs – recersive chown.
chmod 600 fileChange file / dir permissions, see [Linux File System Permissons](#linux-file-system-permissions) for details.

Clear bash history:

Linux File System Permissions

777rwxrwxrwx No restriction, global WRX any user can do anything.
755rwxr-xr-x Owner has full access, others can read and execute the file.
700rwx------ Owner has full access, no one else has access.
666rw-rw-rw- All users can read and write but not execute.
644rw-r--r-- Owner can read and write, everyone else can read.
600rw------- Owner can read and write, everyone else has no access.

Penetration Testing Cheat Sheet for Linux File System

// also know as “slash” or the root.
/binCommon programs, shared by the system, the system administrator and the users.
/bootBoot files, boot loader (grub), kernels, vmlinuz
/devContains references to system devices, files with special properties.
/etcImportant system config files.
/homeHome directories for system users.
/libLibrary files, includes files for all kinds of programs needed by the system and the users.
/lost+foundFiles that were saved during failures are here.
/mntStandard mount point for external file systems.
/mediaMount point for external file systems (on some distros).
/netStandard mount point for entire remote file systems – nfs.
/optTypically contains extra and third party software.
/procA virtual file system containing information about system resources.
/rootroot users home dir.
/sbinPrograms for use by the system and the system administrator.
/tmpTemporary space for use by the system, cleaned upon reboot.
/usrPrograms, libraries, documentation etc. for all user-related programs.
/varStorage for all variable files and temporary files created by users, such as log files, mail queue, print spooler. Web servers, Databases etc.

Linux Interesting Files / Dir’s

Places that are worth a look if you are attempting to privilege escalate / perform post exploitation.

/etc/passwdContains local Linux users.
/etc/shadowContains local account password hashes.
/etc/groupContains local account groups.
/etc/init.d/Contains service init script – worth a look to see whats installed.
/etc/hostnameSystem hostname.
/etc/network/interfacesNetwork interfaces.
/etc/resolv.confSystem DNS servers.
/etc/profileSystem environment variables.
~/.ssh/SSH keys.
~/.bash_historyUsers bash history log.
/var/log/Linux system log files are typically stored here.
/var/adm/UNIX system log files are typically stored here.
/var/log/apache2/access.log/var/log/httpd/access.logApache access log file typical path.
/etc/fstabFile system mounts.