TrustedSec: Recent Episodes

None

View Details

Very often in engagements, you’ll want to list out processes running on a host. One thing that is beneficial is to know is if the processes is a 64-bit or 32-bit process. Why do you need to know the process architecture, you might ask? The reasons are many, but one common example is that you might find a process running as system that is vulnerable to an escalation attack (DLL hijack or similar technique). Then, you would need to craft your payload according to the architecture. You would think that you could use scripts and code to list out the process architecture pretty easily. At least I thought so when I started looking into this. Let’s take a quick look at a GUI example using process explorer to list out the architecture.

As you can see from the unelevated Process Explorer, you can only see the Image Type for process launched by the user. This is due to the fact that a non-elevated user cannot get details about system processes or processes launched by other users. It states on the username field amongst other processes. Process Explorer cannot show it, but the native Task Manager in Windows can. All you have to do is to add the column named Platform. Using the Task Manager however you can see that you are not allowed to see the UAC Virtualization for any other users process.

If we try to list out a process using PowerShell’s get-process, you will see this output:

(Get-Process)[10] | fl *Name : explorerId : 4364PriorityClass : NormalFileVersion : 10.0.19041.2311 (WinBuild.160101.0800)HandleCount : 2523WorkingSet : 156053504PagedMemorySize : 59518976PrivateMemorySize : 59518976VirtualMemorySize : 613797888TotalProcessorTime : 00:00:16.1875000SI : 2Handles : 2523VM : 2203932020736WS : 156053504PM : 59518976NPM : 111184Path : C:\Windows\Explorer.EXECompany : Microsoft CorporationCPU : 16.1875ProductVersion : 10.0.19041.2311Description : Windows ExplorerProduct : Microsoft® Windows® Operating System\_\_NounName : ProcessBasePriority : 8ExitCode :HasExited : FalseExitTime :Handle : 2768SafeHandle : Microsoft.Win32.SafeHandles.SafeProcessHandleMachineName : .MainWindowHandle : 131348MainWindowTitle :MainModule : System.Diagnostics.ProcessModule (Explorer.EXE)MaxWorkingSet : 1413120MinWorkingSet : 204800Modules : {System.Diagnostics.ProcessModule (Explorer.EXE), System.Diagnostics.ProcessModule (ntdll.dll), System.Diagnostics.ProcessModule (KERNEL32.DLL), System.Diagnostics.ProcessModule (KERNELBASE.dll)...}NonpagedSystemMemorySize : 111184NonpagedSystemMemorySize64 : 111184PagedMemorySize64 : 59518976PagedSystemMemorySize : 1099280PagedSystemMemorySize64 : 1099280PeakPagedMemorySize : 71675904PeakPagedMemorySize64 : 71675904PeakWorkingSet : 211505152PeakWorkingSet64 : 211505152PeakVirtualMemorySize : 820936704PeakVirtualMemorySize64 : 2204139159552PriorityBoostEnabled : TruePrivateMemorySize64 : 59518976PrivilegedProcessorTime : 00:00:09.2968750ProcessName : explorerProcessorAffinity : 1Responding : TrueSessionId : 2StartInfo : System.Diagnostics.ProcessStartInfoStartTime : 8/25/2023 4:48:07 AMSynchronizingObject :Threads : {4368, 4628, 4684, 4692...}UserProcessorTime : 00:00:06.8906250VirtualMemorySize64 : 2203932020736EnableRaisingEvents : FalseStandardInput :StandardOutput :StandardError :WorkingSet64 : 156053504Site :Container : As you can see, there’s nothing here that immediately sticks out. Namely, whether the process is a 64-bit process or not. Let’s also do the same using vbscript together with WMI to list out the processes. For this demonstration, I am going to use WMI Explorer to generate a sample vbscript code that includes all process properties. The script looks like this:

On Error Resume NextConst wbemFlagReturnImmediately = &h10Const wbemFlagForwardOnly = &h20Set wshNetwork = WScript.CreateObject("WScript.Network")strComputer = wshNetwork.ComputerNamestrQuery = "SELECT * FROM Win32\_Process"WScript.StdOut.WriteLine ""WScript.StdOut.WriteLine "====================================="WScript.StdOut.WriteLine "COMPUTER : " & strComputerWScript.StdOut.WriteLine "CLASS : ROOT\CIMV2:Win32\_Process"WScript.StdOut.WriteLine "QUERY : " & strQueryWScript.StdOut.WriteLine "====================================="WScript.StdOut.WriteLine ""Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\ROOT\CIMV2")Set colItems = objWMIService.ExecQuery(strQuery, "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)For Each objItem in colItems WScript.StdOut.WriteLine "Caption: " & objItem.Caption WScript.StdOut.WriteLine "CommandLine: " & objItem.CommandLine WScript.StdOut.WriteLine "CreationClassName: " & objItem.CreationClassName WScript.StdOut.WriteLine "CreationDate: " & objItem.CreationDate WScript.StdOut.WriteLine "CSCreationClassName: " & objItem.CSCreationClassName WScript.StdOut.WriteLine "CSName: " & objItem.CSName WScript.StdOut.WriteLine "Description: " & objItem.Description WScript.StdOut.WriteLine "ExecutablePath: " & objItem.ExecutablePath WScript.StdOut.WriteLine "ExecutionState: " & objItem.ExecutionState WScript.StdOut.WriteLine "Handle: " & objItem.Handle WScript.StdOut.WriteLine "HandleCount: " & objItem.HandleCount WScript.StdOut.WriteLine "InstallDate: " & objItem.InstallDate WScript.StdOut.WriteLine "KernelModeTime: " & objItem.KernelModeTime WScript.StdOut.WriteLine "MaximumWorkingSetSize: " & objItem.MaximumWorkingSetSize WScript.StdOut.WriteLine "MinimumWorkingSetSize: " & objItem.MinimumWorkingSetSize WScript.StdOut.WriteLine "Name: " & objItem.Name WScript.StdOut.WriteLine "OSCreationClassName: " & objItem.OSCreationClassName WScript.StdOut.WriteLine "OSName: " & objItem.OSName WScript.StdOut.WriteLine "OtherOperationCount: " & objItem.OtherOperationCount WScript.StdOut.WriteLine "OtherTransferCount: " & objItem.OtherTransferCount WScript.StdOut.WriteLine "PageFaults: " & objItem.PageFaults WScript.StdOut.WriteLine "PageFileUsage: " & objItem.PageFileUsage WScript.StdOut.WriteLine "ParentProcessId: " & objItem.ParentProcessId WScript.StdOut.WriteLine "PeakPageFileUsage: " & objItem.PeakPageFileUsage WScript.StdOut.WriteLine "PeakVirtualSize: " & objItem.PeakVirtualSize WScript.StdOut.WriteLine "PeakWorkingSetSize: " & objItem.PeakWorkingSetSize WScript.StdOut.WriteLine "Priority: " & objItem.Priority WScript.StdOut.WriteLine "PrivatePageCount: " & objItem.PrivatePageCount WScript.StdOut.WriteLine "ProcessId: " & objItem.ProcessId WScript.StdOut.WriteLine "QuotaNonPagedPoolUsage: " & objItem.QuotaNonPagedPoolUsage WScript.StdOut.WriteLine "QuotaPagedPoolUsage: " & objItem.QuotaPagedPoolUsage WScript.StdOut.WriteLine "QuotaPeakNonPagedPoolUsage: " & objItem.QuotaPeakNonPagedPoolUsage WScript.StdOut.WriteLine "QuotaPeakPagedPoolUsage: " & objItem.QuotaPeakPagedPoolUsage WScript.StdOut.WriteLine "ReadOperationCount: " & objItem.ReadOperationCount WScript.StdOut.WriteLine "ReadTransferCount: " & objItem.ReadTransferCount WScript.StdOut.WriteLine "SessionId: " & objItem.SessionId WScript.StdOut.WriteLine "Status: " & objItem.Status WScript.StdOut.WriteLine "TerminationDate: " & objItem.TerminationDate WScript.StdOut.WriteLine "ThreadCount: " & objItem.ThreadCount WScript.StdOut.WriteLine "UserModeTime: " & objItem.UserModeTime WScript.StdOut.WriteLine "VirtualSize: " & objItem.VirtualSize WScript.StdOut.WriteLine "WindowsVersion: " & objItem.WindowsVersion WScript.StdOut.WriteLine "WorkingSetSize: " & objItem.WorkingSetSize WScript.StdOut.WriteLine "WriteOperationCount: " & objItem.WriteOperationCount WScript.StdOut.WriteLine "WriteTransferCount: " & objItem.WriteTransferCount WScript.StdOut.WriteLine ""Next For example, the output from the svchost.exe process looks like this:

Caption: svchost.exeCommandLine:CreationClassName: Win32\_ProcessCreationDate: 20230825044553.785112-420CSCreationClassName: Win32\_ComputerSystemCSName: DESKTOP-7S4VDR9Description: svchost.exeExecutablePath:ExecutionState:Handle: 3044HandleCount: 204InstallDate:KernelModeTime: 312500MaximumWorkingSetSize:MinimumWorkingSetSize:Name: svchost.exeOSCreationClassName: Win32\_OperatingSystemOSName: Microsoft Windows 10 Enterprise|C:\Windows|\Device\Harddisk0\Partition3OtherOperationCount: 113OtherTransferCount: 1636PageFaults: 2378PageFileUsage: 1936ParentProcessId: 588PeakPageFileUsage: 2444PeakVirtualSize: 2203401961472PeakWorkingSetSize: 8744Priority: 8PrivatePageCount: 1982464ProcessId: 3044QuotaNonPagedPoolUsage: 11QuotaPagedPoolUsage: 75QuotaPeakNonPagedPoolUsage: 13QuotaPeakPagedPoolUsage: 77ReadOperationCount: 0ReadTransferCount: 0SessionId: 0Status:TerminationDate:ThreadCount: 6UserModeTime: 0VirtualSize: 2203397767168WindowsVersion: 10.0.19045WorkingSetSize: 7729152WriteOperationCount: 0WriteTransferCount: 0 As you can see, there’s nothing that shows the architecture from that script output here either. If we are in a lower-level coding language like C++, we can use Kernel API calls such as IsWow64Process to figure out architecture of a process. If you are using hacking tools that have that low level access you need, this is when you need to get a bit creative. Let me show you what I mean.

I had a case where a tool I used was based on some vbscript code and I needed to figure out the architecture of some of the processes to exploit further. This meant that I had to investigate ways of achieving that. After a lot of exploring processes in a lab, I realized that the vbscript code (using wmi) outputted the VirtualSize of the process. This is where things got interesting.

You see, every time a process is created in Windows, it allocates memory for that process, and uses something named virtual memory to keep track of things. Simply put, virtual memory is way for the operating system to give processes their own isolated address space. VirtualSize is the amount of virtual address space reserved for a memory allocation within a process (Virtual memory, not actual memory). The nice thing about VirtualSize is that a 32-bit process has a virtual size allocated of 4 GB while a 64-bit process typically has 8 TB.

Trying to test the VirtualSize theory in my lab, I found that key takeaway was that I could differentiate based on the size of the virtual memory. If it was 4 GB and less, then it would be a 32-bit process, and if was more than 4 GB, it would be a 64-bit process.

The VirtualSize output from the vbscript is outputted in bytes so everything less than 4,294,967,296 should be a 32-bit process and everything above should be 64-bit, regardless of how much physical memory is present. There are a few exceptions to this that I have found: “Memory compression”, “Registry”, “System”, and “System idle” processes. From my understanding, there is nothing stopping someone from launching a 64-bit process with a smaller VirtualSize, but based on default behavior, this is rarely the case. I have not yet observed that in my lab or in the wild. That being said, this is of course not a 100% guarantee way of checking it but should be good enough for use in hacking adventures.

Now, let’s write a vbscript function that shows the process architecture. This is what I came up with:

Function list\_processes()Set objLocator = CreateObject("WbemScripting.SWbemLocator")Set objWMIService = objLocator.ConnectServer(".", "root\cimv2")Set col = objWMIService.ExecQuery ("Select Name,ProcessId,ParentProcessId,VirtualSize,ExecutablePath from Win32\_Process")procs = "PID" & vbTab & "PPID" & vbTab & "Arch" & vbTab & "ProcessName" & vbTab & vbTab & vbTab & "Executable Path" & vbCrLfFor Each obj in colif obj.VirtualSize < 4294967296 Thenprocarch = "x86"if obj.processid = "0" thenprocarch = "x64"end ifif obj.processid = "4" thenprocarch = "x64"end ifelseprocarch = "x64"end ifif obj.Name = "Memory Compression" Thenprocarch = "x64"end ifif obj.Name = "Registry" Thenprocarch = "x64"end ifprocs = procs & obj.ProcessId & vbTab & obj.ParentProcessId & vbTab & procarch & vbTab & obj.Name & vbTab & vbTab & vbTab & obj.ExecutablePath & vbCrLfNextlist\_processes = procsEnd Functionwscript.echo list\_processes() Upon running this code with cscript , you can see something like this:

I highlighted some of the x86 processes so they are easier to read. You can see on the top process that it resolves the architecture, even if it cannot read the command line since it is not allowed. This same process of differentiating on VirtualSize could be used in other scripting languages as well to achieve the same result.

What I wanted to showcase in this post was that even if you do not find a way doing something using built-in scripting methods, it does not mean that it is not possible to achieve. Hope you found this useful and learned something new.

The post Creative Process Enumeration appeared first on TrustedSec.

View Details

Have you ever wanted to send an email from a domain you don’t have SMTP credentials for? With some HTML injection, we may be able to do just that.

From time to time, applications have a need to notify users that an action has occurred or that something in the application needs attention. This may come in the form of a notification icon or an email to the user. In modern applications, most emails support HTML, which is often enabled by default. This gives developers a way to include the company logo or a product image in the email along with easy-to-read links for users.

When securing an application, it’s common to HTML-encode user input to prevent client-side vulnerabilities such as XSS. What is less common is encoding in emails that contain HTML. If an HTML-enabled email is sent that contains user input, it can be vulnerable to HTML injection, which can allow an attacker to change the entire body of an email to something the attacker controls and can contain links to malicious sites.

Common places that can allow such behavior are sections of an application in which a user can send invites to other users or notify a user when an action is complete. The injected values can vary depending on the context of the email. An example is an email to a colleague that allows the recipient access to a section of an application. The email might contain the first name and email address of the sender along with the recipient’s email address. It may even allow the sender to craft the email with a markdown editor.

Figure 1 – Markdown Email EditorThe application then sends an email using an HTTP POST request. The body of the request can contain parameters used in the email.

Figure 2 – HTTP Request Body of Email MessageOn the server side of the application, the email may go through an additional audit to ensure that the links added are only for the current domain or the application may add the company image as a header with an unsubscribe link at the bottom.

The issue with not encoding user input in an email is that any unencoded input can allow the entire body of the email to be altered. It doesn’t matter if the input is a name at the start of the email or a signature at the bottom. HTML allows style tags to be set that can be applied globally.

For instance, let’s say we send an email without encoding the current user’s name.

Figure 3 – Email HTMLIf my name is ‘User’ then everything looks fine and the email output on the right is what is expected. But let’s say I just changed my name to:

</p><style>p{display:none;}</style><span>This is now the only thing that shows up.</span><p> I know it’s hard to pronounce but I just felt like it suited me. Now when we render the HTML the original message is hidden, and the only thing left is our message.

Figure 4 – Updated Name in Email HTMLSo, if the application adds a footer that the user cannot control, the original footer can still be hidden and replaced with your own.

In HTML, you can often add the start of an HTML comment to the end of a payload, and anything after that is marked as a comment and not processed. Ending a payload with <!— can hide the original footer and allows us to replace it with our own.

Figure 5 – HTML Comment to Hide Email FooterFigure 6 – Attacker-Controlled Email FooterSometimes it can be hard to know what elements are being used in an email to determine which HTML tag to break out of. Instead of trial and error, you can view the source of the email, which shows the HTML being used. In Outlook, this can be done by right-clicking an email in the inbox and selecting ‘View Source,’ or in Gmail by clicking the more option icon (three (3) vertical dots) when viewing an email and selecting ‘Show Original.’

Depending on how the email was sent and what provider is used by the recipient, the HTML may be in a parameter as a Base64 encoded value.

Figure 7 – Base64 Encoded Email HTMLIf the email is encoded, you can base64 decode the value and put it in a text editor to see where the values you control are shown in the HTML. An easy way to find your input is to use a canary string with a little HTML to confirm the functionality is vulnerable. If your first name is showing in an email, change your name to testqwerty<b>12345</b> and search for testqwerty in the email source to find where the value is added to the HTML. This is similar to injecting an XSS payload, but here we cannot execute JavaScript. If the bold tags in the canary string are unencoded in the email source, then you have HTML injection.

What if we don’t have any user input to edit? Consider something like the forgot password functionality, where the only input we have is the email address of the account. If we inject some HTML into the email parameter, the application won’t send the email because it is not in the correct format.

If you have spent any time looking at application requests, you know there are lots of values that are user controlled other than URL parameters or body parameters. Depending on how the application functions, it may use values stored in request headers, such as the host header or a cookie value. Additionally, some servers will use request headers to determine information about the user, such as the user agent or X-Headers. A header that is commonly used to obtain a user’s IP address is the X-Forwarded-For header. Typically, this is used when a request is proxied so that the server knows where the request originated.

Going back to the forgot password example, let’s say that when a password reset is issued, the user is sent an email with a URL to reset their password. That email may contain something along the lines of:

“A password reset request was issued from California with a source IP address of 8.8.8.8. If this was not you, please contact us using the phone number below. If this was intentional, use the link below to reset your password.”

If that email is using request headers, such as the X-Forwarded-For header to set the value of 8.8.8.8, then you may be able to send other users an email with a body that you control.

Figure 8 – HTML Injection in Request HeaderBecause the header is being entered into the email body (as the IP address), we can break out of the tag the IP address is in. In this case, the IP address is in a span tag inside a few tables. We can break out of the tag with </span> and repeat </td></tr></table> until we are at the HTML root. Now we can add a new div tag with whatever we want the email body to be and add a style tag to hide all the tables in the HTML. We can also end our payload with a starting comment to remove any footer element that may not be inside a table or left over because of missing tags.

When the email renders, all the original content that was stored in HTML tables is now hidden and our div tag is all that remains.

Figure 9 – Altered Email Body With HTML InjectionAdditionally, if the email was using the host header as the domain to create the password reset link, we may be able to change our host header to a domain that we control.

Figure 10 – Host Header InjectionThe request is still sent to the original application domain but the link in the recipient’s email may look something like:

https://mysubdomain.trustedsec.com/password/forgot/88b4f7eb-f302-4153-8f2d-29168cae81e0 If a user then clicks the password reset link in the email, a request will be made to a server we control, and the request will likely have the reset token needed to reset that user’s password.

With email injection, any messages you inject will come from the original sender, and if the subject of the email is vague or user controlled, it can be difficult to know that the email has been altered as it’s coming from a trusted source.

The remediation for this is to HTML encode any user input added to emails. Or if you do not need to use HTML in your emails, then ensure your email functions have HTML disabled. For instance, the SmtpClient Class in .NET allows you to set the IsBodyHtml parameter to false.

As stated previously, this is not XSS, and JavaScript will not run when injected into an email. But any HTML in the body of the email can be changed, and external images can be loaded. At a minimum, an attacker can reveal the IP address of a victim if that victim has external images set to automatically load.

In the end, output encoding is still our friend and will serve you well—as long as you know where your user input is.

The post Crafting Emails with HTML Injection appeared first on TrustedSec.

View Details

This blog post was co-authored with Charlie Clark and Jonathan Johnson of Binary Defense. 1    Introduction One thing often forgotten is that detection engineering isn’t always centered around 1 action to 1 query but also to drive effective incident response to optimize the triage of an alert. This is best served with context. We often...

The post The Client/Server Relationship — A Match Made In Heaven appeared first on TrustedSec.

View Details

Incident Response and forensic analysts use the contents of prefetch files in investigations to gather information, such as the source from which an executable was launched, how many times it was executed, what files it touched, and the date and time it was launched. A prefetch file is like the little brother that tells the...

The post Prefetch: The Little Snitch That Tells on You appeared first on TrustedSec.

View Details

Introduction Attackers are always looking for new ways to deliver or evade detection of their malicious code, scripts, executables, and other tools that will allow them to access a target. We on the Tactical Awareness and Countermeasures (TAC) team at TrustedSec strive to keep up with attacker techniques and look ahead to develop potential evolutions...

The post Modeling Malicious Code: Hacking in 3D appeared first on TrustedSec.

View Details

Cross-Site Scripting (XSS) vulnerabilities are quite common in web applications. These vulnerabilities allow attackers to inject their own JavaScript into the application which can have devastating impacts. TrustedSec regularly creates weaponized XSS payloads on engagements to perform malicious actions such as stealing documents we shouldn’t have access to. One specific form of XSS vulnerability that...

The post Chaining Vulnerabilities to Exploit POST Based Reflected XSS appeared first on TrustedSec.

View Details

As a web application tester, I encounter a recurring challenge in my work: receiving incomplete responses from Burp Collaborator during DNS and HTTP response testing. For example, Collaborator will provide the IP address that performed the DNS look up or HTTP Request. Sometimes, these responses turn out to be false positives caused by intrusion protection...

The post Introducing CoWitness: Enhancing Web Application Testing With External Service Interaction appeared first on TrustedSec.

View Details

An Incident Response (IR) examiner faced with a case or asked whether something ‘funny’ or ‘bad’ happened on a host will wonder if a comprehensive file listing is attainable for the system in question. Sometimes this comes in the form of a question, such as “How long has that malware been there,” or “Was the...

The post Incident Response: Bring Out the Body File appeared first on TrustedSec.

View Details

1.1      Introduction I love when I get tossed a piece of unique malware. Most of the time, malware is obfuscated using PowerShell or a dropper written in C. This time, however, it was obfuscated using Python. How fun! My first thought when I was asked to look at it was, “It’s Python. I’ll just read...

The post Obfuscation Using Python Bytecode appeared first on TrustedSec.

View Details

Introduction The cloud security landscape for AWS has continued to evolve each year to become a complex set of products and best practices with the goal of maintaining a mature security posture. AWS Organizations was released in 2017[1] and has been a major solution to aid in managing the multi-account AWS environment that the cloud...

The post Control Tower Pivoting Using the Default Role appeared first on TrustedSec.

View Details

In the last blog on Parent Process ID (PPID) Spoofing, we discussed how to hide the malicious process by giving it a legit parent. In this blog, we are going to discuss yet another method of hiding malicious code, using Process Hollowing. At a high level, this is where malicious code launches a new process,...

The post The Nightmare of Proc Hollow’s Exe appeared first on TrustedSec.

View Details

THIS POST WAS WRITTEN BY @NYXGEEK

Greetings fellow hackers,

Today we’ll be diving into the topic of user enumeration via OneDrive. I wrote a blog post on this topic a few years back when I first identified the technique. Since then, I’ve learned more about it, and the onedrive_enum.py tool has been updated and is more powerful than ever!

In short, OneDrive can be the best way to do user enumeration because:

  • It doesn’t require a login attempt
  • It’s completely silent (companies cannot see the requests)
  • There’s no rate-limiting

It’s a perfect enumeration method, IF they use OneDrive.

Overview of OneDrive EnumerationOneDrive is a part of SharePoint. It is designed for personal file storage and linked directly to an Azure/M365 account. Whenever a user logs in to various Microsoft services such as Excel or Word, OneDrive is activated, and a personal URL containing the user’s email address is created. To be more precise, this personal URL is actually the account’s UPN, or User Principal Name.

Figure 1 – Example of OneDrive URL Containing AccountSince this personal URL is directly tied to the user’s account, it is then possible to enumerate users simply by looking for web directories in a specific format, similar to using DirBuster/dirb.

Below is a chart showing various services and whether each activates OneDrive.

Figure 2 – M365 Services and OneDrive ActivationIn reality, due to the large number of triggers for OneDrive URL creation, almost anybody who has actually used an Azure/M365 account will have a OneDrive URL.

Once OneDrive is activated, a unique URL is created that is associated with that user. The URL is in the following format:

https:**//<tenant>**-my.sharepoint.com/personal/**<UserPrincipalName>**/\_layouts/15/onedrive.aspx This is illustrated in the screenshot below, where you can see the tenant name is ‘acmecomputercompany’ and the User Principal Name is a translation of ‘lightmand@acmecomputercompany.com’. When a UPN is translated to a OneDrive URL, periods and symbols are stripped and replaced with underscore (“_”) characters.

Figure 3 – Example of OneDrive URL with Tenant and AccountSo, in this way, it is trivial to make a web request and identify whether a username is valid (or rather, whether a user exists who has logged in to their account at least once).

This enumeration is undetectable, as it is a simple HTTP HEAD request to a Microsoft server. No authentication is ever attempted.

Note: Since OneDrive enumeration can only enumerate accounts with licenses, results may be subpar at certain organizations. If they limit Microsoft 365 licenses to specific departments or do not provision them, enumeration coverage will be affected. Examples might be department store sales floor employees and cashiers or non-technical jobs where employees do not use a computer. However, this also means you’re identifying live, actual users with OneDrive Enum—users who might have access to Azure resources.

Identifying Azure Tenant NamesFor OneDrive enumeration to be successful, you need to know the Azure tenant name. An Azure tenant name is a short name associated with an Azure tenant.

Many times, the tenant name for an organization would match the domain name. For example, ‘microsoft.com’ has an associated tenant of ‘microsoft’. But this is often not the case. Sometimes it will be an alternate name, or an abbreviation of an organization’s full legal name.

For a long time, I had searched for a method of identifying the Azure tenant names directly. Without knowing the tenant name or having a means of looking it up, you could easily hit a dead-end with OneDrive enumeration.

Little did I know, Dr. Nestori Syynimaa (@DrAzureAD) had identified just such a method, shared via AADInternals tools (https://github.com/Gerenios/AADInternals). This was brought to my attention by @thetechr0mancer, with the release of TREVORspray (https://github.com/blacklanternsecurity/TREVORspray).

Figure 4 – Lookup via TREVORsprayThis was it! The missing piece of the puzzle! With this new technique, we can reliably use the OneDrive enumeration technique!

Updated OneDrive_Enum Tool v2.0I have released an updated version of the ondrive_enum.py script which can be found here:

https://github.com/nyxgeek/onedrive_user_enum

A number of improvements have been made. More are in the pipeline.

New features:

  • Local DB – Logging of valid accounts, previous enumeration runs
  • Auto-lookup – Automatic Tenant lookup, thanks to Dr. Nestori (@DrAzureAD) and TREVORspray (@thetechr0mancer)
  • Read directory – Read in all files in a directory; useful for multiple similar files (e.g., ‘john.smith’ or ‘jsmith’ formatted user lists)
  • Append – Easily append digits or words to usernames (‘jsmith1’, ‘jsmith2’, etc.)
  • Skip-Tried – Dedupe: checks the run log and ensures that you only run NEW usernames against a particular domain/tenant combination
  • Kill-After – Cancels a userlist if no usernames identified with ‘x’ number of tries

Figure 5 – OneDrive_Enum_v2.pyEnumerating Users with OneDriveFigure 6 – OneDrive User EnumerationRemember, to create the OneDrive URL, we need to know the tenant name AND the domain name. If only a domain is supplied to the tool, then it will attempt to look up the associated tenant automatically, using the lookup method from AADInternals/TREVORspray.

Here is an example of a lookup against Microsoft.com:

Figure 7 – ExampleThe tool looks for any mail sync records, which could indicate a primary tenant. Note that this is not a foolproof method. If it cannot determine the correct tenant, it will show you a list and you will have to pick one.

Below is an example output of the onedrive_enum.py tool:

Figure 8 – OneDrive EnumerationHere we can see that an HTTP status code of ‘403’ (or ‘401’) is what differentiates the VALID account from the invalid accounts.

In the updated OneDrive_Enum script, all enumeration sessions are logged in a onedrive_log table in a local SQLite database. This enables OneDrive_Enum to identify which userlists (and usernames) have been tried. It is also useful for statistics, as it will log the number of ‘found’ usernames per wordlist. This lets you identify top-performing wordlists over time.

In addition to using an SQLite database for logging sessions, all valid usernames are also stored, along with the tenant and domain with which they are associated.

Valid usernames are also written out to a local file at the end of each session for easy grepping.

Tips and TricksMost organizations will only have one (1) tenant defined, and the tool will not have any problem identifying it. However, in the case of multi-tenant setups, you must make a choice (either pick one or all combinations of tenants/domain).

In OneDrive enumeration, the exact combination of tenant name and domain is important. If ‘AcmeComputerCompany.com’ has 3 tenants: ‘acmecomputercompany’, ‘acmeEurope’, and ‘acmeAPC’, then users could exist in any of those tenants.

Possible OneDrive URL combinations would include:

acmecomputercompany – user@acmecomputercompany.com

acmeEurope – user@acmecomputercompany.com

acmeAPC – user@acmecomputercompany.com

This can get further complicated if the organization also uses country-specific domains for email. In many cases this won’t be an issue, but it is something to be aware of. It is also a double-edged sword. While this division of users might increase enumeration time investments, it also allows for targeting users in specific geographic areas. If you encounter this, I recommend running small survey wordlists against all combinations of domains and tenants. You might be surprised!

If you are not getting any hits anywhere, try the ‘tenant.onmicrosoft.com’ address as the domain. During user creation, an admin can choose the tenant ‘onmicrosoft domain’, such as ‘acmecomputercompany.onmicrosoft.com’ instead of a custom domain like ‘acmecomputercompany.com’.

Figure 9 – User Creation Domain SelectionLastly, I want to disclose one additional piece of information regarding OneDrive enumeration. When you try to connect to the OneDrive or SharePoint host (e.g., ‘acmecomputercompany-my.sharepoint.com’), you will receive a ‘403’ or a ‘401’ error response.

When a username returns a ‘401’, that indicates that SharePoint has been configured to require Modern Auth. (This is specifically in regard to SharePoint and not the organization as a whole.)

Figure 10 – Example of Tenant Without Modern Auth RequiredFigure 11 – Example of Tenant With Modern Auth RequiredThe associated setting for Modern Auth in SharePoint can be found here:

Figure 12 – Modern Auth ControlsIf this is set to ‘Block Access’, the OneDrive enumeration (and any request to that OneDrive/SharePoint host) will result in a ‘401’ error. If it is in the default, ‘Allow Access’, it will return a ‘403’ error.

Username ListsThe classic, ‘Statistically-Likely-Usernames’ is a good starting point. However, it should not be your ONLY wordlist source. At least not directly.

The problem is that the wordlists included with ‘Statistically-Likely-Usernames’ are small. The wordlists in the SLU total approximately 1.2 million. This may seem like a lot, but it is inadequate in most cases. Instead, you should build your own.

If your targets are based in America, I recommend using US Census data. Here you can find the 1990 census data, including first names and last names:

https://www.census.gov/topics/population/genealogy/data.html

Specifically, the 1990 files can be found here:

https://www.census.gov/topics/population/genealogy/data/1990_census/1990_census_namefiles.html

I have included these as the ‘firstnames1990.txt’ and ‘lastnames1990.txt’ in my GitHub: (https://github.com/nyxgeek/onedrive_user_enum).

Using these lists, we can generate all of our usernames.

I have included a shell script that can be run, titled ‘generate_usernames_f17.sh’. It will create a ‘USERNAMES’ folder within the project folder, and then proceed to create sub-folders for various username formats.

./generate_usernames_f17.sh firstnames.c2010.txt lastnames.c2010.txt

For easier processing, the files are split up into 175k chunks. This should be a size that is digestable even to smaller machines with less memory. OnedDrive_Enum can take a directory as a source and will iterate through the files within.

File will be written out in the following format:

USERNAMES/john.smith\_1kx10k\_c2010/xaaUSERNAMES/john.smith\_1kx10k\_c2010/xabUSERNAMES/john.smith\_1kx10k\_c2010/xacUSERNAMES/john.smith\_500x20k\_c2010/xaaUSERNAMES/john.smith\_500x20k\_c2010/xabUSERNAMES/john.smith\_500x20k\_c2010/xacUSERNAMES/jsmith\_c2010/xaaUSERNAMES/jsmith\_c2010/xabUSERNAMES/jsmith\_c2010/xac Note: This will take approximately 8GB of space.

Notes for DefendersUnfortunately, there is no way to detect this, that I’m aware of. Microsoft does not consider user enumeration to be a vulnerability.

Your only option is to disable the OneDrive personal sites.

Figure 13 – Disabling OneDrive Personal URLIf you do this, existing users will still have OneDrive URLs that can be enumerated and will need to be cleaned up. This is not an ideal solution, but it is the most you can do until Microsoft takes user enumeration more seriously. Even if you do this and disable OneDrive, there are other methods of user enumeration. Microsoft Graph and Microsoft Teams are major methods.

If we really want to get serious about user enumeration, we need to stop making our usernames the same as our email addresses. Email addresses are by definition a public piece of information that you give out. Usernames don’t have to be public.

Username format also makes a real difference in enumeration resistance. Numeric usernames are the worst, as these are the easiest to enumerate once identified. Simple combinations like ‘jsmith’ or ‘smithj’ are easy to enumerate. While ‘john.smith’ and ‘john.j.smith’ formats offer a greater variety, they also disclose the most PII.

I believe that a format such as ‘jsmith192837’, where the numeric portion is random, would be a palatable yet strong username format. By adding six (6) digits to the end of a normal ‘jsmith’ username, you increase the enumeration resistance by a million. An attacker would then need to iterate through A MILLION attempts just to get any ‘jsmith’ matches. And so on, with ‘jsmith’, ‘ssmith’, ‘rsmith’, etc. This would make massive enumeration unfeasible. For outward-facing employees, mail aliases could be created to allow easy contact with the outside world.

ConclusionOneDrive adoption is at an all-time high. So many actions will inadvertently create a OneDrive URL, whether users are actually using it or not. Couple this with the relative unawareness of most companies about this exposure and the inability to detect it, and we have an ideal enumeration method.

Happy Hacking!

ShoutoutsThanks to Dr. Nestori Syynimaa (@DrAzureAD – AADInternals), @thetechr0mancer and Black Lantern Security with TREVORspray, SkullSecurity (statistically-likely-usernames), @rootsecdev (since HE in turn showed me TREVORspray) and @HackingLZ.

The post OneDrive to Enum Them All appeared first on TrustedSec.

View Details

On May 31, 2023, Progress Software released a security bulletin concerning a critical vulnerability within MOVEit Transfer, a widely used secure file transfer system. According to Shodan, over 2500 servers running this software are on the Internet.

TrustedSec has performed analysis on the vulnerability and post-exploitation activities. At the time of publication, there is no associated CVE or CVS score.

This post will describe the research conducted so far and provide detection, response, and protection recommendations. Additional information will be released as it is found.

VulnerabilityAccording to the MOVEit notification, a SQL injection (SQLi) vulnerability within the application could allow escalated privileges and unauthorized access to the environment. Based on TrustedSec’s analysis of the backdoor seen, a successful attack could allow unauthenticated remote access to any folder or file within a MOVEit system.

Progress has published mitigation steps as well as fixed versions of the software in their notice.

Exploit ActivityAccording to a Reddit thread on the vulnerability, one of the backdoors named in the attack is human2.aspx. According to our research, these backdoors have been uploaded to public sites since May 28, 2023, meaning the attackers likely took advantage of the Memorial Day holiday weekend to gain access to systems. There have also been reports of data exfiltration from affected victims.

TrustedSec was able to gain access to multiple copies of the human2.aspx backdoor and perform analysis. Most of the code within the backdoor samples is the same except for a unique hard-coded password. These hard-coded, randomly generated passwords used for compromises means searching purely for file hashes may be less fruitful.

Figure 1 – Example of Hard-Coded PasswordBackdoorThe human2.aspx backdoor, which is allegedly uploaded during the attack, allows the attacker to do the following:

  • Obtain a list of all folders, files, and users within MOVEit
  • Download any file within MOVEit
  • Insert an administrative backdoor user into MOVEit and give attackers an active session to allow credential bypass

Note that the backdoors examined do not yet return a list of user password hashes from MOVEit.

The human2.aspx backdoor functions as follows:

  • When the page loads, a request header named X-siLock-Comment will be checked against a hard-coded password. If the password does not match, a 404 code is returned.
  • The value of a request header named X-siLock-Step1 is then read in.
    • X-siLock-Step1 will contain a value of -1, -2, or null. A follow-on set of actions will occur depending on this value.
  • If the X-siLock-Step1 value is -1:
    • The Azure Blog Storage Account, Blob Key, and Blob Container IDs are appended to the response header.
    • The following is obtained and returned in a Gzip’d stream:
      • A list of all files and folders stored in MOVEit
      • The file owners and file size
      • All institution names within the MOVEit instance

Figure 2 – Initial Actions for X-siLock-Comment Value of -1 If the X-siLockStep1 value is -2: + A backdoor user named Health Check Service is deleted from the users* table.

Figure 3 – Deletion of Backdoor Account If no X-siLockStep1 value is specified, the backdoor reads in two (2) headers: X-siLock-Step2 (a folder ID) and X-siLock-Step3 (a file ID). + If the values are present, the backdoor responds with the file requested. + If the values are not present, the backdoor: - Adds an administrative user named Health Check Service into the users* table - Creates and inserts a new active session for this user into the application

Figure 4 – Insertion of Backdoor Account and SessionDetectionThere are several steps organizations can take to detect a successful compromise of the attack:

  • Examine the c:\MOVEit Transfer\wwwroot folder for any suspicious files that have been created recently.
  • Examine MOVEit or firewall logs for large outbound network transfers from the MOVEit environment.
  • Search for a user named Health Check Service within the MOVEit user database.
  • Examine active sessions within the MOVEit database for user Health Check Service.
    • Note that the backdoor script modifies the last login time, so this is not a reliable field to examine.
  • Search for web requests that contain any of the request or response headers listed above.
  • Florian Ross has created a SIGMA rule to detect the known ASPX webshell backdoors that are dropped during the attack. This can be found here.
  • Search firewall and MOVEit IIS logs for requests from any of the IP addresses specified within the IOCs below.

If any indicators of compromise (IOCs) are found, organizations should do the following:

  • Contain the system per your Incident Response policies.
    • If the ability to contain does not exist, the system should be isolated on the network by removing network connectivity or pausing the system (if it is a VM).
    • Do not power off the system!
  • Ensure that any network-based logs, including firewall logs, are centralized or saved offline.
  • Begin an investigation or contact your Incident Response provider to begin an investigation.

ProtectionCurrently, Progress has not released a patch but has published mitigations to prevent the vulnerability from being exploited.

Progress’ mitigations are to deny all HTTP (TCP/80) and HTTPS (TCP/443) traffic to the MOVEit environment. Note that this will block all access to the system, but SFTP/FTP will still work, which currently appears unaffected.

However, it is unknown at this time if the insertion of the backdoor account will allow the attacker to log in through the SFTP/FTP interface. Therefore, TrustedSec recommends blocking all access to vulnerable MOVEit servers until a patch is released.

Indicators of Compromise

| Type | Indicator | | Account | Health Check Service | | Filename | human2.aspx | | HTTP Header | X-siLock-Comment | | HTTP Header | X-siLock-Step1 | | HTTP Header | X-siLock-Step2 | | HTTP Header | X-siLock-Step3 | | SHA256 Hash | 2413b5d0750c23b07999ec33a5b4930be224b661aaf290a0118db803f31acbc5 | | SHA256 Hash | 48367d94ccb4411f15d7ef9c455c92125f3ad812f2363c4d2e949ce1b615429a | | SHA256 Hash | 6015fed13c5510bbb89b0a5302c8b95a5b811982ff6de9930725c4630ec4011d | | SHA256 Hash | 702421bcee1785d93271d311f0203da34cc936317e299575b06503945a6ea1e0 | | SHA256 Hash | 9d1723777de67bc7e11678db800d2a32de3bcd6c40a629cd165e3f7bbace8ead | | SHA256 Hash | 9e89d9f045664996067a05610ea2b0ad4f7f502f73d84321fb07861348fdc24a | | SHA256 Hash | b1c299a9fe6076f370178de7b808f36135df16c4e438ef6453a39565ff2ec272 | | SHA256 Hash | c56bcb513248885673645ff1df44d3661a75cfacdce485535da898aa9ba320d4 | | SHA256 Hash | d49cf23d83b2743c573ba383bf6f3c28da41ac5f745cde41ef8cd1344528c195 | | SHA256 Hash | e8012a15b6f6b404a33f293205b602ece486d01337b8b3ec331cd99ccadb562e | | SHA256 Hash | fe5f8388ccea7c548d587d1e2843921c038a9f4ddad3cb03f3aa8a45c29c6a2f |

The following are medium confidence Indicators of Compromise that TrustedSec has not been able to validate, but external partners have indicated have been seen in the attack.

| Type | Indicator | | --- | --- | | IP Address | 89.39.105[.]108 | | IP Address | 5.252.190[.]197 | | IP Address | 5.252.190[.]0/24 | | IP Address | 5.252.189-195[.]X | | IP Address | 138.197.152[.]201 | | IP Address | 209.97.137[.]33 |

Reference* https://community.progress.com/s/article/MOVEit-Transfer-Critical-Vulnerability-31May2023 * https://www.reddit.com/r/sysadmin/comments/13wxuej/critical_vulnerability_moveit_file_transfer * https://github.com/Neo23x0/signature-base/blob/master/yara/vuln_moveit_0day_jun23.yar#L2

ChangelogVersion 1 – Initial publication

Version 2 – Added fixed version information, SIGMA signature, and IP address IOCs

The post Critical Vulnerability in Progress MOVEit Transfer: Technical Analysis and Recommendations appeared first on TrustedSec.

View Details

1 New Blog Series on Common Malware Tactics and TricksThis will be the first post in a series of blogs covering some common malware tactics and tricks. The following list is of topics that will be discussed in these blogs. However, feel free to reach out if there is topic that is not on the list that you would like to read about.

  • PPID Spoofing
  • Process Hollowing
  • DLL Hollowing
  • Thread Queue APC Injections
  • Reflective DLL Injection
  • DLL Injection SetWindowsHookExA
  • Shellcode Injection by Mapping Sections
  • Shellcode Execution with CreateThreadpoolWait
  • Syscall Basics
  • Patching AMSI
  • Windows NamedPipes
  • API Hooking
  • API Hashing for Hiding Functions
  • Hooking Import Address Table (IAT)

Each post will cover the following questions about the focus topic:

  • What is it?
  • How does it work?
  • What do the attackers gain?
  • How can we identify and defend against it?
  • Code Demonstration in C# and C
  • Walk through Ghidra disassembly

1.1 What is PPID Spoofing?Parent Process ID (PPID) Spoofing is a technique used to aid in hiding malicious code from identification. This technique will falsify the PPID of the current executable to be that of any arbitrary process accessible to the current user. By falsifying this PPID, it would appear to any investigator that the current execution belongs or has been started by another benign process. During Incident Response cases, one (1) of the first tasks is to identify if any executable is having an odd or out of place parent. PPID hinders this by making the executable appear to be started by an acceptable process. An example would be if an executable was started by an Excel.exe file, which would raise suspicions of the investigator and warrant further analysis. However, if the process was started by svchost.exe, it would most likely not be immediately seen as suspicious.

1.2 How does PPID Spoofing work?Let’s discuss how the PPID Spoofing works on a high level for Windows systems, in later sections we will get into detailed code samples. The first thing that needs to be done is to identify the parent ID that we want to spoof. This should be done by knowing what is running on that target system and being able to identify what is normal. Once a target process has been identified and the potential parents PID is captured, then we need to setup a list of attributes for the process and its threads. This will then be modified by inserting the PID of the parent we would like to spoof. The final step is to create a new process with this updated attribute list.

1.3 What do the attackers gain?The main purpose of PPID spoofing is to hide, this includes hiding the executable that implemented this technique and hiding the origin of its execution. We already saw the example of having an Office document as the parent to the executable as being a red flag. When the attackers gain access through a web vulnerability, they do not want the parent process being w3wp.exe, as this points directly to the web service as the source of the compromise and would want to protect that information (In case they lose access to their malware and need to gain access to the environment again).

1.4 How can we identify and defend against PPID Spoofing?A limiting factor of PPID Spoofing is that it can only spoof PIDs that the current user has permissions to access/modify. So, if the current user is a low-level user, then they can only spoof one (1) of their own processes. On a live system, Event Tracing can be enabled to monitor the start-up of the process to detect PPID Spoofing. However, this doesn’t help for an executable that is already running or has already executed and currently being analyzed through triage data. For more information on Event Tracing, see https://www.picussecurity.com/resource/blog/how-to-detect-parent-pid-ppid-spoofing-attacks. Elastic.co has written a great blog on how to query and set rules to detect the execution of programs that use PPID Spoofing.

1.5 Code Demonstration in C# and CTo demonstrate how to implement PPID Spoofing, we will discuss a sample written in C and another in C#.

We will start with the example in C.

Line 1: Gets a handle to the process we want to be our new parent

MAXIMUM_ALLOWED(0x2000000) is the desired permissions, and the will be replaced with the PID of the parent process. This can be done differently by searching for processes by name, as performed in the C# sample below. Attackers can only gain access to a handle on the process that they have permissions to.

Line 2: Used to get the size of the Attribute list

Line 3: Allocates a new section of memory for the Attribute List

Line 4: Copies the Attribute List into the newly allocated memory

Line 5: Modifies the Attribute List to include the handle to the parent process obtained in Line 1

Line 6: Sets the Startup info size

Line 7: Launches a new instance of Notepad with the modified startup info that contains the new parent handle

1) HANDLE parentProcessHandle = OpenProcess( MAXIMUM\_ALLOWED, false, <PID>); 2) InitializeProcThreadAttributeList( NULL, 1, 0, &attributeSize); 3) si.lpAttributeList = (LPPROC\_THREAD\_ATTRIBUTE\_LIST)HeapAlloc( GetProcessHeap(), 0, attributeSize); 4) InitializeProcThreadAttributeList( si.lpAttributeList, 1, 0, &attributeSize); 5) UpdateProcThreadAttribute( si.lpAttributeList, 0, PROC\_THREAD\_ATTRIBUTE\_PARENT\_PROCESS, &parentProcessHandle, sizeof(HANDLE), NULL, NULL); 6) si.StartupInfo.cb = sizeof(STARTUPINFOEXA); 7) CreateProcessA( NULL, (LPSTR)"notepad", NULL, NULL, FALSE, EXTENDED\_STARTUPINFO\_PRESENT, NULL, NULL, &si.StartupInfo, π); In the C# example below, we will basically do the same steps described in Lines 1-7 (Most of the Windows API calls are the same, too). However, there is a lot more code involved and much of it is used to setup and define the structures needed to make the API calls.

For example, there is a class called Win32, which is not displayed due to its length, that is used to define structures needed by the windows API.

Line 8: Call the InitializeProcThreadAttributeList, just like we did in the C example which returns the size of the attribute list in the lpSize variable

Line 9: Allocates the memory for the Attribute List

Line 14: Populates the list of attributes

Lines 16 to 30: Varies from the C example above, in that the C# program attempts to locate a currently running process with the names of any of the following: “explorer”, “Services”, or “svchosts”

Line 23: Gets the parent processes handle using Process.GetProcessByname rather than the OpenProcess command from the C example

Lines 31 to 37: Check the Parent Handle is valid then copies its process ID and stores it into the attributes structure

Line 36: Update the list of attributes to include the handle to the parent process

Line 39: A new process is created with the new startup information, causing the new process to have the spoofed parent ID

1) startInfoEx.StartupInfo.cb = (uint)Marshal.SizeOf(startInfoEx); 2) 3) var processSecurity = new Win32.SECURITY\_ATTRIBUTES(); 4) var threadSecurity = new Win32.SECURITY\_ATTRIBUTES(); 5) processSecurity.nLength = Marshal.SizeOf(processSecurity); 6) threadSecurity.nLength = Marshal.SizeOf(threadSecurity); 7) var lpSize = IntPtr.Zero; 8) Win32.InitializeProcThreadAttributeList( IntPtr.Zero, 2, 0, ref lpSize); 9) startInfoEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);10) Win32.InitializeProcThreadAttributeList( startInfoEx.lpAttributeList, 2, 0, ref lpSize);11)12) Marshal.WriteIntPtr( lpValue, new IntPtr((long)Win32.BinarySignaturePolicy.BLOCK\_NON\_MICROSOFT\_BINARIES\_ALLOW\_STORE));13)14) Win32.UpdateProcThreadAttribute( startInfoEx.lpAttributeList, 0, (IntPtr)Win32.ProcThreadAttribute.MITIGATION\_POLICY, lpValue, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero );15)16) var parentHandle = IntPtr.Zero;17) string[] processes = {"explorer", "services","svchosts"};18) foreach (string process in processes)19) {20) try21) {22) Console.WriteLine("trying Parent:: " + process);23) parentHandle = Process.GetProcessesByName(process)[0].Handle;24) }25) catch (Exception e)26) {27) continue;28) }29) break;30) }31) if (parentHandle != IntPtr.Zero)32) {33) lpValue = Marshal.AllocHGlobal(IntPtr.Size);34) Marshal.WriteIntPtr(lpValue, parentHandle);35)36) Win32.UpdateProcThreadAttribute( startInfoEx.lpAttributeList, 0, (IntPtr)Win32.ProcThreadAttribute.PARENT\_PROCESS, lpValue, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero );37) }38)39) Win32.CreateProcess( null, "notepad", ref processSecurity, ref threadSecurity, false, Win32.CreationFlags.ExtendedStartupInfoPresent | Win32.CreationFlags.CreateSuspended, IntPtr.Zero, null, ref startInfoEx, out processInfo ); 1.6 Reversing the codeThe C code discussed earlier was compiled into a Windows 64 bit executable using MinGW, then disassembled and decompiled with Ghidra. As you can see below, the Ghidra generated source code is a very close match to the original.

Figure 1 – Ghidra Generated Code for C ProgramReversing most C# code is simple if you use the tool, dnSpy. There are methods to hide or corrupt the .exe so that dnSpy cannot decompile it but for the most part, attackers do not go to that extent.

To load the executable in dnSpy, simply drag and drop it onto the left pane. Once loaded, the pane will provide a tree listing of the components of the .exe.

Figure 2 – DNSpy’s Executable BreakdownThe listing shows the Main(string[]) function. Clicking on this function will start the decompilation and the output will be display on the right pane. Scrolling down to line 802, dnSpy provides almost the same code as shown above.

Figure 3 – DNSpy’s Decompilation of the C# Executable1.7 ConclusionThe technique of PPID Spoofing is not very complicated and is useful to attackers wishing to obfuscate their attack process. As shown above, the implementation is fairly easy and although there are detections for this type of obfuscation, most of them are disabled by default or require custom rules to be written in order to detect these actions.

The post PPID Spoofing: It’s Really this Easy to Fake Your Parent appeared first on TrustedSec.

View Details

JavaScript is heavily used in almost all modern web applications. Knowing how to format a .js file, set breakpoints, and alter a script’s logic on the fly can be very helpful when working with web applications.

To start, let’s navigate to a website and view the application’s resources. For our example, we are using the angular.io website. To do this, we can navigate to the site’s homepage and press F12, or right-click on the homepage and choose the inspect option.

Figure 1 – Inspect PageThis opens the developer tools, and from there, we can select the Sources tab if we are in a Chromium-based browser such as Google Chrome or Brave. In Firefox, we can use the Debugger tab.

Figure 2 – Developer Tools View1. Lists the resources by domain. 2. Shows the HTML of the current page, including scripts. In this case, we are on the homepage of the application, which is called ‘index’. 3. This would show the contents of the selected JavaScript file. In this case, the file is named main.348210d987da4b84.js, which we will just reference as main.js. 4. Contents of the currently selected item from the document tree; in this case, we have the index page selected. 5. Shows line numbers of the current file, which can be used to set breakpoints anywhere in a JavaScript file or in-between any script tags in an HTML file.

We select the main.js file from the document tree to view the contents of the file. In this case, it’s not really in a readable format. It is common for production applications to minify resource files to help speed up the application. This process usually combines several files into one and changes a file’s variable and function names. Minified files also do not include comments. To help make the file easily readable during debugging, a map file is also generated during the minifying process. These files are not always publicly accessible, as they are only necessary in development environments. Typically, if a map file is accessible, the location of the map is added as a comment at the bottom of the minified file it is mapped to.

Figure 3 – JavaScript File ContentsIf a script file doesn’t contain a map’s location, you can also find map files by appending .map to the original JavaScript file, e.g., site.com/js/main.js.map.

If Chrome can use a source map to unminify a resource, then additional files and directories will show up in the document tree, usually under the Webpack section. We will also have the ability to set breakpoints in an unminified file when debugging—more on that a little later.

Figure 4 – Unminified File StructureIt is common for applications to not include source maps, though, so we need other ways to view and format scripts. An easy way to format a script file is to use the built-in pretty print option in the browser.

Note that all browsers are not made equal, and Chromium browsers seem to be faster at formatting and displaying large JavaScript files than some of the other browsers.

Pretty print helps format the document to make it easier to read but doesn’t deobfuscate any of the code. Variable names and function names that were changed during minification will still be changed in the pretty print view.

Figure 5 – Pretty PrintDepending on why you are looking at a file, you may find it hard to read parts of the document in the development tools window, or you may want to change function names to make code more easily readable. Formatting an offline document can further help you understand the logic in a file. To do this, we can right-click a script in the document tree and select ‘Open in new tab’.

Figure 6 – View Raw JavaScript SourceThis can allow us to copy the whole script to an offline editor, such as Visual Studio Code (VS Code) or Sublime, where we can format the script or perform advanced searches for specific text.

Figure 7 – Format JavaScript in VS CodeIn VS Code, we can create a new document, set the language to JavaScript, and paste the code from the browser that we want to format. Then, we can right-click the document, select ‘Format Document With…’, and use a JavaScript formatter like Beautify to format our script.

Figure 8 – Format JavaScript FileIf you do not have any JavaScript formatters installed in VS Code, you can add them from the extension marketplace.

Figure 9 – VS Code Beautify ExtensionNow that we have an easier-to-read file, we can search the file for useful information such as API endpoints or file paths.

Figure 10 – Regex URL Path Search in VS CodeRegex:

([a-zA-Z0-9_-/]{1,}/[a-zA-Z0-9_-/]{3,}(?:[\?|#][^”|’]{0,}|))

Searching for text like ‘password’ or ‘secret’ may not yield many results if variable names have been changed. Hard-coded text such as the password itself may remain unchanged and could be contained between double or single quotes. Doing a simple regex search for just strings can return valuable information about an application.

Figure 11 – Regex String Search in VS CodeRegex:

:”(?:[a-zA-Z0-9][- ]?){3,20}”

Changing double quotes to single quotes in the above regex, or preceding with an equals sign instead of a colon, can return other string values as well. This can, of course, be done in the browser as well by clicking anywhere in the file contents view of the developer tools, entering regex in the the search bar by pressing Ctrl+F or Command+F, and adding your search term.

Figure 12 – Regex Search in the Developer ToolsOnce we have identified any areas of interest within the script, we may want to see what values are being set for a specific parameter or variable. To do that, we can set breakpoints in the browser.

Going back to the main.js script in the developer tools, we notice that after we applied pretty print formatting, our line numbers are no longer on every line of the script file. Instead, they have been replaced with a bunch of dashes. If we click one of these dashes, we can set a breakpoint.

Figure 13 – Set Browser BreakpointWhen we set a breakpoint, we are actually setting a breakpoint in the unminified file. The file will automatically show in the developer tools, and the corresponding line will be highlighted to show a breakpoint has been added. This happens because the row we are setting a breakpoint on is part of a minified file, and so the browser uses the map file we talked about earlier to expand the document back to its original structure.

Figure 14 – Browser Breakpoint SetIf we want to see the location of the current file in the document tree, we can right-click on the file contents of the unminified file and select ‘Reveal in sidebar’.

We can see in the minified version that the ‘url’ variable was renamed to ‘Re’, but the string text ‘index’ remained the same.

Figure 15 – Unminified Variable DifferencesAs long as no additional obfuscation was added to the original files, string values should remain unchanged. Now we have a breakpoint set on one of the unminified files (document.services.ts), as shown with a blue marker.

Now that our breakpoint is set, we can refresh the page, and as long as our breakpoint is in a function that is called on page load, the browser will pause on our breakpoint. In our example, if we wanted to view the value of the ‘id’ variable, we could allow the browser to skip to the line right after our breakpoint and then hover over the ‘id’ to view its current value—in this case, id has the value of ‘index’.

Figure 16 – Debug JavaScriptThis can be useful in cases where a script has complex logic that can be hard to follow in an offline viewer. You can instead run the script with a breakpoint at the end of a function to obtain a variable’s value after all the logic is executed.

Note that if the JavaScript file you are viewing was not minified, then any breakpoints set would be set in the unminified file, because there would be no map file to open and add breakpoints to.

Let’s say that the logic above was restricting access to additional page contents. Something we can do with the help of a proxy is to change what values are being set in our browser. For this, we will use Burp Suite, and specifically, we will use the Match and Replace functionality in the proxy options. This feature should be available on both the Professional and Community versions of Burp.

Figure 17 – Burp Suite Match and ReplaceWith Find and Replace, we can change the response body of any page that passes through our proxy.

Let’s say we want to set the ‘index’ string in the main.js file to something else, like ‘admin’. For this, we don’t have to use regex, but you can if you would like—we just need to be sure we get the spacing correct. When we are viewing an unminified file, the text shown is not the text that is returned in application responses. The response will contain the minified file contents without formatting. So, we need to find what the value of the text we want to change would be in the application response.

To start, let’s go to our proxy history in Burp and find the script file we want to edit. Note that if the file does not appear in your history, then it is most likely cached, and you will need to clear your cache and reload the page. If you still have the developer tools open in a Chromium browser, you can right-click on the refresh button and select ‘Empty Cache and Hard Reload’. Once you find your script file in Burp Suite, make sure the response type is set to Raw.

Figure 18 – View Raw Response in Burp SuiteNow, let’s find our ‘index’ string in the script response by using the Find functionality.

Figure 19 – Search Response in Burp SuiteNotice that we have three (3) matches. If we only find and replace the word ‘index’, we will change every instance of the string ‘index’ in every page response that is proxied by Burp, not just the script we are trying to alter. Looking at all three (3) matches, we see that the first match looks like the code we set a breakpoint on earlier. The ‘url’ variable has been changed to ‘Re’, like we observed. Now that we know what needs to be replaced, we can add a Find and Replace rule to change ‘index’ to ‘admin’.

Figure 20 – Burp Suite Match and Replace AddFigure 21 – Burp Suite Match and Replace ValuesNow that our Replace is set up, we can close any open scripts in Chrome’s developer tools and refresh the application (clear the cache if needed). When we view the contents of main.js, we see that the script has been changed.

Figure 22 – Updated JavaScript FileDepending on the functionality of the application, this could allow page sections to be viewed that were previously not shown to the user. This could also be used to allow specific file extensions during file uploads, which allows any file types to be uploaded and bypasses any client-side restrictions. Thats why it’s important to check any client-side logic on the server side of an application as well.

In our case, the application tried to pull in a resource that included our changed text.

Figure 23 – Response Changes Included in RequestIn some cases, you will find that script files pulled into the application are very large and cause the application to lag when proxied.

Figure 24 – Large JavaScript FilesTo help this, you can set the scope of your Burp project under the Target – Scope tab and check the ‘Use advanced scope control’ option. Then, set your target domain, and exclude from scope any large files that can slow down the application when proxied.

Figure 25 – Setting Specific Domain Scope in Burp SuiteTo exclude file types, you can use a regex like this:

.*.map

This would set any .map files out of scope. Additionally, you can right-click a file in the proxy history and select ‘Remove from scope’. In some cases, applications pull from external domains, so you may need to allow all domains in your scope.

Figure 26 – Setting any Domain Scope in Burp SuiteRegex:

^.*$

Once you exclude files from your scope, you can refresh your application, and your out-of-scope request will no longer be sent to the proxy history or live tasks.

Figure 27 – Large JavaScript Files Removed From Burp Suite HistoryNote that for this to work, Burp needs to have the option turned on that prevents out-of-scope requests from being added to the history, which it does by default when you set a scope for the first time. If you need to toggle the option, it’s in the proxy options under Miscellaneous.

Figure 28 – Burp Suite Out-of-Scope ConfigurationAdditionally, you may need to set your proxy options to only allow in-scope requests.

Figure 29 – Burp Suite Proxy History Filter OptionsNow, you should be able to view, format, search, debug, change, and exclude script files in your proxy the next time you look at a web application.

The post JavaScript Essentials for Beginning Pentesters appeared first on TrustedSec.

View Details

Analyze the balance between gaining useful information and avoiding detection, detailing recon techniques that can be employed without compromising stealth.

Rob Joyce, who at the time was Head of the NSA’s Tailored Access Operations group, had this great quote from a 2016 USENIX talk:

“We put the time in to know that network. We put the time in to know it better than the people who designed it and the people who are securing it. And that’s the bottom line.”

The concept of truly understanding a network can be applied to the commercial side of testing. In the adversary simulation space, you usually land on endpoints with a list of client objectives. Most adversary attack simulations start from a zero knowledge perspective, and a fast ramp-up is needed. If you’re currently not in this space or have taken classes on red teaming, internal discovery is usually a couple of bullet points or hyper-focused on tools. What’s generally covered is in-depth AD exploration and concepts around specific tools like BloodHound or a single recon script. From my experience, I have found this lacking as there is a longer-form process many red teamers take, which is usually not exciting or easy to lab up. The discovery process includes many more things, like reviewing internal documentation, internal websites, and initial host configuration, to name a few.

Host-based discovery is vital in building a picture and attack plan for a target organization. When one lands, taking the time to focus on the host also provides a way to measure the level of maturity of the organization by looking at the controls in place and how they’re configured. A lot can be gleaned during host enumeration—it provides context that can dictate the operational tempo and tools used based on those controls. In most engagements, it is not that important, but in red teaming, it is critical, given that the exercise is conducted against mature organizations. We want as much data as possible so that if complete network eviction occurs, we have the information needed to help regain access.

Many new red teamers come from traditional pentest backgrounds. Penetration testing favors shorter-time box assessments and has testers trained to move more quickly and compromise other systems quickly. The mindset shift is not necessarily easy, and it’s common to see newer testers move on from the recon phase quickly when they first make the red teaming jump. By moving too fast, important information can be missed by the host, and it can also introduce risk by creating patterns of behavior that stand out. Things can also go in the other direction and cause analysis paralysis, with being afraid to do anything for fear of getting caught. This is why understanding modern defensive products and detection engineering is now a building block for offensive testing. Building a strong vetted recon methodology will to help new testers gain confidence to better plan and execute testing as well as open up opportunities for them to contribute new and novel points of view.

PlanningWe want to constantly explore and improve low-risk, low-noise recon methods and improve tools and techniques to gather valuable information without triggering alerts. We use this approach to inform and build a methodology and playbook that leverage as much directly accessible information as possible to build better attack paths. The goal is to stay within normal user behavior for as long as possible. We are avoiding unnecessary Windows API calls, network traffic, and accessing systems outside the typical bounds of the user. Ultimately, we will increase our level of risk after we complete a round of host-based recon and normal user network behavior.

StepsThe first step in building a methodology is picking a centralized place and a sharable format, for example, Obsidian, which allows knowledge transfer across the team and a central place to pull ideas from when building internal tooling and standard workflows. Obsidian can be substituted for whatever works best for you or your team and ultimately leaves the reader with a choice. Adoption of a standard is the crucial part though, not the underlying tool.

A good second step is finding ways to feed the living methodology such team debriefs. After every engagement, have a team meeting for a fixed length of time to document and review what worked and what didn’t, and feed ideas back into this. If you’re solo or just looking for new inspiration, Twitter, blogs, and other CTI sources can also help evolve and inspire your reconnaissance process.

The third area to focus on is understanding the detection space and to keep that in mind while risk-ranking reconnaissance and future activities. A great place to start is published rule sets such as Sigma, Elastic, and all of the various published resources around Microsoft Sentinel. Knowing what the majority of defenders are looking for will help direct where to stay away from or if that area is worth the extra time and effort into evasion research.

The last area would be building a lab environment to test and validate your offensive hypothesis and integrations you made to your toolsets from the newly built methodology. There are lots of options in this space and several blogs and YouTube videos on the subject. The key components you want include are some sort of SIEM and the ability to capture events via Sysmon or, better yet, access to EDR products you will encounter during testing.

By the end of your planning process and steps to be taken, you should have picked a platform as a shared medium in addition to a couple of internal processes to start both the build out and a plan to validate.

On-Host ReconAssumptions going into this are that we have an implant running a low-level user and reliable command and control(C2) with the ability to offload files. We can achieve this by leveraging the cloud providers/CDNs/categorized domains or utilizing multiple C2 channels—one for C&C and one for exfil. An additional assumption is that the target system is running an EDR product and ingesting and acting on alerts typical of most organizations having red team engagements performed.

Consider the following example commands from the Conti playbook:

Figure 1 – Conti Playbook LeakWhy would we want to avoid things like the above?

This behavior is known and commonly has detections written for it or a series of commands in a short period. The MITRE evaluations did an excellent job of highlighting host reconnaissance commands used by threat actors in the wild and the EDR’s ability to trigger an alert on them. I chose three of the EDR products we most encountered the last year at TrustedSec and included the MITRE evaluation links to the detections, which include screenshots of alerts firing on this behavior.

CrowdStrike – https://attackevals.mitre-engenuity.org/enterprise/participants/crowdstrike/subtechnique/T1087.001?adversaries=wizard-spider-sandworm&wizard-spider-sandwormdetection=5.A.3_0

Microsoft MDE – https://attackevals.mitre-engenuity.org/enterprise/participants/microsoft/subtechnique/T1087.001?adversaries=wizard-spider-sandworm&wizard-spider-sandwormdetection=5.A.3_0

SentinelOne – https://attackevals.mitre-engenuity.org/enterprise/participants/sentinelone/subtechnique/T1087.001?adversaries=wizard-spider-sandworm&wizard-spider-sandwormdetection=5.A.3_0

The above is a specific case of cmd.exe calling net.exe. However, many detections are written from process creation events combined with command line arguments and the parent process. We can avoid calling these binaries directly and live inside the initial implant process utilizing Beacon Object Files (BOFs) or frameworks that use standard Windows APIs.

BOFs were first implemented inside Cobalt Strike, but multiple frameworks have adopted the ability to execute them. The power of BOFs for reconnaissance is removing cross-process injection, running other Windows binaries from cmd.exe, or dealing with PowerShell. TrustedSec has several deep dive blogs on this topic from basics to development:

A DEVELOPER’S INTRODUCTION TO BEACON OBJECT FILES

https://www.trustedsec.com/blog/a-developers-introduction-to-beacon-object-files/

SITUATIONAL AWARENESS BOFS FOR SCRIPT KIDDIES

https://www.trustedsec.com/blog/situational-awareness-bofs-for-script-kiddies/

BOFS FOR SCRIPT KIDDIES

https://www.trustedsec.com/blog/bofs-for-script-kiddies/

CHANGES IN THE BEACON OBJECT FILE LANDSCAPE

https://www.trustedsec.com/blog/changes-in-the-beacon-object-file-landscape/

COFFLOADER: BUILDING YOUR OWN IN MEMORY LOADER OR HOW TO RUN BOFS

https://www.trustedsec.com/blog/coffloader-building-your-own-in-memory-loader-or-how-to-run-bofs/

PlaybookLet’s start building out an initial playbook for information we want to gather. This is in no way complete but will allow us to start building a repeatable workflow and supporting tooling.

Host Based Configuration

  • Is it domain joined, hybrid, cloud joined, or standalone?
    • Is auditing configured?
    • Are there logs shipped off system?
    • Who uses the system, and where do they fit into the organization?
  • How stable is the system?
    • Does the system crash, and if so, how often?
    • Is the system suspended or shutdown at the end of the workday?
  • History of profiles of users that use the system
  • Connections and connection history
  • Tokens and credentials under the context under which we are running
  • Proxy configuration
  • User behavior analytics
    • https://www.trustedsec.com/blog/oh-behave-figuring-out-user-behavior/

Installed Software

  • What applications does this user live in?
    • Outlook?
    • Browser of choice version
      • For recon and user-agent mirror for C2
      • Credentials and cookies
    • Thick clients?
      • Electron apps vulnerable to token stealing
  • Can we tell how this system is managed from installed software?
  • EDR/AV Products
    • Exclusions
    • Configuration level when possible
      • Identifying EDR products in a more passive manner, you can pass a directory listing of C:\Windows\System32\Drivers into https://gist.github.com/HackingLZ/b7e5ef65524bb986c16882ef534715c4.
      • This will look up the drivers based on name and match the corresponding altitude number range https://learn.microsoft.com/en-us/windows-hardware/drivers/ifs/allocated-altitudes. For example, AV products are within the range 320000 – 329998.
  • Application Control
    • Built-in capabilities – third party or both
  • Driver Enumeration
    • Altitude numbers/defensive products
    • Outdated, hardware-specific IE Dell
    • Vulnerable drivers that can be abused
  • VPN Client
    • Common Priv Esc path
    • Is it connected? Many enumeration tasks may depend on whether there is a connection to the corporate network.
  • Password Storage – LastPass/KeePass
  • Office Version
    • Security features and defaults vary from version to version.
  • Printers – Large printers are a great source of LDAP or pivoting.

Common Folders

  • Desktop
  • Downloads
  • Temp
  • Trusted Locations – https://learn.microsoft.com/en-us/deployoffice/security/trusted-locations
  • *C:* – Organizations often have standard build/tool folders here.

Honey Documents

There are a few defensive products that plant document files which trigger an alert on access and are often marked as such to stop automated ransomware activity. These are usually easy to spot. Alternately, there is a rise in documents that contain a canary token which trigger upon opening of the document. We are able to identify these documents with methods such as this example PoC: https://gist.github.com/HackingLZ/8fed5fa4983b63b773380e1a8e82478a

Ideally, any documents you take offline are opened in an isolated VM; however, identifying the presence of honey documents can increase your caution level when it comes to accounts and other areas.

Chat logs

  • Slack
  • Teams

Video Conferencing Software

  • Webex
  • Zoom

Email – C:\Users\UserName\AppData\Local\Microsoft\Outlook

  • Help Desk/IT emails
  • Signatures
  • Emails with files attached
  • Upload/Download portals
  • Emails to template for phishing pretexts
  • GAL
  • MFA products

Browser

  • Bookmarks
  • Internal resources
    • Employee lookup tools
    • SharePoint/Wikis
      • Secure Secrets/Password Storage
      • Network documentation
      • IP documentation
    • IT Support/Help Desk
  • Plugins
  • External resources (future pretexts)
    • 401(k)
    • Payroll
    • eLearning

Stored Credentials

  • Password reuse is obvious
  • Password patterns
  • Overlap with domain password

Job Role Specific Tools

  • WSL
  • Python
  • Visual Studio
  • AWS CLI tools
  • Putty
    • Logs/Keys

Other Areas of Interest

  • DNS cache
  • PowerShell history
    • APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt

The last part of on-host reconnaissance and something to always consider is cohabitation. The topic of overlapping events while testing is not discussed often, but it does happen. There is always a chance a threat actor could compromise a system before any testing activities, or potentially, a previous vendor could leave behind artifacts from a penetration test or red teaming. It is often more common on Internet-facing systems like legacy web servers. If you’re going down the path of building some of the host-based reconnaissance into your toolsets, then including checks for standard persistence methods, odd processes, and other IOCs could go a long way in helping clients identify an event that otherwise went unnoticed. Adding features to recognize cohabitation doesn’t reduce the need for proactive threat hunting and other blue team activities, however.

Off-Host Normal Network BehaviorThis is great opportunity to make use of SOCKS features in implants. If we don’t have the users’ passwords, there are BOFs and other methods to prompt the user for their password, which is often effective and goes unreported or detected.

Cloud File Storage

  • OneDrive, Box, Dropbox, SharePoint, Azure Storage Accounts, AWS S3 Buckets
  • Potential mirror vendor for large file exfiltration

Review of bookmarks from previous phase

Internal Employee Lookup Tools

  • Common in large organizations where internal employee lookup tools are built and are often backed by LDAP or other internal technologies and very rarely, if ever, are monitored when you compare it to something like AD directly.

File Shares related to job role

NETLOGON/SYSVOL

  • Netlogon scripts for some reason keep giving
  • Mapped drives
  • Stored scripts

Azure Enumeration

  • Graph API
    • For the future: https://learn.microsoft.com/en-us/azure/azure-monitor/reference/tables/microsoftgraphactivitylogs
  • Look for cookies and try to extract the PRT (Primary Refresh Token).
  • Bearer token extraction and reuse

Other Cloud Platforms

  • Depending on the type of user and applications, we can look for authentication tokens, keys, and passwords.
  • What services are being accessed?

ServiceNow

Centralized Knowledge Bases

  • SharePoint
  • Confluence
  • Wikis

Help Desk Tickets/Systems

  • Can we find support tickets that may contain sensitive information by browsing the system under our current context?
  • Can we find ticket information in emails?

GitLab/SVN

  • Be aware, mass cloning browsing usually goes unnoticed, but users often have limited access.

Revisit Chat platforms to search for credentials across channels.

FinThe goal here wasn’t to build an inclusive list of every possible option but to help start building a post-exploitation methodology for gathering decision-making data.

At a minimum, we understand what defensive controls are on a workstation and the installed programs, versions, and other information with which we can start making informed decisions. Hopefully by the time you’re done with situational awareness, you can answer questions such as:

  • What is the risk vs. reward of elevating privileges on the current system?
  • Are we better off moving on from this machine or switching it to a long-term C2 host?
  • How are the systems managed?
  • What did I learn from bookmarks?
  • Are there any emails I can use for follow-on pretexts? What file types are included with emails or links?

Attack paths are often highlighted in the MITRE IDs an attacker used, but the decisions about why they avoided one for the other are less discussed and will be topics of future blogs. Even behavior that could be written off as basic might have been done for a particular reason, like being evasive.

Lastly, a huge thanks to Carlos Perez, Jason Lang, Edwin David, and Paul Burkeland who contributed comments, suggestions, and methodology ideas to this post.

The post Walking the Tightrope: Maximizing Information Gathering while Avoiding Detection for Red Teams appeared first on TrustedSec.

View Details

IntroductionYour organization has invested significant effort in formally documenting its approach toward cybersecurity to enhance accountability and awareness of security processes; however, operationalizing and enforcing this policy library can appear challenging. Failure to consistently enforce cybersecurity policies generally leads to a degradation of the environment, as individuals come to understand that they will not be held accountable for violating corporate decisions and guidelines.

To mitigate this risk and maintain a strong cybersecurity environment, it is crucial to establish clear policy enforcement processes by ensuring that policies are approved by all relevant parties, policies are distributed and communicated, adherence to policies is monitored, and policy exceptions are appropriately managed.

Identify Key Stakeholders and Solicit FeedbackDuring the development of policies, key stakeholders that will be affected by or responsible for the enforcement of policies should be identified and solicited for feedback. Contention can be reduced by gathering feedback prior to the formal establishment of a policy by ensuring all stakeholders agree with the structure, requirements, and measurement approach.

Key stakeholders are generally thought to include executive management, business unit managers, and operational managers; however, soliciting feedback from non-management personnel educated on best practices or involved in the day-to-day operations, such as security personnel or system users, can be crucial.

Personnel unfamiliar with the policy subject can be beneficial in ensuring the policy is adequately articulated and conveys the intended message. Engaging a variety of individuals not only encourages a culture of shared responsibility and collaboration but also helps uncover potential gaps or ambiguities in the policy that may otherwise go unnoticed.

Policy Distribution, Awareness, and TrainingOnce the policies have been approved and refined with input from key stakeholders, the next step is to ensure effective distribution. It is essential to maintain consistent storage and version control of all policies by utilizing a centralized document management system readily available to all personnel.

To increase awareness of policy changes, consider leveraging multiple communication channels, such as:

  • Email notifications containing policy updates and reminders
  • Physical copies of policies located in common areas
  • Periodic company-wide meetings or webinars discussing policy changes

Personnel may not always understand the reasoning behind a policy change. To encourage a security-conscious culture, it is essential for the organization to provide awareness and training strategies. For example:

  • Explain why the policy is being enforced and describe the risk the policy is designed to mitigate.
  • Use real-life examples and scenarios to illustrate the importance of policy adherence.
  • Highlight key policy elements and concepts when providing notification of changes, as personnel may not read all policy documents.
  • Encourage open dialogue and discussion regarding policy concerns or clarifications.
  • Assess employee comprehension through quizzes, simulations, or practical exercises.

Effectively training personnel on the rationale behind policies and encouraging open dialogue to discuss concerns will help foster an environment where security is ingrained in the organization’s culture.

Monitoring Policy AdherenceConsistently monitoring policy adherence is essential to ensure that personnel are following the established company guidelines. Performing regular audits, leveraging automated monitoring tools, and encouraging a culture of reporting can help detect policy violations.

Establishing regular audits is recommended for monitoring policy adherence; in its simplest form, this includes the following steps:

  • Determine the audit scope based on the organization’s priorities, risk tolerance, and regulatory requirements.
    • The scope should identify and document the policies, processes, controls, and systems that are to be audited. At a minimum, these should include policy updates, policy training and review, incident response testing, periodic access reviews, restoration testing, and vulnerability scans
  • Establish an audit calendar and define the frequency of audits. Ensure any regulatory or compliance requirements are identified when establishing audit frequency.
  • Communicate the audit plan and objectives with relevant stakeholders, such as department heads and system owners.
  • Document audit findings and include evidence of noncompliance or areas for improvement.
  • Define and track a plan for remediation efforts.
    • This includes establishing timelines for remediation, assigning responsibility to specific personnel, coordinating with relevant stakeholders, and conducting follow-up audits to confirm the effectiveness of remediation efforts.
  • Continuously improve the audit process by soliciting feedback from auditors and stakeholders to identify areas of improvement.

When policy violations are detected, addressing them efficiently and consistently is crucial. Management should encourage and reinforce the importance of compliance and provide constructive feedback to personnel to help improve their understanding of the policy. Constructive feedback may involve disciplinary actions, additional training, or process improvements to prevent future occurrences.

Encouraging personnel to feel comfortable reporting potential policy violations or concerns without fear of retribution can help ingrain security into the organization’s culture and foster a secure environment. This can be achieved by maintaining open communication and collaboration or by implementing an anonymous reporting system.

Managing Policy ExceptionsSometimes policy exceptions may be necessary due to a gap between the current policy and the need to accommodate unique business requirements or unforeseen circumstances. Establishing an exception management process is essential to ensure that exceptions are handled consistently and with appropriate risk management considerations.

At a minimum, an effective policy exception management process includes the following steps:

  • Define an exception request process. Often the security team will review exception requests; however, a better approach is to have a management stakeholder or sponsor sign off on the risk and have security advise on the risk and controls.
  • Document the business justification, potential risk, and possible compensating controls.
  • Communicate exception results with appropriate personnel that may be needed in the implementation of compensating controls or may be affected by the potential risk.
  • Define an exception expiration date based on the approval date or a predefined global review period. This ensures that exceptions are periodically reviewed to determine if they are still necessary or if the associated risks have changed.
  • Track and consistently review exception requests to identify areas of improvement that may be needed in the currently adopted policy.

ConclusionUltimately, the success of an organization’s cybersecurity program depends on the consistent enforcement of security controls and the commitment of all personnel. Effective cybersecurity policy enforcement is critical for maintaining consistency across security controls and is often required to meet obligations with respect to contracts and regulatory requirements.

By soliciting appropriate feedback prior to adopting a policy, distributing and training personnel on the policy, and consistently addressing noncompliance, an organization can foster a culture that continuously improves its security posture and reduces risk.

The post Cybersecurity Policy Enforcement: Strategies for Success appeared first on TrustedSec.

View Details

Watch “Learning Sysmon,” a new video series hosted by Research Team Lead Carlos Perez on YouTube now!

  1. What is Sysmon?
  2. Installation
  3. Command Line Configuration
  4. Sysmon Configuration File
  5. Rule and Filter Order
  6. Process Tracking
  7. File Create Time
  8. Network Connection
  9. Tracking When Drivers Are Loaded
  10. Detecting Abuse via Process Access

The post Learning Sysmon – Videos 1-10 appeared first on TrustedSec.

View Details

1 TLDR;Microsoft is releasing an Azure AD integrated, built-in LAPS agent to Windows 10 and Windows 11 that can be controlled by Intune.

1.1 Problem StatementMigrating Windows endpoints to Intune-only management left gaps in controllable settings. An alternative for traditional Local Administrator Password Solution (LAPS) in an on-premises domain has been a primary gap. Third-party tools and DIY solutions existed but introduced complexity and insecurities. Microsoft is now releasing a new version of LAPS that will be built in to the Windows OS, integrates directly with Azure Active Directory (AD) for password escrow, and is configurable natively in Microsoft Endpoint Manager (MEM/Intune).

1.2 AudienceOrganizations and teams managing Azure AD joined endpoints looking to remove dependencies of on-premises AD

1.3 Prerequisites* Azure AD joined or Hybrid joined Windows 10 20H2 or later systems * A configuration management tool capable of applying CSP or Registry settings

2 Windows LAPSMicrosoft’s legacy LAPS tool has long provided a necessary mechanism for maintaining administrative accounts on endpoints. IT and security teams have traditionally deployed and configured this tool by Group Policy to meet numerous security requirements, including:

  • Automatically rotating privileged passwords on endpoints
  • Maintaining access to endpoints that lose domain membership
  • Providing end users temporary privileged access while unreachable by RMM tools
  • Performing troubleshooting or IR access to potentially compromised devices

With organizations trending toward a primarily remote workforce, many of the tools and techniques that have depended on local AD have become a significant pain point for IT. Legacy LAPS was no exception, with its dependance on Group Policy for deployment and local AD as the only option for storing device passwords. Later versions of legacy LAPS supported uploading passwords to Azure AD but could still only be deployed and configured by Group Policy. This restriction meant that teams wanting to leverage the Microsoft native solution were forced to keep devices tethered to AD.

Step in, Windows LAPS! In the April cumulative update for Windows, Microsoft has released Windows LAPS. This version is built in to Windows 10 devices running 21H2 or later and can be configured by Configuration Service Provider (CSP), including through Intune. Since it’s officially in public preview, let’s kick the tires!

2.1 PrerequisitesWe need to first enable the preview feature in Azure AD:

Azure AD or Entra > Devices > Device settings > Enable Azure AD Local Administrator Password Solution (LAPS)

While we’re here, let’s make sure users (and attackers) can’t get their own BitLocker keys.

Figure 1 – Enable Azure AD LAPSNext, let’s get an Intune-managed system updated to the version of Windows that includes Windows LAPS. We’ll check for the 2023-04 Cumulative Update (CU) and make sure we’re enrolled and synced with Intune.

Figure 2 – Windows 10 Update StatusFigure 3 – Azure AD Join StatusFigure 4 – Intune Registration StatusIf the legacy LAPS agent is installed, make sure to remove it at this point to avoid conflict with the new policy.

2.2 Create a ProfileNow we need to set up a policy in Intune. I have been using the Windows LAPS CSP, but there is a new Account Protection policy template for Windows LAPS here:

Intune > Endpoint Security > Account Protection > Create > Windows 10 and later > Windows LAPS

Figure 5 – LAPS Profile TemplateAlternatively, you can still use the CSP in a custom template here:

Intune > Devices > Configuration profiles > Create profile > Windows 10 and later > Templates > Custom

https://endpoint.microsoft.com/?ref=AdminCenter#view/Microsoft_Intune_DeviceSettings/CreatePolicyFullScreenBlade/policyId/00000000-0000-0000-0000-000000000000/policyType/Windows10Custom/policyJourneyState~/0

Many of the settings shown below are default values and do not need to be configured. I prefer to set these settings anyway, to remove any doubt, and so I can verify that the setting was applied through the Per Setting Status later. A description is also optional, but since the value is not directly visible from the profile, I use that to note a friendly value of the setting. There are other settings for devices syncing the LAPS password to on-premises, but you can ignore those settings for Azure AD.

https://learn.microsoft.com/en-us/windows/client-management/mdm/laps-csp

2.3 Create a New Local Account (Optional)If you configured LAPS to manage the built-in local Administrator account, you can skip this section. LAPS looks up the local Administrator account by well-known Security Identifier (SID), so if even if you’re using a renamed Administrator account, you can skip this section.

If you configured LAPS to manage a custom account name, you need to create the new account separately. There is a CSP for creating local accounts, but the documentation isn’t quite as clear. The account’s username goes directly in the path of the OMA-URI, not as a value. Check out the placement of TrustedSecAdmin in the two (2) settings below to see what I mean. Change the username and initial password to your own. If you configured the LAPS profile above via CSP, you can add these two (2) settings to the same profile.

https://learn.microsoft.com/en-us/windows/client-management/mdm/accounts-csp

2.4 Make it So!Assign this policy to the test device and force a sync. Wait a few minutes for the profile to pull down and get applied. If you configured LAPS to back up to Azure AD, Windows registers Event ID 10022 to the Microsoft-Windows-LAPS/Operational Log once the profile is successfully applied.

(Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-LAPS/Operational';Id=10022}|Select-Object -First 1).Message Figure 6 – LAPS Policy Application EventThe new profile should trigger LAPS to do a sync and generate Event IDs 10029 and 10020.

Figure 7 – LAPS Password Reset EventsIf this doesn’t happen or you need to adjust the policy and trigger a new LAPS reset attempt, run this command:

Invoke-LapsPolicyProcessing Check that the device’s password is visible in Entra/Azure AD. There is a handy new menu that will show every device with a password uploaded:

Figure 8 – LAPS Device Password EscrowAnd that’s it! Now you have a cloud-native, built-in LAPS solution deployed.

If you were pushing local administrators with Azure AD or Intune previously, you can now roll that policy back. Having any account with administrative access to many devices is a bad idea.

Lastly, remember to train support staff with information on what the local administrator username is and where to get the password before deploying the profile to the fleet.

The post Windows LAPS: Closing a Gap for Cloud-Native Device Management appeared first on TrustedSec.

View Details

IntroductionMany compliance frameworks require Information Security Risk Assessments, and some organizations may receive third-party requests for Risk Assessment results. Organizations without any compliance obligations will still benefit from Risk Assessment as they are a key tool for efficiently increasing Information Security maturity and, more importantly, aligning Information Security with business needs and constraints.

This post defines the Risk Assessment process at a high level and guides organizations to other resources that can help them conduct their own Risk Assessment or vet third parties offering Risk Assessment services.

What Is a Risk Assessment?An Information Security Risk Assessment determines the level of risk posed to the organization by specific threats to their Information Security. The results of the Risk Assessment are intended to be used to determine which security controls should be implemented to reduce these risks and prioritize them for implementation. The results can also enable executive leadership to make appropriate business decisions with an understanding of potential losses.

An information security Risk Assessment requirement is often included in compliance frameworks because most frameworks are based on a generic risk assessment that more or less apply to the information that the framework is concerned with protecting but cannot account for the unique circumstances at every organization implementing the framework. Requiring each organization to conduct their own Risk Assessment is a way of forcing them to consider these unique circumstances and address the additional Information Security risks that the framework does not address.

ISO 27005 and NIST SP 800-30 are documented Risk Assessment methodologies that are often used to support compliance with ISO 27001, NIST SP 800-53, NIST SP 800-171, and other compliance frameworks. While both methodologies use slightly different terminology, they both follow the same basic process:

  • Establish risk criteria
  • Identify threats to information security
  • Apply risk criteria
  • Determine risk treatment

What a Risk Assessment Isn’tThere is often confusion about what a Risk Assessment is and is not. I have asked for Risk Assessment results many times in my career and have often been handed various reports that did not result from the process described above. These often include vulnerability scan reports, penetration test reports, gap assessment reports, and internal audit reports. All those documents are useful inputs to a Risk Assessment process but are not Risk Assessments by themselves.

A previous post described a variety of common compliance frameworks including NIST CSF, NIST SP 800-53, NIST SP 800-171, CMMC, HIPAA, GPDR, ISO 27001, and PCI DSS. Some organizations offer ‘Risk Assessments’ conducted ‘using’ one (1) of those frameworks. From the reports I have seen, these are typically conducted by determining which of the framework controls are not in place and flagging those missing controls as risks. While the missing controls likely result in increased risk, calling this method of assessment a Risk Assessment is a misnomer. This process would be more accurately described as gap assessment with some risk-based window dressing tacked on. This is because there are no identification of threats, impacts, or likelihoods. There is simply a statement that a control is not in place and an indication of risk, usually subjective based on how important the assessor deems each control.

None of the frameworks described above are suitable methodologies for conducting a Risk Assessment. In fact, nearly all the frameworks described above explicitly require conducting a Risk Assessment. It would be a paradox for a framework that contains a requirement to conduct a Risk Assessment to be used to conduct a risk assessment.

Many organizations conduct high level Risk Assessments that consider threats to the business, (e.g., Changing market conditions, political instability, inflation, etc.). Often, these Risk Assessments will include Information Security as a single line item. These are, in fact, Risk Assessments, but they are not Information Security Risk Assessments, even with the Information Security line item. A true Information Security Risk Assessment should contain many lines describing a variety of different Information Security threats and risks. An Information Security Risk Assessment can be used as an input to the higher level Risk Assessment or conducted as part of the higher level Risk Assessment.

The Risk Assessment ProcessEstablish Risk CriteriaThe first step in conducting a Risk Assessment is defining the risk criteria. This refers to determining appropriate parameters so that risks can be weighed against each other and against the organization’s needs. The criteria should be unique to every organization, as every organization will face different types of risk and have a different tolerance for risk.

The criteria that must be established includes:

  • Likelihood
  • Potential impact
  • Risk level
  • Acceptable loss
  • Prioritization

An important aspect of the criteria is that they should be consistent between Risk Assessments. If the criteria change drastically every time a Risk Assessment is conducted, it will be very hard to compare the results of past and future Risk Assessments. Typically, the criteria will be established before the first Risk Assessment and will then be used for all future Risk Assessments with small updates only when necessary to adjust to changing conditions.

LikelihoodLikelihood is the chance that a threat event could occur, regardless of whether it will have any impact if it does occur.

Likelihood criteria should allow for a wide variety of threat events, including events that are extremely rare (e.g., An electrical fire in the datacenter) and others that are very frequent (e.g., A port scan of Internet-facing IP addresses).

The following table is an adaptation of an example likelihood scale from Appendix G of NIST SP 800-30r1:

Note the qualitative (An arbitrary scale from very low to very high) and semi-quantitative values (Arbitrary numbers from 0-10) that can be used to denote likelihood. Typically, an organization would choose only one (1) of these scales to use. The choice of scale is a matter of preference for the organization conducting the Risk Assessment. Semi-quantitative scales can be used to calculate risk in ways that qualitative scales cannot. This, along with true quantitative scales, is explained more in the Risk Level subsection below.

Using the expected number of occurrences per year as the likelihood scale provides an objective way to measure likelihood and should help maintain consistency between Risk Assessments. Compare this to a scale that uses terms like Very Frequent, Frequent, Infrequent, Very Infrequent, and Almost Never in lieu of the number of occurrences per year. These are subjective terms and if different personnel conduct Risk Assessments in the future, they may interpret any of these terms differently than their predecessors.

ImpactImpact is the potential consequence if a threat event occurs, regardless of how likely the event is to occur.

As with the likelihood scale, the impact scale should be designed to cover a wide variety of threat events where some may have almost no impact at all and others may be catastrophic to the organization.

The simplest way to define risk criteria is in terms of financial impact on the organization as shown in this example:

The thresholds shown in this example should be tailored to each organization. A loss of $100,000 may be negligible for a large enterprise but could be catastrophic for a small business. As with the Likelihood scale that is based on occurrences per year, using a financial loss scale in this manner provides objectivity and avoids varying interpretations of subjective terms like Catastrophic, Severe, Serious, Minor, and Negligible.

Many organizations struggle to use purely financial-based impact criteria because they are not prepared to quantify the financial cost from certain types of events. A more complex set of impact criteria can establish other types of impacts, such as privacy and reputation, that can be used in conjunction with financial impacts as shown in this example:

The organization would consider a threat event against all the types of impacts presented and select the highest impact. For example, a sustained denial-of-service (DoS) attack may be predicted to have the following impacts on the organization:

  • Financial: Low
  • Privacy: None
  • Reputation: High

In this case, the overall impact would be High, as the reputation impact is greater than the other types of impact.

As with financial impact, the criteria should be tailored to each organization. Sustained local news coverage could also be catastrophic for a small business that operates in a single location while it would have negligible impact on a large organization that operates internationally.

Organizations may choose to add other types of impacts that are specific to the types of activities they perform. For example, a chemical manufacturing plant may have Information Security systems that control heavy industrial machinery with potential life-safety and environmental implications. They may also want to directly consider the impact from production downtime. The following example impact criteria could be added to the examples provided above:

Ultimately, any of these additional types of impacts could be converted to a financial loss value if the effort was spent to understand the financial consequences (e.g., Regulatory cost of a privacy breach, the cost of every hour of production downtime, or the clean-up cost of a chemical spill), but this would require more detailed analysis during each assessment. Using alternative impacts are a convenient shortcut for completing the Risk Assessment process quickly with reasonable accuracy while still maintaining objective criteria, because reasonable parameters can be discussed and defined once.

Risk LevelRisk Levels combine the Likelihood and Impact values to produce an overall risk score.

Events with High Impact and Low Likelihood will usually be valued similarly to events with Low Impact and High Likelihood. This is to reflect how Low Impact but frequent events will have a cumulative effect on the organization over time comparable to a High Impact but rare event. Events with Low Impact and Low Likelihood will receive a Low risk level, while an event with a High Impact and High Likelihood will receive a High risk level.

Assignment of Risk Levels can be accomplished using a matrix with qualitative values as shown in this example from Appendix I of NIST SP 800-30r1:

By using this matrix, we can see that a hypothetical risk with a Moderate Likelihood and High Impact would have an overall Risk Value of Moderate.

An alternative method of determining risk is to use semi-quantitative Likelihood and Impact scores to calculate a Risk Score. For example, if we used the 0-10 semi-quantitative scales as shown in the Likelihood and Impact examples above, we could use the following formula to calculate a Risk Score in the range 0-20: (Likelihood Score) + (Impact Score) = (Risk Score).

Quantitative ApproachAll of the Likelihood, Impact, and risk criteria presented above use qualitative or semi-quantitative measurements. Organizations can also objectively measure risk using strictly quantitative scores for all these criteria. This approach is often more difficult, as most organizations are not prepared to determine expected financial loss for all event types.

An example of this approach would be to use the following criteria:

  • Likelihood: Number of expected occurrences per year
  • Impact: Expected financial loss per event
  • Risk: (Likelihood) x (Impact) = (Expected Annual Loss)

Using this example criteria, an event that is expected to occur once every two (2) years with a cost of $500,000 per event would have an expected annual loss (risk) of $250,000 (0.5 occurrences per year x $500,000 per occurrence).

Acceptable LossOrganizations are not expected to reduce every risk to zero (0). Instead, organizations must establish an acceptable loss threshold. Generally, risks below the threshold will not be addressed. These risks should still be tracked because changes in the threat landscape may increase the risk above the acceptable loss threshold in the future.

A very simple example of an acceptable loss threshold using qualitative criteria could be as follows:

  • All risks with a value of ‘Very Low’ are acceptable.
  • Any risk with a value of ‘Low’ is acceptable if treatment will cost more than $10,000 or require more than one (1) week of effort.

Acceptable loss thresholds for organizations using semi-quantitative Risk Assessment methodologies can be expressed numerically. For example:

  • All risks with a score less than two (2) are acceptable.
  • Any risk with a score between two (2) and 10 is acceptable if treatment will cost more than $10,000 or require more than one (1) week of effort.

Organizations using quantitative Risk Assessment criteria can directly use quantitative values as their acceptable loss thresholds. For example:

  • All risks with an expected annual loss of less than $10,000 are acceptable.
  • Any risk with an expected annual loss of $10,000-$100,000 is acceptable if treatment will cost more than $10,000 or require more than one (1) week of effort.

The examples shown above are a starting point. As with the other criteria, acceptable loss thresholds should be tailored to each organization’s unique needs.

PrioritizationThe risks that fall above the acceptable loss threshold will need to be prioritized for treatment, effectively determining which risks will be addressed first.

Simple prioritization criteria that focuses on addressing higher risks first could be defined as follows:

  • Risks will be prioritized according to their value, with higher value risks having a higher priority.
  • If risks have identical values, the risks with the higher Impacts will be prioritized over risks with lower Impacts.
  • If risks have identical Risk and Impact Values, the risks with higher Likelihood will be prioritized over risks with lower Likelihoods.

This example fails to consider the cost of addressing risks. While this approach is simple, it is potentially inefficient as it may be possible to have a larger impact on the organization’s overall risk by addressing many lower valued risks for the same cost as addressing a single high-value risk.

More complex prioritization criteria could factor in the cost of addressing risks, thereby prioritizing the remediation of risks with the highest return on investment regardless of the overall risk score. This works best when quantitative risk criteria are used as it can be difficult to calculate return on investment when using qualitative or semi-quantitative criteria.

Identify Threats to Information SecurityOnce the risk criteria have been established, it is time to begin the core Risk Assessment processes. This begins by identifying threats to the organization’s Information Security.

The Risk Assessment should consider anything that can affect:

  • Confidentiality: The ability to keep sensitive information out of unauthorized hands
  • Integrity: The ability to ensure information is reliably accurate
  • Availability: The ability for authorized persons to access the information when it is needed

When most people think of Information Security threats they consider hackers, malware, and other types of electronic attacks. An Information Security Risk Assessment should have a much broader scope than these common types of adversarial attacks. For example, while a hacker can affect the availability of information (e.g., Via a DoS attack), there are other non-hacker threats that can also affect the availability of information (e.g., A user accidentally deleting data, a hard drive failure, or a natural disaster destroying a datacenter).

Appendix D of NIST SP 800-30r1 provides four (4) categories of threats that are worth considering when identifying threats, which have been adapted in a simplified form here:

  • Adversarial: Individuals or groups attempting to harm the organization
  • Accidental: Mistakes made by authorized users
  • Structural: Equipment or software failures
  • Environmental: Natural and man-made disasters and infrastructure outages

Appendix E of NIST SP 800-30r1 also contains lists of various types of threat events that fall into these categories and can be used by organizations to create a list of threat events that concern them. This list should be considered a starting point. Organizations should also consider their own unique threats. Sources of inspiration for additional threat events that should be included in the Risk Assessment include:

  • Threats identified in past Risk Assessments
  • Past Information Security events and incidents at the organization
  • Information about past Information Security incidents or events at similar organizations as reported via ISACs and threat reports
  • Threat intelligence concerning ongoing attacks and emerging threats

Some potential threats may be so far-fetched for an organization that they can be excluded from the Risk Assessment entirely (e.g., An organization doing business exclusively in Kansas should not bother considering the threat of volcanic activity to their facilities), but threats that are even remotely possible should be included and considered. What may seem to be an extremely unlikely or low impact threat today may evolve in the future. Including these threats in the Risk Assessment will serve as a reminder to check on them in the future to determine if they are becoming more of a concern.

Asset-Based ApproachBoth the NIST SP 800-30r1 and ISO 27005:2022 Risk Assessment methodologies include an event-based approach to Risk Assessment as described above, but ISO 27005:2022 also offers a more sophisticated approach that explicitly considers the motivations of attackers and their impact on assets.

In this asset-based approach, the organization would start by identifying their information assets, business processes, and the infrastructure that supports the information and processes. Threat events and vulnerabilities that could affect these assets would be documented as well. ISO 27005:2022 §A.2.5.1 lists examples of threats and §A.2.5.2 lists example vulnerabilities.

The organization would then document likely threat sources, their motivations, and target objectives. This example threat source is adapted from the examples provided in ISO 27005:2022 §A.2.3:

  • Organized crime groups are a threat source that uses scams, ransomware, and botnets
  • They are motivated by a desire to acquire resources
  • Their objective is financial gain

Organizations would then combine the asset information with the threat source information to develop scenarios whereby a threat source could achieve their objectives by targeting relevant organizational assets. Example scenarios are provided in ISO 27005:2022 §A.2.6. These scenarios are used during the rest of the Risk Assessment in lieu of the threat events described above.

Applying Risk CriteriaOnce the threat events (or scenarios) have been identified, the organization must apply their risk criteria to each threat event.

To oversimplify this, the organization will:

  • Consider each threat against the Likelihood criteria to assign score
  • Consider each threat against the Impact criteria to assign a score
  • Consider the Likelihood and Impact scores of each threat against their risk criteria to assign a Risk Score
  • Consider the threat’s Risk Score against their risk acceptance criteria to determine whether to accept or treat the risk
  • Use the prioritization criteria to prioritize the treatment of any risk that does not meet the acceptance criteria

In reality, most organizations will need to consider how independent or codependent their business processes, systems, and facilities are to determine how many times the risk criteria must be evaluated for each threat. This is because a threat that poses a High risk on one (1) system may only pose a Low risk on another separate system, and it would be inefficient to consider the threat once, assign it a High Risk Score, and implement identical controls to treat that risk on both systems (It would also be dangerous to assign the threat a Low Risk Score and decline to treat it on both systems). Conversely, if systems are highly interconnected, it’s likely that a threat to any of the systems can affect another, and a threat that poses a High risk to one (1) system should be considered a High risk and addressed on all interconnected systems.

While the threats may be considered separately for certain systems, processes, or facilities, the resulting risks should be combined and prioritized together so that the more critical systems are addressed before the less critical systems.

Information on the Likelihood and Impact of threats can come from many sources. The organization may be able to use their own historical data related to Information Security events and incidents to determine the Likelihood and Impact of common threat events. Breach reports, information shared via ISACs, and other threat intelligence sources can also provide good Likelihood and Impact information. As with all external information, these inputs should be considered in the context of the organization and adjusted accordingly.

Vulnerabilities and/or controls can also be considered as part of a Risk Assessment and may adjust the Likelihood and Impact scores. This requires more effort during the Risk Assessment process but may produce more accurate results. Vulnerability scan and penetration test results are useful for identifying potential vulnerabilities that should be considered. Gap assessment and audit results are useful for identifying controls. Vulnerabilities typically increase Likelihood and Impact while controls decrease them. For example, maintaining a legacy application that can no longer be patched is a vulnerability that may increase the Likelihood of a malware threat gaining hold within the network, firewalling the legacy application so it has no Internet access and very limited internal network access may reduce the Likelihood of malware threat gaining a hold or spreading.

Throughout this process, the team conducting the Risk Assessment should consult with business and system owners to confirm that their understanding of threats, Likelihood, Impact, vulnerabilities, and controls are correct and verify that the resulting risk scores are reasonable. It is critical to the success of the Risk Assessment objectives that the business and system owners have faith in the process so that they will commit to following up on its recommendations.

If the Likelihood, Impact, or Risk Scores resulting from this process don’t make sense, the Risk Assessment team should reevaluate their process. This sometimes happens with a Risk Assessment process lacks objectivity. Adjusting risk criteria to establish objective measurements that do not rely on opinions can help alleviate this problem. Risk criteria may also need to be adjusted as the organization grows or changes (e.g., A financial loss threshold that was appropriate when the organization was a small startup may need to be raised if the organization develops into a mature enterprise with a much larger budget).

Determine Risk TreatmentThe final step in the Risk Assessment process is to determine how to treat the risks that have been identified. The ideal goal is to reduce all risks below the risk acceptance threshold, although this is not possible in many cases.

Typically, a risk can be treated in four (4) ways:

  • Avoid: Stop doing whatever created the risk (e.g., If a database of sensitive information poses a confidentiality risk due to the possibility of compromise, but the sensitive information is no longer needed, delete the information)
  • Modify: Implement controls that reduce the likelihood or impact of a risk (e.g., If sensitive data stored on laptops poses a confidentiality risk due to the possibility of theft or loss, encrypt the data on the laptops)
  • Share: Transfer the risk onto another organizations (e.g., Outsource processes or purchase cyber insurance)
  • Retain: Live with the risk (e.g., Accept that use of a vulnerable legacy application is unavoidable, and the risk cannot be further modified to an acceptable level or shared)

Avoiding risk is the best option as it is the only way to reliably eliminate a risk completely. Unfortunately, many activities that create risk are unavoidable for an organization to keep operating its business, so many risks will have to be treated in another manner.

Retaining risks is a last resort. Retaining a risk is similar to the concept of accepting a risk under the risk acceptance criteria, except this risk would be above the usual acceptance threshold. Risks are often retained when the cost of further reducing the risk exceeds the benefit that can be gained by treating the risk in another manner.

Modifying risks is the most common option chosen. The ISO 27002 framework provides an extensive list of security controls that can be used to modify risks and guidance on how to effectively implement those controls. Recommended controls to modify risks are usually fed into a planning and change control process to come up with detailed plans for implementing an effective control.

These risk treatment options are not exclusive to each other. In many cases, a risk may be modified to reduce as much risk as is practical using controls and, if it is still above the risk acceptance threshold, the remaining risk may be shared. If sharing the risk is not possible or the risk remains above the acceptance threshold, the remaining risk may be retained.

Business process and system owners should be very involved in the risk treatment decision process. They will likely be responsible for implementing the recommendations and must deal with the consequences of treating or declining to treat risks.

Do It All Over AgainRisk Assessments are not meant to be a one-time event. Threats and organizations change, and the Risk Assessment helps keep organizations aware of the effects of these changes. Typically, an organization-wide Risk Assessment will be updated annually.

Risk Assessments can also be more narrowly scoped. A Risk Assessment can be used when a new system is being deployed or an existing system is undergoing significant modification. These limited scope Risk Assessments help build good security practices into systems at the design phase when controls can be added more efficiently and with less disruption.

Ongoing Risk Assessments are a core part of a mature Information Security program.

Shameless PlugTrustedSec performs Risk Assessments based on the FAIR, ISO 27005, NIST SP 800-30, and other methodologies for our clients to support general Information Security maturity and compliance Risk Assessment requirements. TrustedSec’s Risk Assessments can incorporate the results of our own technical penetration testing activities to provide increased accuracy.

TrustedSec also helps our clients build their own risk management program to implement the concepts describe here and conduct their own in-house Risk Assessments.

The post Why Risk Assessments are Essential for Information Security Maturity appeared first on TrustedSec.

View Details

Having small XSS payloads or ways to shorten your payloads ensures that even the smallest unencoded output on a site can still lead to account compromise. A typical image tag with a onerror attribute takes up around 35 characters by itself.

<img src=1 onerror="alert('XSS')"> If you would like to prove you can steal credentials or change the source of a page, you may need to have a few different methods in your pocket to get a working payload if your input is limited to say, 50 characters. What can we do with those remaining 15-16 characters?

As a disclaimer, the domains used in this article are examples and not explicitly owned by me or TrustedSec. If you end up trying any of the payloads mentioned in this blog, it is advised you change the domain or IP used to an endpoint you are authorized to use.

Output encoding and sanitization are typical recommendations to prevent client-side vulnerabilities. As an additional security measure, user inputs have character limitations to prevent misuse. For example, it might be a zip code that only allows a 10-character maximum.

Another effective way to prevent XSS is by configuring a Content Security Policy (CSP). A correctly configured CSP can prevent external script execution and other content from retrieving data from external domains. A CSP can also prevent scripts from being executed for sources that have not exclusively been defined. However, due to the amount of third-party software in modern applications, most CSPs are not very strict and still allow an attacker the ability to perform XSS. A combination of these security configurations can prevent larger XSS payloads from executing.

Let’s consider the following: A site has a blog that you can enter comments into. To submit a comment, you are required to put your first name, last name, and email address, as well as what comment you would like to add. The site encodes any input you enter into the comments sections to prevent XSS.

Through testing the application, you find that the first and last name fields are vulnerable to XSS and have character limitations of no more than 50 characters. In testing, you find you can submit your last name with a common payload to display an alert.

Payload:

<img src=1 onerror=alert('XSS')> Figure 1 – XSS Payload in InputFigure 2 – XSS Alert in Displayed UsernameSo, we’re done. We got XSS, and we can move on. But we can’t make a request on behalf of an admin or change the page source with an alert. Let’s try to actually show some impact. Instead of implying what could be done with an XSS vulnerability, let’s create a proof-of-concept.

So first off, we can try to load some external scripts since we don’t have enough space to write out the few lines of JavaScript it might take to make a fetch request on behalf of the user. We can do this by adding a script tag.

```

``` Right off the bat, we run into an issue. This payload is too long for the user’s last name. So, what are our options? First, try to shorten the payload by getting rid of anything that’s not needed.

Something more like this:

```

``` We removed the quotes around the payload because similar to a command line function. As long as you don’t have any spaces in your URL, the browser will add them for you. Next, we changed our protocol from http to https. In this case, we can assume that we control the content on the server that we are setting as the source, and because we can control incoming requests, we can easily set up a URL redirect for any http request to https. In some cases, the browser may throw a mixed-content error due to the fact you are trying to load in content from an unencrypted source. In those cases, it may be required to leave the protocol as https.

Then, we removed the forward slashes from the URL scheme. We did this because if we have a valid protocol followed by a colon, most browsers will add the slashes before the domain path.

Now to shorten the domain and path of the URL. There are many ways to do this, and the above payload could be even shorter if we had control of a short domain name and removed any subdomains. Furthermore, because we control the external domain, we could make our site return a JavaScript content type and serve up our XSS payload on the home page of the domain to eliminate the path completely.

Making the homepage return a JavaScript file in Express.js can look something like this:

Figure 3 – Hosting a JavaScript File as the HomepageFigure 4 – Contents of test.jsWith all of these redactions, we end up with something like the following script tag with only 34 Characters.

```

``` Another thing that can be done is that modern browsers are very helpful and try to add any missing or incomplete tags. For example, if a label is meant to be bolded but the end tag is missing, the browser will add one.

So,

<label><b>Bold Me</label> Will be changed to:

<label><b>Bold Me></b><label> In some cases, we can use this to our advantage by not adding end tags to our payload but do this at your own risk. Depending where the XSS is located on the page, it may “eat” sections of the original page content. If no ending script tag is added, the browser will end up putting the content that is after our starting script tag into the body of our tag. This can make the page not render properly. In some cases, this may include only a few lines of HTML and other times it will contain the entire rest of the page. It depends on where the next script tag is located after our XSS. An example payload would look like this:

```