protected bool ReadLocal(string fileName) { L.Log(LogType.FILE, LogLevel.INFORM, "EventLogFileAuditRecorder In ReadLocal -- Started."); if (!callable.WaitOne(0)) { L.Log(LogType.FILE, LogLevel.INFORM, "EventLogFileAuditRecorder In ReadLocal -- CALLED MULTIPLE TIMES STILL IN USE"); callable.WaitOne(); try { throw new Exception("Parse already been processed by another thread while this call has made"); } finally { callable.ReleaseMutex(); } } try { L.Log(LogType.FILE, LogLevel.INFORM, "EventLogFileAuditRecorder In ReadLocal -- Started with lastfile: " + lastFile); var eventLogLocation = fileName; var query = last_recordnum > 0 ? "*[System/EventRecordID > " + last_recordnum + "]" : null; var handle = IntPtr.Zero; var events = new IntPtr[] { IntPtr.Zero }; var hRenderContext = IntPtr.Zero; var pRenderedValues = IntPtr.Zero; var hRenderContextEvtData = IntPtr.Zero; var metaDict = new Dictionary<string, IntPtr>(); var dwBufferUsed = 0; var dwPropertyCount = 0; var dwBufferSize = 0; var status = UnsafeNativeMethods.ERROR_SUCCESS; var session = IntPtr.Zero; try { var info = user == null ? null : user.Split('\\'); if (info != null && info.Length >= 2) { domain = string.IsNullOrEmpty(info[0]) ? null : info[0]; ip = info.Length == 2 ? remoteHost : (string.IsNullOrEmpty(info[1]) ? null : info[1]); domainUser = string.IsNullOrEmpty(info[info.Length - 1]) ? null : info[info.Length - 1]; if (!string.IsNullOrEmpty(domain) && !string.IsNullOrEmpty(domainUser)) { L.Log(LogType.FILE, LogLevel.DEBUG, "EventLogFileAuditRecorder In ReadLocal -- Remote Logger: " + user); var login = new UnsafeNativeMethods.EvtRpcLogin() { Domain = domain, User = domainUser, Password = CoTaskMemUnicodeSafeHandle.Zero, Server = ip }; var secureString = new SecureString(); if (!string.IsNullOrEmpty(password)) { foreach (var ch in password) { secureString.AppendChar(ch); } } login.Password.SetMemory(Marshal.SecureStringToCoTaskMemUnicode(secureString)); session = UnsafeNativeMethods.EvtOpenSession(UnsafeNativeMethods.EvtLoginClass.EvtRpcLogin, ref login, 0, 0); L.Log(LogType.FILE, LogLevel.DEBUG, "EventLogFileAuditRecorder In ReadLocal -- UnsafeNativeMethods.EvtQueryFlags.EvtQueryChannelPath: " + UnsafeNativeMethods.EvtQueryFlags.EvtQueryChannelPath); } } /* flags = (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryFilePath; L.Log(LogType.FILE, LogLevel.DEBUG, "EventLogFileAuditRecorder In ReadLocal -- UnsafeNativeMethods.EvtQueryFlags.EvtQueryFilePath: " + UnsafeNativeMethods.EvtQueryFlags.EvtQueryFilePath); } else { */ int flags; if (location.Contains("\\")) { flags = (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryFilePath; L.Log(LogType.FILE, LogLevel.DEBUG, "EventLogFileAuditRecorder In ReadLocal --EvtQueryFilePath"); } else { flags = (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryChannelPath; L.Log(LogType.FILE, LogLevel.DEBUG, "EventLogFileAuditRecorder In ReadLocal --EvtQueryChannelPath"); } L.Log(LogType.FILE, LogLevel.DEBUG, "EventLogFileAuditRecorder In ReadLocal -- " + session + " - " + eventLogLocation + " - " + query + " - " + flags); handle = UnsafeNativeMethods.EvtQuery(session, eventLogLocation, query, flags); if (handle == IntPtr.Zero) { L.Log(LogType.FILE, LogLevel.ERROR, "EventLogFileAuditRecorder In ReadLocal -- Error Opening Event File: " + Marshal.GetLastWin32Error()); return false; } hRenderContext = UnsafeNativeMethods.EvtCreateRenderContext(0, null, UnsafeNativeMethods .EvtRenderContextFlags .EvtRenderContextSystem); if (hRenderContext == IntPtr.Zero) { L.Log(LogType.FILE, LogLevel.ERROR, "EventLogFileAuditRecorder In ReadLocal -- Error Creating Render Context Failed: " + Marshal.GetLastWin32Error() + ")"); return false; } var buffer = new StringBuilder(); var lineBuffer = new StringBuilder(); var tmpBuffer = new StringBuilder(); var domainBuffer = new StringBuilder(); var usernameBuffer = new StringBuilder(); var returned = 0; var rec = new CustomBase.Rec(); var audit = new AuditInfo(); isFileFinished = false; try { while (UnsafeNativeMethods.EvtNext(handle, 1, events, int.MaxValue, 0, ref returned)) { PrintT(++total); try { using (Benchmark("GetRender")) { if (!GetRenderValues(hRenderContext, events[0], UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues, ref dwBufferSize, ref pRenderedValues, ref dwBufferUsed, ref dwPropertyCount, ref status)) { L.Log(LogType.FILE, LogLevel.ERROR, "EventLogFileAuditRecorder In ReadLocal -- Error Getting Render Event Values Failed: " + status + ")"); continue; } } string description; using (Benchmark("GetFields")) { string meta; using (Benchmark("GetFields P1")) { meta = Marshal.PtrToStringAuto( ((UnsafeNativeMethods.EvtVariant) (Marshal.PtrToStructure(pRenderedValues, typeof(UnsafeNativeMethods.EvtVariant)))) .StringVal); if (meta == null) { L.Log(LogType.FILE, LogLevel.INFORM, "EventLogFileAuditRecorder In ReadLocal -- Event has no meta data. Skipping"); continue; } } using (Benchmark("GetFields P2")) { rec.EventId = ((UnsafeNativeMethods.EvtVariant) Marshal.PtrToStructure( new IntPtr((Int32)pRenderedValues + ((int) UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemEventID) * Marshal.SizeOf(typeof(UnsafeNativeMethods.EvtVariant))), typeof(UnsafeNativeMethods.EvtVariant))).UShort; L.Log(LogType.FILE, LogLevel.DEBUG, "EventId: " + rec.EventId); } IntPtr metaPtr; using (Benchmark("GetFields P3")) { if (!metaDict.TryGetValue(meta, out metaPtr)) { metaPtr = UnsafeNativeMethods.EvtOpenPublisherMetadata(session, meta, null, LangId, 0); if (metaPtr != IntPtr.Zero) metaDict[meta] = metaPtr; } } using (Benchmark("GetFields P4")) { if (!GetMessageString(metaPtr, events[0], UnsafeNativeMethods.EvtFormatMessageFlags .EvtFormatMessageEvent, ref buffer, out dwBufferUsed, ref status)) { L.Log(LogType.FILE, LogLevel.ERROR, "Get Description failed:" + status); continue; } } using (Benchmark("GetFields P5")) { description = buffer.ToString(); buffer.Remove(0, buffer.Length); //WriteLine(description); //continue; rec.Recordnum = (int) ((UnsafeNativeMethods.EvtVariant) Marshal.PtrToStructure( new IntPtr((Int32)pRenderedValues + ((int) UnsafeNativeMethods.EvtSystemPropertyId .EvtSystemEventRecordId) * Marshal.SizeOf( typeof(UnsafeNativeMethods.EvtVariant))), typeof(UnsafeNativeMethods.EvtVariant))).ULong; last_recordnum = (long)rec.Recordnum; rec.ComputerName = Marshal.PtrToStringAuto( ((UnsafeNativeMethods.EvtVariant) (Marshal.PtrToStructure( new IntPtr((Int32)pRenderedValues + ((int) UnsafeNativeMethods.EvtSystemPropertyId .EvtSystemComputer) * Marshal.SizeOf(typeof(UnsafeNativeMethods.EvtVariant))), typeof(UnsafeNativeMethods.EvtVariant)))) .StringVal); } using (Benchmark("GetFields P6")) { if (!GetMessageString(metaPtr, events[0], UnsafeNativeMethods.EvtFormatMessageFlags .EvtFormatMessageTask, ref buffer, out dwBufferUsed, ref status)) { buffer.Remove(0, buffer.Length); } rec.EventType = buffer.ToString(); if (!GetMessageString(metaPtr, events[0], UnsafeNativeMethods.EvtFormatMessageFlags .EvtFormatMessageLevel, ref buffer, out dwBufferUsed, ref status)) { buffer.Remove(0, buffer.Length); } rec.EventCategory = buffer.ToString(); ulong timeCreated = ((UnsafeNativeMethods.EvtVariant) Marshal.PtrToStructure( new IntPtr((Int32)pRenderedValues + ((int) UnsafeNativeMethods.EvtSystemPropertyId .EvtSystemTimeCreated) * Marshal.SizeOf(typeof(UnsafeNativeMethods.EvtVariant))), typeof(UnsafeNativeMethods.EvtVariant))).FileTime; rec.Datetime = DateTime.FromFileTime((long)timeCreated) .ToString("yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture); rec.LogName = Marshal.PtrToStringAuto( ((UnsafeNativeMethods.EvtVariant) (Marshal.PtrToStructure( new IntPtr((Int32)pRenderedValues + ((int) UnsafeNativeMethods.EvtSystemPropertyId .EvtSystemChannel) * Marshal.SizeOf(typeof(UnsafeNativeMethods.EvtVariant))), typeof(UnsafeNativeMethods.EvtVariant)))) .StringVal); rec.Description = description; } } var sentItems = 0; using (Benchmark("ParseDescriptionForAudit")) { if ( !ParseDescriptionForAudit(audit, description, buffer, domainBuffer, usernameBuffer)) continue; } using (Benchmark("ParseAuditOperations2")) { ParseAuditOperations2(ref rec, audit, buffer, domainBuffer, usernameBuffer, ref sentItems); if (sentItems > 0) continue; if (audit.Reasons.Count == 0 && audit.OriginalRights.Count == 0 && audit.NewRights.Count == 0) continue; } rec.Description = description; rec.CustomStr2 = audit.ObjectType; rec.CustomStr3 = audit.ObjectName; rec.CustomStr4 = audit.Sid; rec.CustomStr5 = audit.Username; rec.CustomStr6 = audit.Process; rec.CustomInt6 = audit.ProcessId; rec.CustomStr7 = audit.AccessMask; using (Benchmark("ParseAuditOperations2")) { if (audit.OriginalRights.Count > 0 && audit.NewRights.Count > 0) SendAccessRightChange(ref rec, audit); //else // SendAudit(ref rec, audit); } } finally { UnsafeNativeMethods.EvtClose(events[0]); events[0] = IntPtr.Zero; } } } finally { foreach (var item in benchmark) { item.Value.Stop(); } //BenchStat(Console.Out); try { var customServiceBase = GetInstanceService("Security Manager Remote Recorder"); L.Log(LogType.FILE, LogLevel.DEBUG, " EventLogFileAuditRecorder In ReadLocal -->> Setting Registry."); customServiceBase.SetReg(Id, last_recordnum.ToString(CultureInfo.InvariantCulture), "-", lastFile, "", LastRecordDate); L.Log(LogType.FILE, LogLevel.DEBUG, " EventLogFileAuditRecorder In ReadLocal -->> Registry Set."); } catch (Exception exception) { L.Log(LogType.FILE, LogLevel.ERROR, " EventLogFileAuditRecorder In ReadLocal -->> Setting Registry Error." + exception.Message); } } isFileFinished = true; return true; } finally { CleanupEvtHandle(handle); CleanupEvtHandle(events[0]); CleanupEvtHandle(hRenderContext); CleanupEvtHandle(hRenderContextEvtData); CleanupEvtHandle(metaDict); } } catch (EventLogNotFoundException e) { L.Log(LogType.FILE, LogLevel.ERROR, "EVTX Parser in ReadLocal ERROR." + e.Message); } finally { callable.ReleaseMutex(); } return false; }
private string LocalTranslation(string kernelRoot, string restOfPath) { string path; if (!localTranslations.TryGetValue(kernelRoot, out path)) { var trans = new Dictionary<string, string>(); foreach (var drive in DriveInfo.GetDrives()) { var i = drive.Name.Length; while (--i >= 0 && drive.Name[i] == Path.DirectorySeparatorChar) { } var driveName = drive.Name.Substring(0, ++i); var kernelPath = Kernel32.QueryDosDevice(driveName); if (string.IsNullOrEmpty(kernelPath)) return kernelRoot + restOfPath; trans[kernelPath] = driveName; } localTranslations = trans; if (!localTranslations.TryGetValue(kernelRoot, out path)) return kernelRoot + restOfPath; } return path + restOfPath; }