понедельник, 1 октября 2018 г.

Better Web-Pentesting in Windows with AHK

(It's a repost from  https://www.acunetix.com/blog/web-security-zone/better-web-pentesting-in-windows-with-ahk/)

Recently, I have moved to Malta. It’s quite hot here, but as I’m from colder country, I like it very much. Actually, I’m obsessed with everything hot, including hotkeys!

Every pentester / researcher / bugbounter / etc has their own approach to doing things in their own work environment. So in this article I’m not looking to give exact solutions, but the aim is to share some ideas (which I found useful), so you can have a fresh look at your approach and push your imagination in this area.

Windows is not a very popular OS for pentesters due to many reasons. Sometimes however we need to use it (at least on a virtual machine). I have been a pentester for 8 years and pentested many “windows-only” applications, I remember that pain, I even got used to it… But, nowadays, everything is not so bad and hacky.

Today I want to discuss AutoHotKey. This is an old tool and, I’m sure, many of you use it for some kind of automations. I suggest to look at it as a tool for pentesters.


AHK – a small tool which can set global hotkeys and perform a lot of actions in OS. Actually, it has its own scripting language, and, if you have enough knowledge (and patience), you can do whatever you want.
I will not explain the syntax of the scripts (there is better doc about it here), but I’ll give you a bunch of examples.

So, the basic idea of AHK is quite simple: In scripts you set global hotkeys and once you press one of them, AHK will make the necessary action. All you need to do is install AHK, create your scripts and run them.

We all use many programs at once, but we need to use ALT+TAB to switch between them, it could be worse if you use multiple-desktop.
Using next script you can focus on a necessary program (or run it, if it’s closed), even if you are on another desktop, just by pressing Shift+Ctrl+F4 (+ – Shift, ^ – Ctrl)
SetTitleMatchMode 2
IfWinExist Sublime Text
WinActivate, Sublime Text
run "C:\Program Files\Sublime Text 3\sublime_text.exe"

IfWinExist Google Chrome
WinActivate, Google Chrome
run "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"


For researching/pentesting something related to web, you need to have all popular browsers at your hands. But it’s such a pain that they have different or lack of hotkeys.

For example, by clicking a hotkey (Ctrl+Tab) I can cycle through the last used tabs (not just next or previous tabs). It works out of the box for Firefox, but for Chrome you need an extension (CLUT: Cycle Last Used Tabs, for example). However even with the extension, you cannot bind Ctrl+Tab for this operation, because you cannot rebind Chrome’s hotkeys.

With AHK , you can easily achieve this. Firstly, AHK gives us an opportunity to set global hotkeys for specific applications. Secondly, we can “rebind” hotkeys. Here, only for Chrome, when we press Ctrl+Tab, AHK intercepts it and sends Alt+W into Chrome (! – Alt), so our extension shows us a last used tab.
#IfWinActive ahk_exe chrome.exe
Send, !w


Also, AHK supports hotstrings. What is it? When we input a specific consequence of symbols anywhere in Windows, AHK replaces it with whatever you want.

Typical example: Wherever I input two symbols “a” and “@“, they will be replaced with my email.
Here are some cases which I found useful.

When I pentested Windows-only applications with fat clients, it was annoying to input credentials again and again, especially, if it has “several layers of protection” or if you need to test multiple roles.
Here is a solution. Create a script which you use only during a project (with AHK you can run or stop as many ahk-scripts as you want at any time) with necessary credentials.

:*:!t1::testAccount :*:!p1::VeryLoooooongP4ssword :*:!t2::adminTestAccount :*:!p2::p4ssw0rd


Now, you can input them fast without using a text-document and clipboard 🙂
We still do a lot of web hacking manually, therefore, we can set hotstrings for most useful things, which we enter again and again.

Here are some self-explaining examples (here I use % just to make string more unique):
:*:%c.l::console.log('');{Left 3}

But we can improve it. For example, we can set our favourite payloads and also add random parts to them, so it will be easier to track input/output down in proxy. Wherever we print %xss1, it will be replaced with “<svg/onload=alert(17384)> you see, lol?
Random, rand, 1, 99999
SendInput "<svg/onload=alert(%rand%)>
Or with our DNS/HTTP connection-checker:
Random, rand, 1, 99999
SendInput http://x%rand%.yourserver.here/poc
web pentesting


When pentesting or researching something, we often work with strings and their encoding, modifications. We have some tools which help us (like HackBar addon for browsers) or use online resources. What if we can make it (semi-)global? For example, we select a string in any application, press a hotkey and get its base64-(de/en)coded version? Or md5-hash of it? Or any other mutation?

To be honest, the AHK’s scripting language doesn’t look friendly to me, so the idea is to use “normal” language, such as python. I found several projects which try to join AHK and Python, but it looks like all of them are forgotten.

So, we use “a universal” way of calling a program from AHK and getting results from it:
SendInput {Ctrl down}c{Ctrl up}
RunWait %ComSpec% /c ""python" "converter.py" "urldec" "%Clipboard%" > "%A_Temp%\tmp1.txt"",,HIDE
FileRead result, %A_Temp%\tmp1.txt
sleep, 100
Clipboard := result
SendInput {Ctrl down}v{Ctrl up}
Yep, it looks awful: We run new cmd (not just python) to be able to hide the “black window”, we get selected text using clipboard and get results from a file(1). However, it works pretty well and fast. So we select and copy text, press ALT+F10 and the script base64-decodes the text and replaces the selected one.

But if you set a lot of global-hotkeys, it could be hard to remember them and to use fast. So we can create a menu with internal hotkeys. As our selection may contain special symbols or to be multiline, it’s better to pass it using an additional file. Also, we can put all similar things into one function.
SendInput {Ctrl down}c{Ctrl up}
;sleep, 200 ; it added some stability for one of my laptops
FileAppend, %Clipboard%, %A_Temp%\tmp_in.txt
RunWait %ComSpec% /c ""python" "C:\path_to_script\kostyli.py" "%command%" ",,HIDE
FileRead, Clipboard, %A_Temp%\tmp_out.txt
;sleep, 100 ; it added some stability for one of my laptops
SendInput {Ctrl down}v{Ctrl up}
FileDelete, %A_Temp%\tmp_in.txt
FileDelete, %A_Temp%\tmp_out.txt

Menu, EncoderMenu, Add, &Base64 Encode, B64EncHandler
Menu, EncoderMenu, Add, B&ase64 Decode, B64DecHandler
Menu, EncoderMenu, Add, &URL Encode, UrlEncHandler
Menu, EncoderMenu, Add, U&rl Decode, UrlDecHandler


#c::Menu, EncoderMenu, Show
Here we define a menu and set various handlers for it. The approach is the same: select text, press `Win+C` and press a button of appropriate encoder/decoder (marked by &).

web pentest

Some tips

  • Be careful with global hotkeys (which you set not only for one/group application), because you can “override” some useful hotkeys of app.
  • Hotstrings don’t work so well in smart text-editors (like Sublime or VS Code), because AHK just send keys instead of you, so autocompletion and similar features of a text editor come into play.
  • Be careful when you use SendInput if you have several keyboard layouts in OS.
  • AHK is quite a reliable tool, but sometimes it doesn’t work so fast and it’s hard to debug. So, keep things simple.
  • You can set a hotkey to reload the script which is very useful during development (!^+R::Reload).
  • AHK allows you to find the elements of a window and makes actions with them (click, input text). So you can set hotkeys even if an application doesn’t have them. Java Swing application is not supported by default, but by using Java Access Bridge and this library (https://github.com/Elgin1/Java-Access-Bridge-for-AHK) we can archive it. 


In the beginning of the article I wrote about “hacky-way”… ok. AHK is a totally hacky solution, but it works!

What about other similar tools? Similar tools of course exist and exist in other OS. They have some additional features or limits. For example, python package keyboard or pyautogui which work for Linux and Windows.

You may have a look at some final examples of AHK at my repository.

четверг, 19 июля 2018 г.

Deserialization Vulnerabilities: Attacking Deserialization in JS

(It's a repost from https://www.acunetix.com/blog/web-security-zone/deserialization-vulnerabilities-attacking-deserialization-in-js/)

At ZeroNights 2017 conference, I spoke about “Deserialization vulnerabilities in various languages”. For my presentation, I used an interesting article about two serialization packages of Node.js. I showed them as examples of vulnerable implementations of deserialization processes. In this post, I’d like to show results of my own research and a new approach of attacking deserialization in JS.

Previous research

The article mentioned above talks about two packages – node-serialize and serialize-to-js. Both of them can serialize an object in JSON format, but unlike standard functions (JSON.parse, JSON.stringify), they allow the serialization of almost any kind of object, such as Function, for example (i.e in JavaScript, a function is an object too). So, it’s a valid object:
var obj = {
    field1: "value1",
    field2: function(){
        return 1;
But if we serialize it using JSON.stringify, we have only:
{ field1: "value1" }
To implement support of all kinds of objects, node-serialize, internally uses eval.
{"anything_here":"_$$ND_FUNC$$_function (){сonsole.log(1)}"}
This is what a serialized object with a function should look like. During the deserialization process, anything after a special tag $$ND_FUNC$$ goes directly to eval function. Therefore, we can use IIFE (as mentioned in the article) or write code directly (as mentioned in the article‘s comment).

With IIFE (Immediately-Invoked Function Expression), all we need to do is add () to a function and it will be automatically invoked just after it will be defined during deserialization.
{"anything_here":"_$$ND_FUNC$$_function (){сonsole.log(1)}()"}
The next example is serialize-to-js. Although it doesn’t support function as a type, its implementation is still insecure due to the fact that it uses next construction during the deserialization process:
return (new Function('"use strict"; return ' + str))()
where str is a value under the attacker’s control.
Practically, it’s just a variation of eval. So we can achieve RCE using the following payload as seen in the following issue:
(function (){сonsole.log(1)}())

The safer way?

After my presentation at ZeroNights, I came across a package for serialization from Yahoo. It supports serialization of functions too. However, the package doesn’t include any deserialization functionality and requires you to implement it yourself. Their example uses eval directly. So I was interested to see if there were any packages supporting function serialization and did not use eval or similar functions.

Actually, there are a lot of serialization libraries (about 40 or 60). I looked through some of them and found that a safer way of deserialization is to use different constructors depending on an object type.

For example, a package returns new Function(params, body) for a function, where params and body are taken from specific JSON fields. In this case, the function is reconstructed, however an attacker cannot force its execution.

I’ve also found another vulnerable package funcster. It is vulnerable to the same attack using IIFE as previous ones, so we (as attackers) can execute our code during the deserialization process. Here is an example of a payload:
{ __js_function: 'function testa(){var pr = this.constructor.constructor("return process")(); pr.stdout.write("param-pam-pam") }()' }
The package uses another approach for serialization/deserialization. During deserialization it creates a new module with exported functions from a JSON file. Here is part of the code:
return "module.exports=(function(module,exports){return{" + entries + "};})();";
The interesting difference here is that the standard built-in objects are not accessable, because they are out of scope. It means that we can execute our code, but cannot call build-in objects’ methods. So if we use console.log() or require(something), Node returns an exception like "ReferenceError: console is not defined".

However, we can easily can get back access to everything because we still have access to the global context:
var pr = this.constructor.constructor("console.log(1111)")();
Here this.constructor.constructor gives us Function object, we set our code as a parameter there and call it using IIFE.

Step deeper with Prototype

While I was researching packages, I stumbled upon the idea to look at other approaches of attacks on deserialization, which are used in other languages. To achieve code execution we leverage functions with attacker’s controlled data which are called automatically during the deserialization process or after when an application interacts with a newly created object. Something similar to “magic methods” in other languages.

Actually, there are a lot of packages which work completely differently, still after some experiments I came to an interesting semi-universal attack. It is based on two facts.

Firstly, many packages use the next approach in the deserialization process. They create an empty object and then set its properties using square brackets notations:
where key and value are taken from JSON

Therefore we as attackers are able to control practically any property of a new object. If we look through the list of properties, our attention comes to the cool __proto__ property . The property is used to access and change a prototype of an object. This means that we can change the object’s behavior and add/change its methods.

Secondly, a call of some function leads to the invoking of the function arguments’ methods. For example, when an object is converted to a string, then methods valueOf, toString of the object are called automatically (more details here). So, console.log(obj) leads to invocation of obj.toString(). Another example, JSON.stringify(obj) internally invokes obj.toJSON().

Using both of these features, we can get remote code execution in process of interaction between an application (node.js) and an object.

I’ve found a nice example – package Cryo, which supports both function serialization and square bracket notation for object reconstruction, but which isn’t vulnerable to IIFE, because it properly manages object (without using eval&co).

Here a code for serialization and deserialization of an object:
var Cryo = require('cryo');
var obj = {
     testFunc : function() {return 1111;}

var frozen = Cryo.stringify(obj);

var hydrated = Cryo.parse(frozen);
Serialized JSON looks like that. Pretty tangled:
{"root":"_CRYO_REF_1","references":[{"contents":{},"value":"_CRYO_FUNCTION_function () {return 1111;}"},{"contents":{"testFunc":"_CRYO_REF_0"},"value":"_CRYO_OBJECT_"}]}
For our attack we can create a serialized JSON object with a custom __proto__. We can create our object with our own methods for the object’s prototype, but as a small trick, we can set an incorrect name for __proto__ (because we don’t want to rewrite a prototype of the object in our application) and serialize it.
var obj = {
    __proto: {
        toString: function() {console.log("defconrussia"); return 1111;},
        valueOf: function() {console.log("defconrussia"); return 2222;}
So we get serialized object and rename from __proto to __proto__ in it:
{"root":"CRYO_REF_3","references":[{"contents":{},"value":"_CRYO_FUNCTION_function () {console.log(\"defconrussia\"); return 1111;}"},{"contents":{},"value":"_CRYO_FUNCTION_function () {return 2222;}"},{"contents":{"toString":"_CRYO_REF_0","valueOf":"_CRYO_REF_1"},"value":"_CRYO_OBJECT"},{"contents":{"proto":"CRYO_REF_2"},"value":"_CRYO_OBJECT"}]}
When we send that JSON payload to an application, the package Cryo deserializes the payload in an object, but also changes the object’s prototype to our value. Therefore, if the application interacts with the object somehow, converts it to a sting, for example, then the prototype’s method will be called and our code will be executed. So, it’s RCE.

I tried to find packages with similar issues, but most of them didn’t support serialization of function. I didn’t find any other way to reconstruct functions in __proto__. Nevertheless, as many packages use square bracket notation, we can rewrite __proto__ for them too and spoil prototypes of newly created objects. What happens when an application calls any prototype method of such objects? It may crash due to an unhandled TypeError exception.

In addition, I should mention that the whole idea potentially works for deserialization from any format (not only JSON). Once both features are in place, a package is potentially vulnerable. Another thing is that JSON.parse is not “vulnerable” to __proto__ rewriting.

function stringify == eval

While Googling, I came across another approach of serializing objects with fuctions. The idea is to first stringify functions, then to JSON.stringify the whole object. “Deserialization” consists of the same steps in reverse order. Examples of such function-stringifiers are packages cardigan, nor-function and so on. All(?) of them are insecure (due to eval & co) and allow code execution using IIFE during unstringifying.


For pentesters: Look closely at square bracket notation and access to __proto__. It has good potential in some cases.

For developers: I’m writing here that some packages are vulnerable, but your application is only vulnerable when a user’s input comes to the vulnerable function. Some packages are created in such an “insecure” way ion purpose and will not be fixed. So don’t panic, and just check if you depend on a non-standard serialization package and how you handle user’s input in it.

I shared information about both vulnerabilities with their maintainers using HackerOne’s program. A warning message has been added to `funcster` package’s README. We were not able to reach cryo’s developers.

PS: Thanks @lirantal from HackerOne for his cooperation on the above mentioned vulnerabilities.

пятница, 12 января 2018 г.

Java Deserialization: Misusing OJDBC for SSRF

This year ZeroNights has got a new zone - Web Village. It was a special "track" for people who were interested in web security. The basic idea of the Web Village is to tell people about typical vulnerabilities and attack techniques. I made a speech about basics of deserialization vulns in various languages. I wanted to show common patterns which make serialization libs potentially vulnerable. There is that presentation.

In the presentation I showed an example of a new Java gadget in order to prove that it's stupid to "fix" gadgets or "blacklist" them instead of protecting/changing deserialization lib. Here I’d like to show some details of the example.

The gadget is a class in a library which is used to connect a Java application to a RDBMS Oracle - ojdbc. Actually, this exact class (OraclePooledConnection) is responsible for establishing a connection.
The example is very simple, because the class has a readObject method which goal is to reestablish connection to a database during a deserialization process.
In the bottom of the post you can read the code, but it's not necessary, because we are going to use it in the same way as it's supposed to be used.

As we control a field (connection_url) with a string where a java application tries to connect during deserialization process, it means that we have a SSRF vulnerability here.
At first glance, it looks pretty useless, because the Oracle's protocol is binary. But I played with Oracle DB some years ago and know that the client (and TNS protocol) is very flexible.
The "URL" consists of several fields:


I think almost all of them are self-describing.
An important feature for us is that the "service name" field can contain a very long value and almost any ASCII symbols. So, potentially we can interact with text-based services. Yes, there will be binary garbage before the service name and after, but many servers don't care much about such things ("errors friendly").

So step-by-step, we create a serialized object with a specific payload as service name, send it to an application. The application runs readObject of "OraclePooledConnection" class and it forces the application to connect to wherever we want and to send our payload.

So, my point is pretty clear, the class doesn't really have any vulns, but we still can misuse its features for our attacks.

PS: The same "SSRF-attack" you can perform if you have access to Oracle DB with privs that allow you to create DB links.

P.P.S: Potentially, the attack can be improved somehow... As we control the "url" for connection, may be we can steal NetNTLM credentials (because oracle auth supports it) or perform TNS Poisoning attack?

 Code of readObject method of OraclePooledConnection class