blib/lib/Parse/EventLog.pm

filter: Statementstmt 12.0% 17 / 141 Branchbran 0.0% 0 / 32 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 28.5% 4 / 14 Podpod 80.0% 8 / 10 totaltotal 14.3% 29 / 202 CC 19 SCAR 32.1
CC
19
Cov
10%
new
56.0
GetEventType
42.0
ShiftSIDAsString
20.0
CRAP 24.9
↑ Summary
1 package Parse::EventLog;
2  
3 1 require Exporter;
4 1 @ISA = qw(Exporter);
5 1 @EXPORT = qw(EVENT_INFORMATION EVENT_WARNING EVENT_ERROR EVENT_AUDIT_SUCCESS EVENT_AUDIT_FAILURE GetEventType);
6 1 $VERSION = '0.7';
7  
8 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use constant { EVENT_ERROR => 1, EVENT_WARNING => 2, EVENT_INFORMATION => 4,
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 EVENT_AUDIT_SUCCESS => 8, EVENT_AUDIT_FAILURE => 16 };
13  
14 # Internal function for retrieving UTF-16LE strings from the string table.
15 0 ▶sub ShiftUTF16LEAsString($) {
Subroutine ShiftUTF16LEAsString: not called CC=3 SCAR=24.8
Pod undocumented
16 0 my $str_ref = shift;
17 0 my $shifted = '';
18 0 my $two;
19 0 my $x = 0;
20 0 my $l = length($$str_ref);
21 0 ▶ while ($x < $l) {
Branch: 1 branch
BranchTrueFalseTotal
if ($x < $l) 0 0 0
22 0 $two = substr($$str_ref, $x, 2);
23 0 $x += 2;
24 0 ▶ if ($two eq "\0\0") {
Branch: 1 branch
BranchTrueFalseTotal
if ($two eq "\000\000") { } 0 0 0
25 0 $$str_ref = substr($$str_ref, $x);
26 0 return decode('UTF-16LE', $shifted);
27 } else {
28 0 $shifted .= $two;
29 }
30 }
31 }
32  
33 # Internal function. See 'struct _SID' in WTypes.h for the SID binary format.
34 0 ▶sub ShiftSIDAsString($) {
Subroutine ShiftSIDAsString: not called CC=4 SCAR=30.0
Pod undocumented
35 0 my $str_ref = shift;
36 0 my $x = 0; # Shift this much off of the input string.
37 0 my $revision; # SID version.
38 my $sub_authorities; # Sub authorities partly defines the size of the struct.
39 0 my @sid_id_auth; # SID Identifier Authority as an array of bytes
40 0 my @sub_auths; # An array of the actual sub authorities.
41 0 my $sid; # The final SID;
42  
43 0 ($revision, $sub_authorities, @sid_id_auth) = unpack('CCCCCCCC', $$str_ref);
44  
45 # Unpack all of the sub authorities into @sub_auths. 8 is the offset to the array.
46 0 @sub_auths = unpack("V[$sub_authorities]", substr($$str_ref, 8));
47  
48 # Length of the above header, plus the length of one ULONG per sub authority.
49 0 $x = 8 + ($sub_authorities * 4);
50  
51 0 $$str_ref = substr($$str_ref, $x);
52 0 $sid = "S-$revision-";
53  
54 # The following code is taken from the Windows Platform SDK regarding, in
55 # "Converting a Binary SID to String Format".
56 0 ▶ if (($sid_id_auth[0] != 0) || ($sid_id_auth[1] != 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sid_id_auth[0] != 0 or $sid_id_auth[1] != 0) { } 0 0 0
Condition0%0/3
$sid_id_auth[0] != 0 or $sid_id_auth[1] != 0
l!l&&r!l&&!r
000
MC/DC0%0/2
$sid_id_auth[0] != 0 or $sid_id_auth[1] != 0
$sid_id_auth[0] != 0 $sid_id_auth[1] != 0
Truth table0%0/3
A or B
A= $sid_id_auth[0] != 0B= $sid_id_auth[1] != 0
ABresult
1X1
011
000
57 0 $sid .= sprintf('0x%02hx%02hx%02hx%02hx%02hx%02hx',
58 $sid_id_auth[0],
59 $sid_id_auth[1],
60 $sid_id_auth[2],
61 $sid_id_auth[3],
62 $sid_id_auth[4],
63 $sid_id_auth[5]);
64 } else {
65 0 $sid .= sprintf('%lu',
66 $sid_id_auth[5] +
67 ($sid_id_auth[4] << 8) +
68 ($sid_id_auth[3] << 16) +
69 ($sid_id_auth[2] << 24) );
70 }
71  
72 0 ▶ if (@sub_auths) { $sid .= '-'; }
Branch: 1 branch
BranchTrueFalseTotal
if (@sub_auths) 0 0 0
73 0 local $" = '-';
74 0 $sid .= "@sub_auths";
75  
76 0 return $sid;
77 }
78  
79 =head1 NAME
80  
81 Parse::EventLog - Parse information from Windows Event Logs
82  
83 =head1 SYNOPSIS
84  
85 use Parse::EventLog;
86 my $elog =
87 Parse::EventLog->new("c:\\winnt\\system32\\config\\SysEvent.Evt");
88  
89 my %c = $elog->getNewestEvent();
90 # Do something interesting here.
91  
92 while (%c = $elog->getPreviousEvent()) {
93 print localtime($c{TimeGenerated}) .
94 ": $c{EventID} generated by $c{Source} on $c{Computer}.\n";
95 # Do a lot of interesting somethings here.
96 }
97  
98 =head1 DESCRIPTION
99  
100 Parse::EventLog is a module designed to allow parsing of binary Windows 2000+
101 Event Logs on any platform. For better Event Log parsing on Windows platforms,
102 see Win32::EventLog.
103  
104 When instansiated with the location of an Event Log file, you will be able to
105 walk through the existing events in chronological order from oldest to newest or
106 vice versa, as well as being able to extract the whole log to a hash table and
107 seek through however you wish.
108  
109 =head1 METHODS
110  
111 =head2 new
112  
113 my $eventlog =
114 Parse::EventLog->new("c:\\winnt\\system32\\config\\SysEvent.Evt");
115  
116 Parse::EventLog constructor, called with the location of the event log file to
117 open. Returns a Parse::EventLog object or dies on error. Stores the internal
118 record pointer at the newest event, so the next call to getPreviousEvent will
119 succeed but getNextEvent will fail (there are no newer events).
120  
121 =cut
122  
123 0 ▶sub new {
Subroutine new: not called CC=7 SCAR=40.3
Pod documented
124 0 my $class = shift;
125 0 my $filename = shift;
126 0 my %events;
127 my @events_by_time;
128 0 my @data;
129 0 my $RecordNumber;
130 0 my $TimeGenerated;
131 0 my $TimeWritten;
132 0 my $EventID;
133 0 my $EventType;
134 0 my $NumStrings;
135 0 my $EventCategory;
136 0 my $unused;
137  
138 {
139 0 local $/ = undef; #$INPUT_RECORD_SEPARATOR;
140 0 my $filedata;
141 my $file;
142 0 ▶ open($file, $filename) or die "Unable to open file $filename";
Branch: 1 branch
BranchTrueFalseTotal
open $file, $filename or die "Unable to open file $filename" 0 0 0
143 0 binmode($file);
144 0 $filedata = <$file>;
145 0 close $file;
146 # Split each record out by its header.
147 0 @data = split(/LfLe/, $filedata); #chr(0x4c).chr(0x66).chr(0x4c).chr(0x65)
148 }
149  
150 0 foreach my $rec (@data) {
151 0 ▶ if (length($rec) < 92) { # Magic number! Entry not long enough.
Branch: 1 branch
BranchTrueFalseTotal
if (length $rec < 92) 0 0 0
152 0 next;
153 }
154  
155 0 ($RecordNumber, $TimeGenerated, $TimeWritten,
156 $EventID, $unused, $unused, $EventType, $unused,
157 $NumStrings) = unpack('VVVvccccv', $rec); # More magic.
158  
159 0 ▶ if ($events{$RecordNumber}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($events{$RecordNumber}) 0 0 0
160 0 die "Error parsing event log, duplicate record number encountered ($RecordNumber)";
161 }
162  
163 0 my $sid_length = unpack('V', substr($rec, 32, 4));
164  
165 0 $events{$RecordNumber}{'TimeGenerated'} = $TimeGenerated;
166 0 $events{$RecordNumber}{'TimeWritten'} = $TimeWritten;
167 0 $events{$RecordNumber}{'RecordNumber'} = $RecordNumber;
168 0 $events{$RecordNumber}{'EventID'} = $EventID;
169 0 $events{$RecordNumber}{'EventType'} = $EventType;
170 0 $events{$RecordNumber}{'NumStrings'} = $NumStrings;
171  
172 # Strings are unicode and in a null terminated array. Split on double-null
173 # (a unicode null), and then remove nulls. Note: Replaced with wcstombs.
174  
175 # Here, 48 is the offset from the start to the string table.
176
177 0 my $stringtable = substr($rec, 48);
178  
179 # Strings are encoded as UTF-16LE, so decode them here. Remember, when we
180 # split above, we truncated the last null character, so re-add it here.
181 0 $events{$RecordNumber}{'Source'} = ShiftUTF16LEAsString(\$stringtable);
182 0 $events{$RecordNumber}{'Computer'} = ShiftUTF16LEAsString(\$stringtable);
183 0 ▶ if ($sid_length) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sid_length) { } 0 0 0
184 0 $events{$RecordNumber}{'SID'} = ShiftSIDAsString(\$stringtable);
185 } else {
186 0 $events{$RecordNumber}{'SID'} = undef;
187 }
188  
189  
190 0 ▶ for (my $msgct = 0; $msgct < $NumStrings; $msgct++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($msgct < $NumStrings) 0 0 0
191 0 push @{$events{$RecordNumber}{'Strings'}}, ShiftUTF16LEAsString(\$stringtable);
192 }
193 }
194  
195 # Sort the events and store it in an array with the oldest being at
196 # $events_by_time[0].
197 @events_by_time = sort {
198 0 $events{$b}{'TimeGenerated'} <=> $events{$a}{'TimeGenerated'}
199 } keys %events;
200  
201 0 my $self = {
202 'filename' => $filename,
203 'events' => \%events,
204 'events_by_time' => \@events_by_time,
205 'lastindex' => 0,
206 'totalevents' => scalar @events_by_time,
207 };
208 0 bless $self, $class;
209  
210 0 return( $self );
211 };
212  
213 =head2 getOldestEvent
214  
215 my %event = $eventlog->getOldestEvent();
216  
217 Returns a hash table containing the oldest entry in the event logand moves the
218 current event pointer to the oldest event.
219  
220 =cut
221  
222 #Remember, the list (@events_by_time) goes from newest -> oldest, so we want
223 # the last entry in that array. Extract the array into $ebt
224 0 ▶sub getOldestEvent {
Subroutine getOldestEvent: not called CC=1 SCAR=6.9
Pod documented
225 0 my $self = shift;
226 0 my @ebt = @{$self->{'events_by_time'}};
227 0 $self->{'lastindex'} = (scalar @ebt) - 1;
228 0 return %{$self->{'events'}->{$ebt[(scalar @ebt) - 1]}};
229 }
230  
231 =head2 getNewestEvent
232  
233 my %event = $eventlog->getNewestEvent();
234  
235 Returns a hash table containing the newest entry in the event log and moves the
236 current event pointer to the newest event.
237  
238 =cut
239  
240 # Get the newest entry in the list. Remember, the list goes from
241 # newest -> oldest, so we want the first entry. Code looks a lot like
242 # getOldestEvent.
243 0 ▶sub getNewestEvent {
Subroutine getNewestEvent: not called CC=1 SCAR=6.9
Pod documented
244 0 my $self = shift;
245 0 my @ebt = @{$self->{'events_by_time'}};
246 0 $self->{'lastindex'} = 0;
247 0 return %{$self->{'events'}->{$ebt[0]}};
248 }
249  
250 =head2 getNextEvent
251  
252 my %event = $eventlog->getNextEvent();
253  
254 Moves us forward in time, returning a hash table containing the next event in
255 the event log. Returns an empty array/hashtable if there are no more events to
256 get.
257  
258 =cut
259  
260 # Move forward in time.
261 0 ▶sub getNextEvent {
Subroutine getNextEvent: not called CC=2 SCAR=17.9
Pod documented
262 0 my $self = shift;
263 0 my @ebt = @{$self->{'events_by_time'}};
264 0 my $newindex = $self->{'lastindex'} - 1;
265 0 ▶ if ($newindex < 0) { return (); }
Branch: 1 branch
BranchTrueFalseTotal
if ($newindex < 0) 0 0 0
266 0 $self->{'lastindex'} = $newindex;
267 0 return %{$self->{'events'}->{$ebt[$newindex]}};
268 }
269  
270 =head2 getPreviousEvent
271  
272 my %event = $eventlog->getPreviousEvent();
273  
274 Moves us backward in time, returning a hash table containing the previous event
275 in the event log. Returns an empty array/hashtable if there are no more events
276 to get.
277  
278 =cut
279  
280 # Move backward in time.
281 0 ▶sub getPreviousEvent {
Subroutine getPreviousEvent: not called CC=2 SCAR=17.9
Pod documented
282 0 my $self = shift;
283 0 my @ebt = @{$self->{'events_by_time'}};
284 0 my $newindex = $self->{'lastindex'} + 1;
285 0 ▶ if ($newindex > (scalar @ebt) - 1) { return (); }
Branch: 1 branch
BranchTrueFalseTotal
if ($newindex > scalar(@ebt) - 1) 0 0 0
286 0 $self->{'lastindex'} = $newindex;
287 0 return %{$self->{'events'}->{$ebt[$newindex]}};
288 }
289  
290 =head2 getAll
291  
292 my %event = $eventlog->getAll();
293  
294 Returns a copy of the internal Event Log hash table for your own nefarious
295 pleasure. The main hash table is keyed by the internal RecordNumber (which is
296 unique to each entry in the file). The value of each of those keys is another
297 hash table containing the actual event (in the same format as is returned by
298 the other get*Event functions).
299  
300 =head3 Example
301  
302 my %c = $eventlog->getAll();
303 foreach my $a (keys %c) {
304 print 'Time: ' . localtime($c{$a}{'TimeGenerated'} . "\n";
305 print "Computer: $c{$a}{'Computer'}\n";
306 print "Source: $c{$a}{'Source'}\n";
307 print 'Type: ' . GetEventType($c{$a}{'EventType'}) . "\n";
308 print '-' x 10;
309 }
310  
311 =cut
312  
313 # Return a copy everything, might be slow.
314 0 ▶sub getAll {
Subroutine getAll: not called CC=1 SCAR=6.9
Pod documented
315 0 my $self = shift;
316 0 return %{$self->{'events'}};
317 }
318  
319 =head2 count
320  
321 my $count = $eventlog->count();
322  
323 Returns the number of entries loaded from the event log.
324  
325 =cut
326  
327 0 ▶sub count {
Subroutine count: not called CC=1 SCAR=6.9
Pod documented
328 0 my $self = shift;
329 0 return $self->{'totalevents'};
330 }
331  
332 =head1 FUNCTIONS
333  
334 =head2 GetEventType
335  
336 print 'Event type:' . GetEventType($c{'EventType'}) . "\n";
337  
338 Returns a string containing the type of event (Error, Warning, Information,
339 Audit Success, Audit Failure, or Unknown).
340  
341 GetEventType is exported by default.
342  
343 =cut
344  
345 0 ▶sub GetEventType {
Subroutine GetEventType: not called CC=6 SCAR=37.4
Pod documented
346 0 my $EventType = shift;
347
348 0 ▶ if ($EventType == EVENT_ERROR) {
Branch: 2 branches
BranchTrueFalseTotal
if ($EventType == 1) { } 0 0 0
elsif ($EventType == 2) { } 0 0 0
349 0 return 'Error';
350 } elsif ($EventType == EVENT_WARNING) {
351 0 return 'Warning';
352 0 ▶ }if ($EventType == EVENT_INFORMATION) {
Branch: 1 branch
BranchTrueFalseTotal
if ($EventType == 4) 0 0 0
353 0 return 'Information';
354 0 ▶ }if ($EventType == EVENT_AUDIT_SUCCESS) {
Branch: 1 branch
BranchTrueFalseTotal
if ($EventType == 8) 0 0 0
355 0 return 'Audit Success';
356 0 ▶ }if ($EventType == EVENT_AUDIT_FAILURE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($EventType == 16) { } 0 0 0
357 0 return 'Audit Failure';
358 } else {
359 0 return 'Unknown';
360 }
361 }
362  
363 =head1 CONSTANTS
364  
365 Several constants are exported by default. These constants are Event Type
366 definitions. They are as follows:
367  
368 =over 4
369  
370 =item * EVENT_ERROR (1)
371  
372 =item * EVENT_WARNING (2)
373  
374 =item * EVENT_INFORMATION (4)
375  
376 =item * EVENT_AUDIT_SUCCESS (8)
377  
378 =item * EVENT_AUDIT_FAILURE (16)
379  
380 =back
381  
382 =head1 RETURN VALUES
383  
384 On success, all of the get*Event functions return a hash of the current Event.
385 The hash itself has several keys made up of each of the values in the Event
386 itself. The following keys are defined (note the capitals):
387  
388 =head2 TimeGenerated
389  
390 The epoch time the event was generated, suitable for feeding to gmtime and localtime.
391  
392 =head2 TimeWritten
393  
394 The epoch time the event was written to the event log,
395 usually the same as TimeGenerated (give or take a second). Suitable for feeding
396 to gmtime and localtime.
397  
398 =head2 RecordNumber
399  
400 The record number of the event. This is assigned and due
401 to the binary nature of the file, and can not be expected to be consistant or
402 unique on subsequent parsings of the same file.
403  
404 =head2 EventID
405  
406 The event identification number, vendor and application
407 specific. Details can often be found in the Microsoft Knowledge Base.
408  
409 =head2 EventType
410  
411 The event type, vendor and application specific.
412  
413 =head2 Source
414  
415 Source of the event, usually the application or service name.
416  
417 =head2 Computer
418  
419 The name of the computer that generated the event.
420  
421 =head2 SID
422  
423 The SID associated with the entry. It is unknown whether this is the SID of the
424 source PC, the PC the log was stored on, the user, or something else.
425  
426 =head2 NumStrings
427  
428 Number of strings in the event.
429  
430 =head2 Strings
431  
432 An array reference to all (if any) of the strings included
433 with the event. Events work a lot like printf format strings, that is, there is
434 a fixed message with a variable part, such as:
435  
436 The %s service failed to start due to the following error:
437 The system cannot find the file specified.
438  
439 In this case, the Strings parameter would contain the name of the service
440 that would be placed in %s above to complete the event message.
441  
442 =head1 TO DO
443  
444 =over 4
445  
446 =item * Support for random access reads.
447  
448 =item * Parsing without loading the whole file into memory. By default, the files are only 64k, but it's possible to specify a much larger size.
449  
450 =item * Descriptions for general Microsoft Windows events.
451  
452 =item * Rename/alias getNextEvent and getPreviousEvent to getNewerEvent and getOlderEvent?
453  
454 =back
455  
456 =head1 KNOWN BUGS
457  
458 =over 4
459  
460 =item * Occasional spurious Strings are read from the Event Log. It seems the log
461 itself specifies they should be there, but there is only garbage data to be
462 read.
463  
464 =item * Incomplete parsing. Due to the mysterious nature of the Event Logs and
465 the lack of documentation on their format, there are several unknown fields in
466 the log. These fields are currently ignored. If anyone knows what these fields
467 are for, please let me know.
468  
469 =back
470  
471 =head1 CAVEATS
472  
473 While this module can extract general information on the events, most of the
474 error description is stored in system libraries specific to the Windows version
475 and patch level that created the log. At this time, Parse::EventLog does not
476 have a facility to extract that data.
477  
478 Assume the Event Viewer shows the following event description:
479  
480 The Print Spooler service was successfully sent a stop control.
481  
482 The data to build this description is stored in two locations. The first, a DLL
483 file associated with the Service Control Manager, contains the string:
484  
485 The %s service was successfully sent a %s control.
486  
487 The Event Log itself contains the strings:
488  
489 Print Spooler
490
491 and
492  
493 stop
494  
495 Unfortunately, at this time Parse::EventLog is not able to extract the string
496 data from files outside of the Event Log itself, only the strings contained
497 within it. At this time, I recommend either parsing the events on the Windows
498 server itself (via Win32::EventLog or a syslog plugin) or manually looking up
499 the data elsewhere.
500  
501 =head1 SEE ALSO
502  
503 L<Win32::EventLog>
504  
505 =head1 THANKS
506  
507 Thanks to Malik of www.whitehats.ca for the initial data structure format that this
508 module was based on. See: L<http://www.whitehats.ca/main/members/Malik/malik_eventlogs/malik_eventlogs.html>
509 for more details and his origional work.
510  
511 =head1 COPYRIGHT
512  
513 Copyright 2005-2006, John Eaglesham
514  
515 This module is free software. It may be used, redistributed and/or modified
516 under the same terms as Perl itself.
517  
518 =cut
519  
520 1 1;
↑ Summary