Tag Archives: powershell empire

Adventures in Malware-Free Hacking, Part V

Adventures in Malware-Free Hacking, Part V

In this series of post, we’ve been exploring attack techniques that involve minimal efforts on the part of hackers. With the lazy code-free approach I introduced last time, it’s even possible to slip in a teeny payload into a DDE field within Microsoft Word. And by opening the document attached to a phish mail, the unwary user lets the attacker gain a foothold on her laptop. To bring the story up to date, Microsoft ultimately closed the door on DDE attacks with a security patch late last year.

The patch adds a registry entry that disables DDE functionality within Word by default. If you still absolutely need this capability, you’re free to update the setting to bring the old DDE capabilities back to the way it was.

However, the original patch only covered Microsoft Word. Are there DDE capabilities in other Microsoft Office products than can be exploited in code-free style?

Yes, indeed. You can also find them in Excel.

Night of the Living DDE

Before you start shouting into your browser, I’m aware that I left you on the edge of your seat in the previous post describing COM scriptlets. I’ll get to them further below.

Let’s continue with the evil side of DDE, the Excel version.

Just as with Word, Excel’s somewhat hidden DDE capabilities allow you to execute a bit of shell code without breaking a sweat. As a long-suffering Word user, I was familiar with fields and knew a little about DDE functions.

In Excel, I was a little surprised to learn I can execute a command shell from within a cell, as demonstrated in the following:

Did you know you can do this? I didn’t.

This ability to run a Windows shell comes to us courtesy of DDE. (And yes there are other apps to which you can connect using Excel’s embedded DDE features.)

Are you thinking what I’m thinking?

Have the cmd shell in the cell launch a PowerShell session that then downloads and executes a remote string — the trick we’ve been using all along. Like I did below:

You can insert a little PowerScript to download and execute remote code within Excel. Stealthy! 

You would, of course, need to explicitly enter the cell to execute this Excel formula.

So how could a hacker force this DDE command to be executed?

When the worksheet is opened, and if not otherwise configured, Excel will try to refresh these DDE links. There have long been options — buried in Trust Center — to either disable or prompt on updating links to external data sources or other workbooks.

Even without the recent patches, you can disable automatic updates of data connections or DDE links. 

Microsoft initially advised companies last year to disable automatic updates to prevent this DDE-based hack from being so easily pulled off in Excel.

These were mitigations, of course, but Microsoft was reluctant to go the same route as they did for Word, which was to provide a registry entry that would disable DDE all together.

But in January, they bit the bullet and provided patches for Excel 2007, 2010, and 2013 that also turn off DDE by default. This article (h/t Computerworld) nicely covers the details of the patch.

Let’s Go to the Event Logs

In short, Microsoft has cut the power on DDE for MS Word and Excel — if you’ve incorporated their patches —  finally deciding that DDE is more like a bug than, clearing throat, a feature.

If you’ve not, for whatever reason, included these patches in your environment, then you can still reduce the risk of a DDE-based attack by disabling automatic updates or enabling the options that prompt users to refresh links when the document or spreadsheets are opened.

And now an important question: if you’re a victim of this style of attack, would the PowerShell sessions launched by, either fields in Word or a shell command in the Excel cell, show up in the log?

Q:Are PowerShell sessions launched through DDE logged? A:Yes.

In my obfuscation series, I discussed how PowerShell logging has been greatly improved in recent versions of Windows. So I took a peek at the log (above), and can confirm that even when you’re launching PowerShell sessions directly from a cell function —rather than as a macro — Windows will log the event.

I’m not saying it would be easy for IT security to connect all the dots between the PowerShell session, an Excel document, and a phish mail and decide that this is indeed the beginning of the attack. I’ll discuss the consequences of malware-free hacking techniques in my final post in this never-ending series.

Enter the COM Scriptlet

In the previous post, I took on the subject of COM scriptlets. On their own, they are, I suppose, a neat feature that allows you to pass around code, say, JScript, as just another COM object.

But then hackers discovered scriptlets, and at a minimum, it allows them to keep a very low profile on a victim’s computer — “living off the land”.  This Derbycon video demos a few resident Windows tools that take remote scriptlets as arguments — regsrv32, rundll32 — and let hackers essentially conduct their attack malware-free. As I showed last time, you can easily launch PowerShell commands using a JScript-based scriptlet.

As it turns out, a very smart security researcher discovered a way to run a COM scriptlet within an Excel document. He found that something called Package is inserted into an Excel cell formula when you try to link to a document or graphic. And Package will accept a remote scriptlet (below).

Yikes, another stealthy code-free technique to launch a shell using COM scriptlets.

After doing low-level code inspection, the researcher learned that this is actually a bug in the Package software. It wasn’t meant to instantiate a COM scriptlet, just file objects.

I’m not sure whether there’s a patch for this yet. In my own exploration in a virtual Amazon WorkSpaces desktop with Office 2010, I was able to reproduce his results. When I tried again the other day, I had no success.

As we finish up this series, I hope I left you with the feeling that there’s a lot of uncertainty in what hackers can do in your environment. Even if you accept all the recent Microsoft Office patches, they still have relatively low-effort techniques, through the VBA macros I initially presented, to embed a malware payload into Word or Excel.

And if you’ve not done your patch homework, you’ve made it even easier for them to gain a foothold with code-free hacking and then perform stealthy post-exploitation.

I’ll talk about what this all means for mounting a reasonable security defense in — I promise — my final post in this saga.

Continue reading the next post in "Malware-Free Hacking"

Adventures in Malware-Free Hacking, Part IV

Adventures in Malware-Free Hacking, Part IV

For this next post, I was all ready to dive into a more complicated malware-free attack scenario involving multiple stages and persistence. Then I came across an incredibly simple code-free attack — no Word or Excel macro required! — that far more effectively proves the underlying premise in this series: it ain’t that hard to get past the perimeter.

The first attack I’ll describe is based on a Microsoft Word vulnerability involving the archaic Dynamic Data Exchange (DDE) protocol. It was only very recently patched. The second one leverages a more general vulnerability with Microsoft COM and its object passing capabilities.

Back to the DDE Future

Does anyone remember DDE? Probably not. It was an early inter-process communication protocol that allowed apps and devices to pass data.

I’m a little familiar with it because I used to review and test telecom gear – well, someone had to do it. At the time, DDE let caller ids pass to CRM apps that would ultimately pop-up a customer contact record for a call center agents. Yeah, you had to connect an RS-232 cable between the phone and the computer. Those were the days!

As it turns out, at this late date, Microsoft Word still supports DDE.

What makes this attack effectively code-free is that you can access the DDE protocol directly from Windows field codes. (Hat tip to SensePost for researching and writing about it.)

Field codes are another ancient MS Word feature that lets you add dynamic text and a bit of programming into a document The most obvious example of this is the  page numbers, which can be inserted into a footer using this field code {PAGE \*MERGEFORMAT}. It allows page numbers to be magically generated.

Pro tip: you can access field codes from the text section of the Word ribbon.

I remember first discovering this Word feature as a young lad and being amazed.

Until the patch disabled it, Word supported a DDE field option. The idea was that DDE would let Word communicate with an app and then embed the output in the document. This was an early version of an idea –communicating with external apps — that was later taken over by COM, which will get to below.

Anyway, hackers realized that the DDE app can be, wait for it, a vanilla command shell! The command shell, of course, launches PowerShell and from there hackers can do just about anything.

In the screenshot below, you can see how I used the stealthy technique introduced a few posts back: the teeny PowerShell script in the DDE field downloads more PowerShell, which then starts the second phase of the attack.

Thank you Windows for warning us that an embedded DDEAUTO field sneakily launches a shell.

The preferred method is to use a variant, the DDEAUTO field, which automatically launches the script when the Word document is opened.

Let’s step back.

As a beginning hacker, you can send a scary phish mail, pretending to be from the IRS, and embed a DDEAUTO field with a teeny first-stage PS script. You don’t have to do any real coding with the MS macro library, as I did in the last post.

The CEO opens the Word doc, the embedded script is activated, and the hacker is effectively inside the laptop. In my case, the remote PS script pops up a message, but it could just as easily have launched a PS Empire client that would grant shell access.

And before you can say Macedonia, the hackers are the wealthiest teenagers in their village.

A shell was launched without any real coding. Even a Macedonian child could do this!

It’s so easy!

DDE and Fields

After some prodding, Microsoft disabled DDE in Word, but at first they said that the feature was just being misused. Their reluctance is somewhat understandable.

From what I can see (based on a sample of one data security company) field updating on opening a document is enabled and Word macros are disabled (with notification) by IT groups. By the way, you can find the relevant configuration settings in the Options section of Word.

However, even when field updating is enabled, Microsoft Word additionally prompts the user when a field is accessing remote data, as is the case with DDE (see above). Microsoft does indeed warn you.

But as we know from Dr. Zinaida Benenson, users will click away and ultimately activate the field update.

This is a roundabout way of thanking Microsoft for disabling the dangerous DDE feature.

How difficult is it to find an unpatched Windows environment?

For my own testing, I used AWS Workspaces to access a virtual desktop. And it was pretty easy to obtain an unpatched VM with MS Office that let me insert a DDEAUTO field.

No doubt there are, cough, more than a few corporate sites that still haven’t added the security patch.

The Mystery of Objects

Even if you have added their patch, there are other security holes in MS Office that let hackers accomplish something very similar to what we did with Word. In this next scenario, we’ll learn how to leverage Excel as the phish bait in a code-free attack.

To first understand this next scenario, let’s step a back a little to consider Microsoft Component Object Model or COM.

COM has been around since the 1990s and is described as a “language neutral, object-oriented component model” based on remote procedure calls. Read this StackOverflow post for basic COM definitions and terminology.

Generally, you can think of a COM app as Excel or Word or some other running binary executable.

As with all things more Microsoft, it’s more complicated than that.  It turns out that a COM app can alsobe a script—JScript or VBScript. Technically, it’s called a scriptlet. You may have seen the .sct extension for a Windows file, which is the official suffix for scriptlets. These scriptlets are essentially scripting code encased in XML (below).

<?XML version="1.0"?>

<scriptlet>
<registration
description="test"
progid="test"
version="1.00"
classid="{BBBB4444-0000-0000-0000-0000FAADACDC}"
remotable="true">
</registration>
<script language="JScript">
<![CDATA[

var r = new ActiveXObject("WScript.Shell").Run("cmd /k powershell -c Write-Host You have been scripted!");

]]>
</script>
</scriptlet>

Hacker and pen testers discovered that there are Windows utilities and apps that accept COM objects and, by extension, these user-crafted COM scriptlets.

Let’s call it a day!

Your homework is to watch this Derbycon video from 2016, which explains how hackers and pen testers have taken advantage of scriptlets. And also read this post on scriptlets and something called monikers.

To get ahead of the story, I can pass a scriptlet to a Windows utility, written in VBS, known as pubprn, which is buried in C:\Windows\system32\Printing_Admin_Scripts. By the way, there are other Windows utilities that take objects as parameters; we’ll just look at this particular one first.

It’s only natural that you can launch a shell from a printing script. Go Microsoft!

For my own testing I crafted a simple remote scriptlet that launches a shell and prints a “boo” message. Effectively, pubprn instantiates the scriptlet object thereby allowing the VBScript code to launch a shell.

This technique provides obvious advantages to hackers who want to “live off the land” and lurk in your system undetected

In the next post, I’ll explain how COM scriptlets can be exploited by hackers within an Excel spreadsheet.

 

 

 

Continue reading the next post in "Malware-Free Hacking"

Adventures in Malware-Free Hacking, Part II

Adventures in Malware-Free Hacking, Part II

I’m a fan of the Hybrid Analysis site. It’s kind of a malware zoo where you can safely observe dangerous specimens captured in the wild without getting mauled. The HA team runs the malware in safe sandboxes and records systems calls, file created, and internet traffic, displaying the results for each malware sample. So you don’t have to necessarily spend time puzzling over or even, gulp, running the heavily obfuscated code to understand the hackers’ intentions.

The HA samples I focused on use either encasing JavaScript or Visual Basic for Applications (VBA) scripts, which are the “macros” embedded in Word or Excel documents attached to phish mails. These scripts then launch a Powershell session on the victim’s computer. The hackers usually send to the PowerShell a Base64-encoded stream. It’s all very sneaky and meant to make it difficult for monitoring software to find obvious keywords to trigger on.

Mercifully, the HA teams decodes Base64 and displays the plain text. In effect, you don’t really need to focus on how these scripts work because you’ll see the command line of the spawned processes in HA’s “Process launched” section. The screenshots below illustrate this:

Hybrid Analysis captures the Base64-encoded commands sent to a PowerShell process …

… and then decodes it for you. #amazing

In the last post, I created my own mildly obfuscated JavaScript container to launch a PowerShell session.

Then my script, like a lot of PowerShell-based malware, downloads a second PowerShell script from a remote web site. To do this safely, my dudware downloads a harmless 1-line of PS to print out a message.

This being the IOS blog we never, ever do anything nice and easy. Let’s take my scenario a step further.

PowerShell Empire and Reverse Shells

One of the goals of this exercise is to show how (relatively) easy it is for a hacker to get around legacy perimeter defenses and scanning software. If a non-programming security blogger such as myself can cook up potent fully undetected or FUD malware in a couple of afternoons (with help from lots of espressos), imagine what a smart Macedonian teenager can do!

And if you’re an IT security person who needs to convince a stubborn manager – I know they don’t exist, but let’s say you have one – that the company needs to boost its secondary defenses, my malware-free attack example might do the trick.

I’m not suggesting you actually phish management, though you could. If you take this route and use my scripts, the message that prints on their laptops would count as a cybersecurity “Boo!”.  It may be effective in your case.

But if your manager then challenges you by saying, “so what”, you can then follow up with what I’m about to show you.

Hackers want to gain direct access to the victim’s laptop or server. We’ve already reviewed how Remote Access Trojans (RATs) can be used to sneakily send and download files, issue commands, and hunt for valuable content.

However, you don’t have to go that far. It’s very easy to gain shell access, which for certain situations might be all a hacker requires – to get in and get out with a few sensitive files from the CEO’s laptop.

Remember the amazing PowerShell Empire post-exploitation environment that I wrote about?

It’s a, cough, pen testing tool, that among its many features lets you easily create a PowerShell-based reverse shell. You can more learn more about this on the PSE site.

Let’s take a quick walk through. I set up my malware testing environment within my AWS infrastructure so I can work safely. And you can do the same to show management a PoC (and not get fired for running grey area hacking software on the premises.)

If you bring up the main console of PowerShell Empire, you’ll see this:

First, you configure a listener on your hacking computer. Enter the commander “listener”, and follow up with “set Host” and the IP address of your system — that’s the “phone home” address for the reverse shell. Then launch the listener process with an “execute” command (below). The listener forms one end of your shell connection.

For the other, you’ll need to generate agent-side code, by entering the “launcher” command (below). This generates code for a PowerShell agent — note that it’s Base64-encoded — and will form the second stage of the payload. In other words, my JavaScript encasing code from last time will now pull down the PowerShell launcher agent, instead of the harmless code to output “Evil Malware”, and  connect to the remote agent in reverse-shell fashion.

Reverse-shell magic. This encoded PowerShell command will connect back to theremote listener and set up a shell.

To run this experiment, I played the part of an innocent victim and clicked on Evil.doc, which is  the JavaScript I set up last time. Remember? The PowerShell was configured to not pop-up a window, so the victim won’t notice anything unusual is going on. However, if you look at the Windows Task Manager, you’ll see the background PowerShell process, which may not trigger alarms ’cause it’s just PowerShell, right?

Now when you click on Evil.doc, a hidden background process will connect to the PowerShell Empire agent.

Putting on my hacker-pentester hat, I returned to my PowerShell Empire console, and now see the message that my agent is active.

I then issued an interact command to pop up a shell in PSE. And I’m in! In short: I hacked into the Taco server that I set-up once upon a time.

What I just described is not a lot of work. If you’re doing this for kicks during a long lunch hour or two to improve your infosec knowledge, it’s a great way to see how hackers get around border security defenses and stealthily lurk in your system.

And IT managers who believe that they’ve built breach-proof defense may, fingers crossed, find this enlightening – if you can convince them to sit down long enough.

Let’s Go Live

As I’ve been suggesting, real-world malware-free hacking is just variation on what I just presented. To get a little bit of a preview of the next post, I searched for Hybrid Analysis specimen that works in a similar fashion to my made-up sample. I didn’t have to search very long – there’s lots of this attack technique on their site

The malware I eventually found in Hybrid Analysis is a VBA script that was embedded in a Word doc. So instead of faking the doc extension, which I did for my JavaScript example, this malware-free malware is really, truly, a Microsoft document.

If you’re playing along at home, I picked this sample, called rfq.doc.

I quickly learned you often can’t directly pull out the actual evil VBA scripts. The hackers compressed or hid them, and they won’t show up in Word’s built-in macro tools.

You’ll need a special tool to extract it. Fortunately, I stumbled upon Frank Boldewin’s OfficeMalScanner. Danke, Frank.

Using this tool, I pulled out the heavily obfuscated VBA code. It looks a little bit like this:

Obfuscation done by pros. I’m impressed!

Attackers are really good at obfuscation, and my efforts in creating Evil.doc was clearly the work of a rank amateur.

Anyway, next time we’ll get out our Word VBA debuggers, delve into this code a little bit, and compare our analysis to what HA came up with it.

Continue reading the next post in "Malware-Free Hacking"

Adventures in Malware-Free Hacking, Part I

Adventures in Malware-Free Hacking, Part I

When I first started looking into the topic of hackers living off the land by using available tools and software on the victim’s computer, little did I suspect that it would become a major attack trend. It’s now the subject of scary tech headlines, and security pros are saying it’s on the rise. It seems like a good time for a multi-part IOS blog series on this subject.

Known also as file-less or zero-footprint attacks, malware-free hacking typically uses PowerShell on Windows systems to stealthily run commands to search and exfiltrate valuable content. To IT security team monitoring for hacker activities, file-less attack are very difficult to spot, often evading virus scanners and other signature-based detection systems.

In short, legacy defense can’t really deal with this style of attack. Of course there is, ahem, security software that will spot the malware activity on file systems.

Anyway, I’ve written about  some of these ideas before in my PowerShell obfuscation series, but more from a theoretical view. Then I discovered the Hybrid Analysis site, where you can find uploaded samples of malware captured in the wild.

Wild PowerShell

I thought it would be a great place to look for some file-less malware specimens. I wasn’t disappointed. By the way, if you want to go on your own malware hunting expedition, you’ll have to be vetted by the Hybrid Analysis folks so they know you’re doing white hat work. As a blogger who writes about security, I passed with flying colors. I’m sure you will too.

Besides having samples, they also provide great insights into what the malware is doing. Hybrid Analysis runs the submitted malware in their own sandbox, and monitors for system calls, processes launched, and Internet activity, as well as pulling out suspicious text strings.

For binaries and other executables in particular, where you can’t even look at the actual high-level code, this container technique allows HA to decide whether the malware is evil or merely suspicious based on its run-time activity. And then they’ll rate the sample.

For the malware-free PowerShell and other scripting samples (Visual Basic, JavaScript, etc.) I was looking for, I could see the actual code. For example, I came across this PowerShell creature:

You too can run base64 encoded PowerShell to evade detection. Note the use of the Noninteractive parameter in this live sample from Hybrid Analysis.

If you’ve read my obfuscation posts, you’ll know that the -e parameter indicates that what follows is base64 encoded. By the way Hybrid Analysis helpfully provides the decoded PowerShell as well. If you want to try decoding base64 PS on your own, you can run this command to do the work: $DecodedText = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($EncodedText))

Getting in Deeper

I decoded the script using this technique, and you can see the resulting plaintext PowerShell malware below.

Note the time sensitivity of this PS malware, and the use of cookies to pass back more information. I modified this real-world sample in my own testing.

I was feeling a little nervous handling this live malware on my own laptop. Attention Varonis IT Security: please note that I worked with an on-line PowerShell console and also my own separate AWS environment. Got that, IT?

Anyway, we’ve seen this particular attack style before —  in the PS obfuscation series — wherein the base64 encoded PS is itself pulling more of the malware from another site, creating a .Net Framework WebClient object to do the heavy lifting.

Why this approach?

For security software that’s scanning the Windows event log, the base64 encoding prevents text-based pattern matching from doing some easy detection – matching on say the string “WebClient”. And since the real evil part of the malware is then downloaded and injected into the PS app itself, this approach completely evades detection. Or so I thought.

It turns out with more advanced Windows PowerShell logging enabled – see my post — you can effectively see the downloaded string in the event log. I commend Microsoft (as did others!) for this added level of logging.

However, hackers then responded by base64 encoding the downloaded PowerShell from the remote site, so it would then show up in the Windows event log like the encoded sample above. Makes sense, right?

Adding More Scripting Sauce

The real-world samples in Hybrid Analysis then take this idea a step further. Hackers cleverly hide this PowerShell attack in Microsoft Office macros written in Visual Basic and in other scripts. The idea is that the victim receives a phish mail from say, FedEx, with a Word doc described as an invoice. She then clicks on the doc that then launches a macro that then eventually launches the actual PowerShell.

Often times, the Visual Basic script itself is obfuscated so that it evades virus and malware scanners.

Yes, it’s complicated and evil. And I’m only doing a very shallow dive.

In the spirit of the above, I decided as a training exercise to encase the above PowerShell within some obfuscated JavaScript. You can see the results of my hacking handiwork:

Obfuscated JavaScript hiding the encoded PowerShell. Real hackers, of course, do this better than me.

There is one technique I borrowed from “in the wild” samples: the use of  Wscript.Shell to launch the actual encoded PowerShell. It’s the way you get out of the script environment to interact with the rest of the system.

By the way, JavaScript is on its own a vehicle for delivering malware. Many Windows environment have by default the Windows Script Host, which will directly run JS.  In this scenario, the encasing JS malware is attached as a file with a .doc.js suffix.  Windows will only show the first suffix, so it will appear to the victim as a Word doc.  The JS icon is rendered as a scroll-like graphic. Not surprisingly, people will click on this attachment thinking it’s a document.

Don’t click on that JS icon that resembles a scroll! It will download evil malware. You’ve been warned.

For my own encasing JavaScript malware, I modified the PowerShell sample above to download a script from a web site I control. The remote PS script merely prints out “Evil Malware”.

Not very evil.

Of course, real hackers are interested in gaining access to a laptop or server, say, through a shell..

In the next post, I’ll show how to do this by using PowerShell Empire, which I wrote about once upon a time.

We probably dove a little too deep for an introductory post, so I’ll let you catch your breath and cover some of this again next time. And then we can start grokking real-world malware-free attacks with the preliminaries out of the way.

 

Continue reading the next post in "Malware-Free Hacking"

Disabling PowerShell and Other Malware Nuisances, Part I

Disabling PowerShell and Other Malware Nuisances, Part I

This article is part of the series "Disabling PowerShell and Other Malware Nuisances". Check out the rest:

Back in more innocent times, circa 2015, we began to hear about hackers going malware-free and “living off the land.” They used whatever garden-variety IT tools were lying around on the target site. It’s the ideal way to do post-exploitation without tripping any alarms.

This approach has taken off and gone mainstream, primarily because of off-the-shelf post-exploitation environments like PowerShell Empire.

I’ve already written about how PowerShell, when supplemented with PowerView, becomes a potent purveyor of information for hackers. (In fact, all this PowerShell pen-testing wisdom is available in an incredible ebook that you should read as soon as possible.)

Any tool can be used for good or bad, so I’m not implying PowerShell was put on this earth to make the life of hackers easier.

But just as you wouldn’t leave a 28” heavy-duty cable cutter next to a padlock, you probably don’t want to allow, or at least make it much more difficult for, hackers get their hands on PowerShell.

This brings up a large topic in the cybersecurity world: restricting application access, which is known more commonly as whitelisting or blacklisting. The overall idea is for the operating system to strictly control what apps can be launched by users.

For example, as a member of homo blogus, I generally need some basic tools and apps (along with a warm place to sleep at night), and can live without PowerShell, netcat, psexec, and some other cross-over IT tools I’ve discussed in previous posts. The same applies to most employees in an organization, and so a smart IT person should be able come up with a list of apps that are safe to use.

In the Windows world, you can enforce rules on application execution using Software Restriction Policies and more recently AppLocker.

However, before we get into these more advanced ideas, let’s try two really simple solutions and then see what’s wrong with them.

ACLs and Other Simplicities

We often think of Windows ACLs as being used to control access to readable content. But they can also be applied to executables — that is, .exe, .vbs, .ps1, and the rest.

I went back into Amazon Web Services where the Windows domain for the mythical and now legendary Acme company resides and then did some ACL restriction work.

The PowerShell .exe, as any sys admin can tell you, lives in C:\Windows\System32\WindowsPowerShell\v1.0. I navigated to the folder, clicked on properties, and effectively limited execution of PowerShell to a few essential groups: Domain Admins and Acme-SnowFlakes, which is the group of Acme employee power users.

I logged backed into the server as Bob, my go to Acme employee, and tried to bring up PowerShell. You see the results below.

In practice, you could probably come up with a script — why not use PowerShell? — to automate this ACL setting for all the laptops and servers in a small- to mid-size site.

It’s not a bad solution.

If you don’t like the idea of setting ACLs in executable files, PowerShell offers its own execution restriction controls. As a user with admin privileges, you can use, what else but a PowerShell cmdlet called Set-ExecutionPolicy.

It’s not nearly as blunt a force as the ACLs, but you can restrict PowerShell to work only in interactive mode –  with the Restricted parameter — so that it won’t execute scripts that contain the hackers’ malware. PowerShell would still be available in a limited way, but it wouldn’t be capable of running the scripts containing hacker PS malware.

However, this would PowerShell scripts from being run by your IT staff.  To allow IT-approved scripts, but disable evil hacker scripts, you use the RemoteSigned parameter in Set-ExecutionPolicy. Now PowerShell will only launch signed scripts. The IT staff, of course, would need to create their own scripts and sign them using an approved credential.

I won’t go into the details how to do this, mostly because it’s so easy to get around these controls. Someone even has a listicle blog post in which 15 PowerShell  security workarounds are described.

The easiest one is using the Bypass parameter in PowerShell itself. Duh! (below).

Seems like a security hole, no?

So PowerShell has some basic security flaws. It’s somewhat understandable since it is, after all, just a shell program.

But even the ACL restriction approach has a fundamental problem.

If hackers loosen up the “live off the land” philosophy, they can simply download — say, using a remote access trojan (RAT) — their own copy of PowerShell .exe. And then run it directly, avoiding the permission restrictions with the resident PowerShell.

Software Restriction Policies

These basic security holes (and many others) are always an issue with a consumer-grade operating systems. This has led OS researchers to come up with secure secure operating systems that have direct power to control what can be run.

In the Windows world, these powers are known as Software Restriction Policies (SRP) — for a good overview, see this — that are managed through the Group Policy Editor.

With SRP you can control which apps can be run, based on file extension, path names, and whether the app has been digitally signed.

The most effective, though most painful approach, is to disallow everything and then add back application that you really, really need. This is known as whitelisting.

We’ll go into more details in the next post.

Anyway, you’ll need to launch the policy editor, gpedit, and navigate to Local Computer Policy>Windows Settings>Security Settings>Software Restriction Polices>Security Levels. If you click on “Disallowed”, you can then make this the default security policy — to not run any executables!

The whitelist: disallow as default, and then add app policies in “Additional Rules”.

This is more like a scorched earth policy. In practice, you’ll need to enter “Additional Rules” to add back the approved apps (with their path names). If you leave out PowerShell, then you’ve effectively disabled this tool on the site.

Unfortunately, you can’t fine-tune the SRP rules based on AD groups or users. Drat!

And that we’ll bring us to Microsoft’s latest and greatest security enforcer, known as AppLocker, which does provide some nuance to application access. We’ll take that up next time as well.

Continue reading the next post in "Disabling PowerShell and Other Malware Nuisances"

Pen Testing Active Directory Environments, Part IV: Graph Fun

Pen Testing Active Directory Environments, Part IV: Graph Fun

If we haven’t already learned from playing six degrees of Kevin Bacon, then certainly Facebook and Linkedin have taught us we’re all connected. Many of the same ideas of connectedness also play out in Active Directory environments. In this post, we’ll start out where we left off last time in thinking about the big picture of Active Directory users and groups.

Or more accurately pondering the big graph of Active Directory. And the game we’re playing is closer to four degrees of Ted, your overworked IT admin or other privileged user.

Graphically Speaking

Why do we need to think about graphs in AD environments?

These structures form naturally from AD group membership. At the Acme company, I already set up groups for Acme-Clevels, Acme-VIPs and Acme-Serfs. These AD groups can contain either users or other groups. IT often establishes AD environments with group hierarchies so they can control permissions at finer levels with each hop down the hierarchy.

Since the last post, for example, I added a group for Acme-Legal under Acme-VIPs. In Acme Legal, there are legal subgroups for Acme-Patents and Acme-Compliance. As Acme’s beloved IT admin, I can set permissions that allow only members of Acme-Patents to view and update certain directories or include all of Acme-Legal or even all of Acme-VIPs.

acme-legal

Part of the Acme AD hierarchy.

The computer science-y word for the hierarchies I’m describing is known as directed acyclic graphs or DAGs. For anyone who’s ever taken a basic CS class such as “Data Structures for Poets and Aspiring Sous Chefs”, this core graph type always comes up.

Pen testers who work in AD environment are also very fond of these graphs. They allow them to quickly hunt down users who’ll have the credentials they need. A gentle intro to the subject can be found in this Def Con presentation. I’ll add the usual qualifier: the whole area of graph theory is a rich one, and we’ll only be sipping its foamy crema in this post.

One use of these ideas is known as “derived admin”, which involves hopping around the network while gaining local admin privileges. We’ll do something a little different: finding users who have permissions to a file we’re interested but can’t access.

Practicing Law Without the Right Permissions

Let’s say I’ve landed on Acme’s Salsa server with Bob’s plain credentials — Bob is in the Acme-Serfs’ group. Bob has enough file permissions to help me move around the server, but not enough to allow access to interesting content.

I come across a tempting directory named “Top Secret”. Unfortunately, I can’t navigate into it. I now use PowerView’s Get-PathACL to get a little more insight.

pathacl

Wouldn’t you know it, but “Top Secret” gives access to those only in Acme-Legal (and Administrators). As an Acme-Serfs member, I’ve been excluded.

Here’s the problem. I’d like to discover all the users under the Acme-Legal umbrella since any user in the Acme-Legal hierarchy would give me the right privileges.

The goal is to find all those users – in graph-speak, the leaves — under Acme-Legal.  And then hope that one of these users are on the Salsa server so I can steal their credentials through pass-the-hash.

If you do this on an ad-hoc, manual basis this can get complicated very quickly for even small companies. For example, I can try running Get-NetGroupMember, write down all the groups and users that are spit out and then repeat until exhaustion sets in.

Paul Revere Rides Again

The better way to do this, of course, is to automate the task using PowerShell.

We need to build what’s known in the trade as adjacency lists — it’s a array structure for representing the DAG. For each Acme group, I can quickly access the immediate members under it.

I’m not much of a PowerShell scripter, but in an afternoon or two I was able to generated these lists using PS’s associative arrays and arraylist data types, along with using PowerView’s Get-NetGroupMember.

You can see the partial results below, with the variable $GroupAdj containing it all.

groupadj

Yeah, it’s a great homework assignment to work this out for yourself.

Do some of these ideas seem familiar in a kind of Paul Revere-metadata way?  Of course, sociologist Kieran Healy’s great Using Metadata to Find Paul Revere should come to mind! Healy’s post was a first introduction to metadata and graphs for many of us.

His problem was finding all the Tea Partiers — the original version 1.0 — that Paul Revere was connected to. By the way, his post shows you how to create what’s known by the graph-erati as the “transitive closure” for each node.  I’ll take that up next time for our Acme graph.

This time we’ll solve a far simpler puzzle: given a specific Acme user and a group, is there are connection between the two? Essentially, I want to see if there’s a path from an AD group to the user by navigating my adjacency lists.

If you’ve the taken the computer course for poets that I mentioned earlier, you know about breadth-first search (BFS) and depth-first search (DFS) algorithms. As a cool pen tester, I wrote a couple of lines of code that implements  BFS and kept in a file call depthsearch:

dfs

Classic depth-first-search in PowerShell. By the way ArrayLists are the way to implement simple queues!

Let’s say I’m watching to see who’s logging into Salsa using crackmapexec with --lusers option. I discover that someone named Cal is now on the server. He’s seems like an IT guy based on running the Get-NetUser cmdlet.

So I now run my depthsearch script with parameters Acme-Legal and cal.

depth-results

Eureka! Next I just need to dump his hash using crackmapexec and then I can pop a shell with Empire – remember from last time?

And the Lesson Is  … Role Based Access Controls

In my role as Acme admin, I created a special group known as Acme-SnowFlakes, where I put Cal the IT guy. The Acme-Snowflakes group is itself buried down in the hierarchy under the Acme-Patents group. In this make believe scenario, once upon a time we needed to give Cal access to legal folders and then we promptly forgot to remove these special Snowflakes.

As a pen tester, I can now report to management about a small hole in the Acme permission structure.

We covered a lot of ground this time, but there is an important lesson. Once the hackers get in and then leverage Active Directory metadata, they have – let’s face it – awesome power. The goal is to make it harder for them.

And one of the ways to do that is through role-based access control policies that always forces you to restrict who has access to sensitive files. An IT group that’s on its game would have been questioning why Cal had give access to the “Top Secret” directory used by the legal department.

Enough preaching!

We’ll go over some of these same ideas again next time, and then explore derivative admins, which is a variation of the concepts we’ve covered in this post.

Continue reading the next post in "Pen Testing Active Directory Environments"

Pen Testing Active Directory Environments, Part III:  Chasing Power Users

Pen Testing Active Directory Environments, Part III:  Chasing Power Users

For those joining late, I’m currently pen testing the mythical Acme company, now made famous by a previous pen testing engagement (and immortalized in this free ebook). This time around I’m using two very powerful tools, PowerView and crackmapexec, in my post-exploitation journey into Acme’s IT.

Before we get into more of the details of hunting down privileged users, I wanted to take up one point regarding Active Directory mitigations that I touched on last time.

Protecting the VIPs

As we saw, PowerView cmdlets give pen testers and hackers incredibly valuable information about the user population. It does this by pulling attributes out of Active Directory, some of which can then be used to launch a phishing-whaling attack.

So you’re wondering whether or not we can put restrictions on who gets to see the data? Or what data is made available in the first place?

Yes and yes.

For the purposes of this post, I’m proposing a quick fix. We’ll simply prevent some key AD attributes from being displayed in PowerView’s Get-NetUser cmdlet.

We really don’t want to make it easy for hackers to access phone numbers, mail addresses, and other personal information of the C-suite.

These folks may not have customer accounts and credit card numbers in their files, but they surely have access to key corporate IP – contracts, plans, pending deals, etc.

The answer can be found in the Active Directory Computer and User interface.

Our first priority should be to secure Ted Bloatly, Chief Honcho (CEO) of Acme.

If we click on his Security tab, we can view a list of broad AD attribute permissions — personal, phone and email — that we can allow or deny access to.

For Mr. Bloatly, I’ll simply deny access to his contact information (see below) for anyone in the Acme domain.

teb-attributes

I really don’t want hackers and even employees to get this kind of sensitive data.  If you want to know anything about Mr. Bloatly, you’ll have to find out the old-fashioned way, by contacting his loyal personal assistant, Smithers.

Sure we can be more granular about who gets to see this information. Clicking on “Advanced” lets you enable certain groups to view Bloatly’s contact information: for example, I could allow access for just the Acme-VIPs group, the C-levels of the company.

In any case, if we go back to the Salsa server that we landed on, and run Get-NetUser, we’ll see that his postal address and the personal info about his bowling habits no longer shows up.

ted-filtered

We’ll delve into other ways to restrict access to AD attributes later on in this series.

The Credential Hunt

Building on the scenario from last time, I’m back on Salsa with Lele’s credential. Lele, like her friend Bob, is in the Acme-Serfs group.

Let’s rerun Get-NetComputer.

enchilad-computers

You’re probably thinking, as I did when I set this up, that Enchilada is where the important people hang out. “Big Enchiladas”, right?

Let’s see if Lele’s credentials will allow me access to it. One quick way to do this is to use crackmapexec and point it at the server you’re trying to access—it will let you know whether can log in (below).

lele-enchilada

My pen testing senses are tingling. I’m denied access to Enchilada, but allowed access to Taco and Salsa.

It’s like the equivalent of a sign that says “Private Property: Keep Out!”. You know there has to be something valuable on the Enchilada server.

We’re now at the point where you have to find the users who’ll get you what you want – access to Enchilada.

Like last time, we can run Get-GroupMembers Acme-VIPs. I’ve found two power users now– Ted Bloatly and Lara Crasus. (fyi: I added VIP Lara since the previous post.)

What you can hope for is that one of these VIPs will let you log on to the Salsa machine. Then we can grab the hashes, and use them with crackmapexec to get into Enchilada.

By the way, this brings up an important point about risk assessments regarding user accounts: you have to be very careful about assigning user account access rights.

One common technique is to assign multiple accounts to the same user with each account having its own privileges. This avoids the problem of an over-privileged account logging into a less-privileged account’s machine, thereby leaving it open to credential theft and pass-the-hash.

So let’s say Acme hasn’t learned this lesson, and Ted Bloatly occasionally uses his one AD account to log into the Salsa server used by the plebians.

We can set an alarm.

Enter something like Invoke-UserHunter –GroupName Acme-VIPs on the command line, then check the output and repeat. Obviously, we can do a better job of fine-tuning and automating. I’ll leave that as a homework assignment.

Once we find an Acme-VIPs member, we dump the hash using the --lsa option for crackmapexec and the pass-the-hash using the –H option to log into the Enchilada server.

PowerShell Empire and Reverse Shells

One aspect of hopping around a domain that’s worth talking about is the topic of getting shell connections. So far I’ve been cheating a little bit in showing screen output from the actual server.

In real life, hackers and pen testers are using reverse-shells — remember those? — to see what’s going on from a remote terminal.

In my last pen testing series, getting a reverse shell from a PowerShell environment was a bit rocky. In fact, I didn’t really have a good way of doing this,

And the I discovered PowerShell Empire.

It describes itself as having the ability “to run PowerShell agents without needing powershell.exe, rapidly deployable post-exploitation modules ranging from key loggers to Mimikatz… all wrapped up in a usability-focused framework”

Amen, and it lives up to its billing. This is powerful stuff and I attained beautiful remote PowerShell access to the Acme environment.

If you want to play around with Empire for yourself, you can download it from GitHub here. With a little bit of struggle (and two aspirins later), I installed it on an Ubuntu Linux server in my AWS environment.

In terms of its remote PowerShell powers, it allows you to create a Listener, which lives at one end of the connection. And then you grab some shell code to run on the victim’s machine. Ultimately, it launches an Agent, which is what you interact with in Empire.

ubuntu-empire

launcher-acme

PowerShell Empire: multiple agents each with its own shell connection.  Shellcode runs on the target computer. Awesome power.

Effectively, we’re implementing the PowerShell version of the reverse shell that I previously accomplished with ncat.

You can have many agents running at a time and interact concurrently with each PowerShell session on the target machines.

lele-empire

PowerShell connection back to Salsa!

This is very powerful, and I’m only scratching the surface.

Let’s take a breath.

In my next post, we’ll go into more detail for this Empire-based reverse PowerShell technique, and demonstrate how you can use it to hop around the Acme domain using crackmapexec to inject the shellcode for the next hop.

Yes, we’ll get back into exploiting the information in Active Directory groups and in particular use the relationships in it to guide which users to chase down. It’s referred to as derived or derivative  admins.

I’ll leave you with this interesting observation made by (I believe) Will Graebner: pen testers think in graphs, IT people think in terms of lists.

Meditate on that thought till next time.

Continue reading the next post in "Pen Testing Active Directory Environments"