Agent/Integrity/Registry.pm untested

filter: Statementstmt 0.0% 0 / 444 Branchbran 0.0% 0 / 112 Conditioncond 0.0% 0 / 84 MC/DCmcdc 0.0% 0 / 51 Subroutinesub 0.0% 0 / 32 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 740 CC 57 SCAR 51.7
CC
57
Cov
0%
_compare
600.0
_diff
42.0
check
42.0
CRAP 175.6
1 #######################################################################
2 # Created on: Dec 03, 2006
3 # Package: HoneyClient::Agent::Integrity::Registry
4 # File: Registry.pm
5 # Description: Performs static checks of the Windows OS registry.
6 #
7 # CVS: $Id: Registry.pm 773 2007-07-26 19:04:55Z kindlund $
8 #
9 # @author kindlund, xkovah
10 #
11 # Copyright (C) 1998 Memorial University of Newfoundland.
12 # Copyright (C) 2007 The MITRE Corporation. All rights reserved.
13 #
14 # This program is free software; you can redistribute it and/or
15 # modify it under the terms of the GNU General Public License
16 # as published by the Free Software Foundation, using version 2
17 # of the License.
18 #
19 # This program is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 # GNU General Public License for more details.
23 #
24 # You should have received a copy of the GNU General Public License
25 # along with this program; if not, write to the Free Software
26 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
27 # 02110-1301, USA.
28 #
29 #######################################################################
30  
31 =pod
32  
33 =head1 NAME
34  
35 HoneyClient::Agent::Integrity::Registry - Perl extension to perform
36 static checks of the Windows OS registry.
37  
38 =head1 VERSION
39  
40 This documentation refers to HoneyClient::Agent::Integrity::Registry version 0.98.
41  
42 =head1 SYNOPSIS
43  
44 use HoneyClient::Agent::Integrity::Registry;
45 use Data::Dumper;
46  
47 # Create the registry object. Upon creation, the object
48 # will be initialized, by collecting a baseline of the registry.
49 my $registry = HoneyClient::Agent::Integrity::Registry->new();
50  
51 # ... Some time elapses ...
52  
53 # Check the registry, for any changes.
54 my $changes = $registry->check();
55  
56 if (!defined($changes)) {
57 print "No registry changes have occurred.\n";
58 } else {
59 print "Registry has changed:\n";
60 print Dumper($changes);
61 }
62  
63 # $changes refers to an array of hashtable references, where
64 # each hashtable has the following format:
65 #
66 # $changes = [ {
67 # # The registry directory name.
68 # 'key_name' => 'HKEY_LOCAL_MACHINE\Software...',
69 #
70 # # Indicates if the registry directory was deleted (0),
71 # # added (1), or changed (2).
72 # 'status' => 0 | 1 | 2,
73 #
74 # # An array containing the list of entries within the
75 # # registry directory that have been deleted, added, or
76 # # changed. If this array is empty, then the corresponding
77 # # registry directory in the original and new hives contained
78 # # no entries.
79 # 'entries' => [ {
80 # 'name' => "\"string\"", # A (potentially) quoted string;
81 # # "@" for default
82 # 'new_value' => "string", # New string; maybe undef, if deleted
83 # 'old_value' => "string", # Old string; maybe undef, if added
84 # }, ],
85 # }, ]
86  
87 =head1 DESCRIPTION
88  
89 This library allows the Integrity module to easily baseline and check
90 the Windows OS registry hives for any changes that may occur, while
91 instrumenting a target application.
92  
93 This library uses modified code from the 'regutils' library by
94 John Rochester and Michael Rendell.
95 See L<http://www.cs.mun.ca/~michael/regutils/> for more information.
96  
97 =cut
98  
99 package HoneyClient::Agent::Integrity::Registry;
100  
101 use strict;
102 use warnings;
103 use Carp ();
104  
105 # Include Global Configuration Processing Library
106 use HoneyClient::Util::Config qw(getVar);
107  
108 # Include Registry Parsing Library
109 use HoneyClient::Agent::Integrity::Registry::Parser;
110  
111 # Use Dumper Library
112 use Data::Dumper;
113  
114 # Use Storable Library
115 use Storable qw(dclone);
116  
117 # Include Logging Library
118 use Log::Log4perl qw(:easy);
119  
120 # Include File IO Libraries.
121 use IO::Handle;
122 use IO::File;
123 use Fcntl qw(:seek);
124  
125 # Include Temporary File Libraries.
126 use File::Temp qw(tmpnam unlink0);
127  
128 # Include Cygwin Path Conversion Library.
129 use Filesys::CygwinPaths qw(:all);
130  
131 # Use Binary Search Library.
132 use Search::Binary;
133  
134 #######################################################################
135 # Module Initialization #
136 #######################################################################
137  
138 BEGIN {
139 # Defines which functions can be called externally.
140 require Exporter;
141 our (@ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS, $VERSION);
142  
143 # Set our package version.
144 $VERSION = 0.98;
145  
146 @ISA = qw(Exporter);
147  
148 # Symbols to export automatically
149 @EXPORT = qw( );
150  
151 # Items to export into callers namespace by default. Note: do not export
152 # names by default without a very good reason. Use EXPORT_OK instead.
153 # Do not simply export all your public functions/methods/constants.
154  
155 # This allows declaration use HoneyClient::Agent::Integrity::Registry ':all';
156 # If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
157 # will save memory.
158  
159 %EXPORT_TAGS = (
160 'all' => [ qw( ) ],
161 );
162  
163 # Symbols to autoexport (when qw(:all) tag is used)
164 @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
165  
166 $SIG{PIPE} = 'IGNORE'; # Do not exit on broken pipes.
167 }
168 our (@EXPORT_OK, $VERSION);
169  
170 =pod
171  
172 =begin testing
173  
174 # Make sure Log::Log4perl loads
175 BEGIN { use_ok('Log::Log4perl', qw(:nowarn))
176 or diag("Can't load Log::Log4perl package. Check to make sure the package library is correctly listed within the path.");
177
178 # Suppress all logging messages, since we need clean output for unit testing.
179 Log::Log4perl->init({
180 "log4perl.rootLogger" => "DEBUG, Buffer",
181 "log4perl.appender.Buffer" => "Log::Log4perl::Appender::TestBuffer",
182 "log4perl.appender.Buffer.min_level" => "fatal",
183 "log4perl.appender.Buffer.layout" => "Log::Log4perl::Layout::PatternLayout",
184 "log4perl.appender.Buffer.layout.ConversionPattern" => "%d{yyyy-MM-dd HH:mm:ss} %5p [%M] (%F:%L) - %m%n",
185 });
186 }
187 require_ok('Log::Log4perl');
188 use Log::Log4perl qw(:easy);
189  
190 # Make sure the module loads properly, with the exportable
191 # functions shared.
192 BEGIN { use_ok('HoneyClient::Util::Config', qw(getVar setVar))
193 or diag("Can't load HoneyClient::Util::Config package. Check to make sure the package library is correctly listed within the path."); }
194 require_ok('HoneyClient::Util::Config');
195 can_ok('HoneyClient::Util::Config', 'getVar');
196 can_ok('HoneyClient::Util::Config', 'setVar');
197 use HoneyClient::Util::Config qw(getVar setVar);
198  
199 # Suppress all logging messages, since we need clean output for unit testing.
200 Log::Log4perl->init({
201 "log4perl.rootLogger" => "DEBUG, Buffer",
202 "log4perl.appender.Buffer" => "Log::Log4perl::Appender::TestBuffer",
203 "log4perl.appender.Buffer.min_level" => "fatal",
204 "log4perl.appender.Buffer.layout" => "Log::Log4perl::Layout::PatternLayout",
205 "log4perl.appender.Buffer.layout.ConversionPattern" => "%d{yyyy-MM-dd HH:mm:ss} %5p [%M] (%F:%L) - %m%n",
206 });
207  
208 # Make sure Data::Dumper loads
209 BEGIN { use_ok('Data::Dumper')
210 or diag("Can't load Data::Dumper package. Check to make sure the package library is correctly listed within the path."); }
211 require_ok('Data::Dumper');
212 use Data::Dumper;
213  
214 # Make sure Storable loads
215 BEGIN { use_ok('Storable', qw(dclone))
216 or diag("Can't load Storable package. Check to make sure the package library is correctly listed within the path."); }
217 require_ok('Storable');
218 can_ok('Storable', 'dclone');
219 use Storable qw(dclone);
220  
221 # Make sure IO::Handle loads
222 BEGIN { use_ok('IO::Handle')
223 or diag("Can't load IO::Handle package. Check to make sure the package library is correctly listed within the path."); }
224 require_ok('IO::Handle');
225 use IO::Handle;
226  
227 # Make sure IO::File loads
228 BEGIN { use_ok('IO::File')
229 or diag("Can't load IO::File package. Check to make sure the package library is correctly listed within the path."); }
230 require_ok('IO::File');
231 use IO::File;
232  
233 # Make sure Fcntl loads
234 BEGIN { use_ok('Fcntl')
235 or diag("Can't load Fcntl package. Check to make sure the package library is correctly listed within the path."); }
236 require_ok('Fcntl');
237 use Fcntl qw(:seek);
238  
239 # Make sure File::Temp loads
240 BEGIN { use_ok('File::Temp')
241 or diag("Can't load File::Temp package. Check to make sure the package library is correctly listed within the path."); }
242 require_ok('File::Temp');
243 can_ok('File::Temp', 'tmpnam');
244 can_ok('File::Temp', 'unlink0');
245 use File::Temp qw(tmpnam unlink0);
246  
247 # Make sure Filesys::CygwinPaths loads
248 BEGIN { use_ok('Filesys::CygwinPaths')
249 or diag("Can't load Filesys::CygwinPaths package. Check to make sure the package library is correctly listed within the path."); }
250 require_ok('Filesys::CygwinPaths');
251 use Filesys::CygwinPaths qw(:all);
252  
253 # Make sure Search::Binary loads
254 BEGIN { use_ok('Search::Binary')
255 or diag("Can't load Search::Binary package. Check to make sure the package library is correctly listed within the path."); }
256 require_ok('Search::Binary');
257 can_ok('Search::Binary', 'binary_search');
258 use Search::Binary;
259  
260 # Make sure HoneyClient::Agent::Integrity::Registry::Parser loads
261 BEGIN { use_ok('HoneyClient::Agent::Integrity::Registry::Parser')
262 or diag("Can't load HoneyClient::Agent::Integrity::Registry::Parser package. Check to make sure the package library is correctly listed within the path."); }
263 require_ok('HoneyClient::Agent::Integrity::Registry::Parser');
264 use HoneyClient::Agent::Integrity::Registry::Parser;
265  
266 # Make sure HoneyClient::Agent::Integrity::Registry loads
267 BEGIN { use_ok('HoneyClient::Agent::Integrity::Registry')
268 or diag("Can't load HoneyClient::Agent::Integrity::Registry package. Check to make sure the package library is correctly listed within the path."); }
269 require_ok('HoneyClient::Agent::Integrity::Registry');
270 use HoneyClient::Agent::Integrity::Registry;
271  
272 # Make sure File::Basename loads.
273 BEGIN { use_ok('File::Basename', qw(dirname basename fileparse)) or diag("Can't load File::Basename package. Check to make sure the package library is correctly listed within the path."); }
274 require_ok('File::Basename');
275 can_ok('File::Basename', 'dirname');
276 can_ok('File::Basename', 'basename');
277 can_ok('File::Basename', 'fileparse');
278 use File::Basename qw(dirname basename fileparse);
279  
280 =end testing
281  
282 =cut
283  
284 #######################################################################
285 # Global Configuration Variables
286 #######################################################################
287  
288 # Registry Status Identifiers
289 our $STATUS_DELETED = 0;
290 our $STATUS_ADDED = 1;
291 our $STATUS_MODIFIED = 2;
292  
293 # The global logging object.
294 our $LOG = get_logger();
295  
296 # Make Dumper format more terse.
297 $Data::Dumper::Terse = 1;
298 $Data::Dumper::Indent = 0;
299  
300 =pod
301  
302 =head1 DEFAULT PARAMETER LIST
303  
304 When a Registry B<$object> is instantiated using the B<new()> function,
305 the following parameters are supplied default values. Each value
306 can be overridden by specifying the new (key => value) pair into the
307 B<new()> function, as arguments.
308  
309 =head2 hives_to_check
310  
311 =over 4
312  
313 This parameter indicates the default array of registry hive names
314 to monitor for changes.
315  
316 =back
317  
318 =head2 key_dirnames_to_ignore
319  
320 =over 4
321  
322 This parameter indicates the default array of regular expressions
323 that each registry directory will be checked against. Any matching
324 key directory names will be ignored and any subsequent additions,
325 deletions, or changes to all content in these matches will also
326 be ignored.
327  
328 Each $entry will be used via the syntax /$entry/. Thus,
329 it is recommended to specify the ^ prefix and $ suffix, when
330 possible.
331  
332 A single backslash (\) must be represented using triple
333 backslashes (\\\) and each $entry must not end with any
334 backslash character.
335  
336 =back
337  
338 =head2 bypass_baseline
339  
340 =over 4
341  
342 When set to 1, the object will forgo any type of initial baselining
343 process, upon initialization. Otherwise, baselining will occur
344 as normal, upon initialization.
345  
346 =back
347  
348 =cut
349  
350 my %PARAMS = (
351  
352 # An array, specifying which registry hives to
353 # analyze.
354 hives_to_check => getVar(name => 'hives_to_check')->{name},
355  
356 # An array of regular expressions that each registry directory
357 # will be checked against. Any matching key directory names will
358 # be ignored and any subsequent additions, deletions, or changes
359 # to all content in these matches will also be ignored.
360 #
361 # Each $entry will be used via the syntax /$entry/. Thus,
362 # it is recommended to specify the ^ prefix and $ suffix, when
363 # possible.
364 #
365 # A single backslash (\) must be represented using triple
366 # backslashes (\\\) and each $entry must not end with any
367 # backslash character.
368 key_dirnames_to_ignore => getVar(name => 'exclude_list')->{regex},
369  
370 # When set to 1, the object will forgo any type of initial baselining
371 # process, upon initialization. Otherwise, baselining will occur
372 # as normal, upon initialization.
373 bypass_baseline => 0,
374  
375 # Baseline File Collection
376 # A hashtable of file parsers, one parser per hive name.
377 # (For internal use only.)
378 _baseline_parsers => { },
379  
380 # Checkpoint File Collection
381 # A hashtable of file parsers, one parser per hive name.
382 # (For internal use only.)
383 _checkpoint_parsers => { },
384  
385 # A hashtable of current key info objects, where the hash key is the
386 # file parser and the hash value is the info object.
387 # (For internal use only.)
388 _currentKeys => { },
389  
390 # A hashtable of counters, where each counter keeps track of
391 # which entry was last read in from the current key. The hash key
392 # is the file parser, and the hash value is the entry counter.
393 _currentEntryIndex => { },
394  
395 # A helper variable, used to keep track of the last search index,
396 # used by the _search() function.
397 _last_search_index => undef,
398  
399 # A helper variable, used to set the array of known line numbers,
400 # where each array entry is a line number, which separates a different
401 # group block.
402 _group_index_linenums => [ ],
403 );
404  
405 #######################################################################
406 # Private Methods Implemented #
407 #######################################################################
408  
409 # TODO: Move down to public area, document, and update unit tests.
410 # Base destructor function.
411 sub destroy {
412 # Extract arguments.
413 my $self = shift;
414  
415 # Sanity check: Make sure we've been fed an object.
416 unless (ref($self)) {
417 $LOG->error("Error: Function must be called in reference to a " .
418 __PACKAGE__ . "->new() object!");
419 Carp::croak "Error: Function must be called in reference to a " .
420 __PACKAGE__ . "->new() object!\n";
421 }
422  
423 # Delete any temporary files created by the baseline
424 # and checkpoint parsers.
425 $self->_cleanupParsers($self->{_baseline_parsers});
426 $self->_cleanupParsers($self->{_checkpoint_parsers});
427 }
428  
429 # Helper function, designed to cleanup temporary files created
430 # by specified parsers.
431 #
432 # Inputs: HoneyClient::Agent::Integrity::Registry object,
433 # the hashtable collection of specified parsers
434 #
435 # Outputs: None.
436 sub _cleanupParsers {
437 # Extract arguments.
438 my ($self, $parser_collection) = @_;
439  
440 # Delete any temporary files created.
441 my $parser = undef;
442 my $fname = undef;
443 foreach my $hive (@{$self->{hives_to_check}}) {
444 $parser = $parser_collection->{$hive};
445 if (defined($parser)) {
446 $fname = $parser->getFilename();
447 if (defined($fname) && (-f $fname)) {
448 $LOG->debug("Deleting temporary '" . $hive . "' hive data in '" .
449 $fname . "'.");
450 if (!unlink($fname)) {
451 $LOG->fatal("Error: Unable to unlink '" . $hive . "' hive data in '" . $fname ."'.");
452 Carp::croak("Error: Unable to unlink '" . $hive . "' hive data in '" . $fname ."'.");
453 }
454 }
455 delete($parser_collection->{$hive});
456 }
457 }
458 }
459  
460 # Helper function, designed to update the Registry object by
461 # taking snapshots of all specified hives and saving these
462 # to temporary files.
463 #
464 # Inputs: HoneyClient::Agent::Integrity::Registry object,
465 # the hashtable collection of files to snapshot
466 #
467 # Outputs: None.
468 sub _snapshot {
469 # Extract arguments.
470 my ($self, $parser_collection) = @_;
471 my $parser = undef;
472 my $fname = undef;
473 my $fname_tmp = undef;
474 foreach my $hive (@{$self->{hives_to_check}}) {
475 # Check to see if we can reuse temporary files from
476 # past checkpoint operations.
477 if (exists($parser_collection->{$hive}) &&
478 defined($parser_collection->{$hive})) {
479 $parser = $parser_collection->{$hive};
480 $fname = $parser->getFilename();
481 } else {
482 $fname = tmpnam();
483 }
484  
485 $fname_tmp = tmpnam();
486 $LOG->debug("Storing snapshot of hive '" . $hive . "' into '" . $fname . "'.");
487 $LOG->debug("Creating temporary file '" . $fname_tmp . "' to perform data conversion.");
488  
489 # Make sure the registry tools aren't disabled.
490 if (system('reg.exe add HKCU\\\Software\\\Microsoft\\\Windows\\\CurrentVersion\\\Policies\\\System /f > /dev/null 2>&1')) {
491 $LOG->fatal("Error: Unable to enable registry tools in policy.");
492 Carp::croak("Error: Unable to enable registry tools in policy.");
493 }
494 if (system('reg.exe add HKCU\\\Software\\\Microsoft\\\Windows\\\CurrentVersion\\\Policies\\\System /v DisableRegistryTools /t REG_DWORD /d 0 /f > /dev/null 2>&1')) {
495 $LOG->fatal("Error: Unable to enable registry tools in policy.");
496 Carp::croak("Error: Unable to enable registry tools in policy.");
497 }
498  
499 # Dump registry. Strip all '\r' characters.
500 if (system("regedit.exe /a \"" . fullwin32path($fname_tmp) . "\" \"$hive\" &&
501 cat " . $fname_tmp . " | sed -e 's/\r//g' > " . $fname) != 0) {
502 $LOG->fatal("Error: Unable to write '" . $hive . "' hive data to '" . $fname ."'.");
503 Carp::croak("Error: Unable to write '" . $hive . "' hive data to '" . $fname ."'.");
504 }
505  
506 # Delete the unconverted temporary file.
507 _cleanup($fname_tmp);
508  
509 $parser = HoneyClient::Agent::Integrity::Registry::Parser->init(input_file => $fname,
510 index_groups => 1,
511 show_progress => 0);
512  
513 $parser_collection->{$hive} = $parser;
514 }
515 }
516  
517 # Helper function, designed to compare two registry key directory
518 # names. This comparison is case insensitive and handles any strings
519 # that may contain '\\' correctly.
520 #
521 # Inputs: HoneyClient::Agent::Integrity::Registry object,
522 # x directory name, y directory name
523 #
524 # Outputs: -1 if x is alphabetically less than y,
525 # 0 if x and y are equal,
526 # 1 if x is alphabetically greater than y
527 sub _cmpGroup {
528 my ($self, $x, $y) = @_;
529 $x =~ tr/A-Z/a-z/;
530 $x =~ s/\\/\001/g; # \001 instead of \0 due to perl 5.003 bug
531 $y =~ tr/A-Z/a-z/;
532 $y =~ s/\\/\001/g;
533 return $x cmp $y;
534 }
535  
536 # Helper function, designed to compare two registry key entry
537 # names. This comparison is case insensitive, handles default entry
538 # names correctly (@), and strips any quotes.
539 #
540 # Inputs: HoneyClient::Agent::Integrity::Registry object,
541 # x entry name, y entry name
542 #
543 # Outputs: -1 if x is alphabetically less than y,
544 # 0 if x and y are equal,
545 # 1 if x is alphabetically greater than y
546 sub _cmpEntryName {
547 my ($self, $x, $y) = @_;
548  
549 if ($x eq '@') {
550 $x = '';
551 } else {
552 $x =~ s/^"//;
553 $x =~ s/"$//;
554 $x =~ tr/A-Z/a-z/;
555 }
556  
557 if ($y eq '@') {
558 $y = '';
559 } else {
560 $y =~ s/^"//;
561 $y =~ s/"$//;
562 $y =~ tr/A-Z/a-z/;
563 }
564  
565 return $x cmp $y;
566 }
567  
568 # Helper function, designed to get the next registry key directory
569 # name out of the specified file.
570 #
571 # Inputs: HoneyClient::Agent::Integrity::Registry object, file parser to read
572 #
573 # Outputs: next registry key directory name; undef if no key directory names
574 # are left to read
575 sub _nextGroup {
576 my ($self, $parser) = @_;
577  
578 # Read the next key from the specified file.
579 $self->{_currentKeys}->{$parser} = $parser->nextGroup();
580  
581 # Check to make sure read was successful.
582 if (!defined($self->{_currentKeys}->{$parser})) {
583 $LOG->fatal("Error: Unable to read registry keys from '" .
584 $parser->getFilename() . "'.");
585 Carp::croak("Error: Unable to read registry keys from '" .
586 $parser->getFilename() . "'.");
587 }
588  
589 # Encountered empty hash ref, thus we are at
590 # the end of the file.
591 if (!%{$self->{_currentKeys}->{$parser}}) {
592 return undef;
593 }
594  
595 # Key read was successful, reset the entry index
596 # for this file.
597 $self->{_currentEntryIndex}->{$parser} = 0;
598  
599 # Return the corresponding key directory name.
600 return $self->{_currentKeys}->{$parser}->{'key'};
601 }
602  
603 # Helper function, designed to get the next entry (name, value) pair within
604 # the last key directory that was fetched by _nextGroup().
605 #
606 # Inputs: HoneyClient::Agent::Integrity::Registry object, file parser to read
607 #
608 # Outputs: next entry (name, value) pair; undef if no entries were found that
609 # correspond to the last key directory fetched by _nextGroup()
610 sub _nextVal {
611 my ($self, $parser) = @_;
612  
613 # Read the last key object read from the specified file.
614 my ($k) = $self->{_currentKeys}->{$parser};
615  
616 # Get the latest entry index associated with the latest key.
617 my ($i) = $self->{_currentEntryIndex}->{$parser};
618  
619 # If the index is past our array of known entries, then return undef.
620 if ($i >= @{$k->{'entries'}}) {
621 return undef;
622 }
623  
624 # There is an entry to be read, so increment the entry index.
625 $self->{_currentEntryIndex}->{$parser} = $i + 1;
626  
627 # Return the corresponding entry (name, value) pair.
628 return (${$k->{'entries'}}[$i]->{'name'},
629 ${$k->{'entries'}}[$i]->{'value'});
630 }
631  
632 # Helper function, designed to perform a binary diff on two files,
633 # providing two arrays of line numbers, corresponding to where changes
634 # have occurred in either source or target registry hive dumps, along
635 # with an array of corresponding characters ('a', 'c', or 'd'),
636 # signifying what type of change was made.
637 #
638 # Inputs: HoneyClient::Agent::Integrity::Registry object,
639 # source parser, target parser
640 #
641 # Outputs: source line number array ref, target line number array ref,
642 # diff type char array ref
643 sub _diff {
644 # Extract arguments.
645 my ($self, $src_parser, $tgt_parser) = @_;
646  
647 my $src_linenums = [];
648 my $tgt_linenums = [];
649 my $diff_types = [];
650  
651 # Get the corresponding file names.
652 my $src_filename = $src_parser->getFilename();
653 my $tgt_filename = $tgt_parser->getFilename();
654  
655 my $fname_tmp = tmpnam();
656 $LOG->debug("Creating temporary file '" . $fname_tmp . "' to perform differential analysis.");
657  
658 # Perform diff operation.
659 # Because we're chaining together multiple system operations, we have to check the file output
660 # directly, to see if any failures occurred.
661 system("((diff --speed-large-files \"" . $src_filename . "\" \"" . $tgt_filename . "\" && " .
662 "echo \"0NOCHANGES\") | " .
663 "grep -e '^[0-9].*' || echo \"FAILURE\") > " . $fname_tmp . " 2>/dev/null");
664  
665 my $fh = new IO::File($fname_tmp, "r");
666 if (!defined($fh)) {
667 $LOG->fatal("Error: Unable to read file '" . $fname_tmp . "'!");
668 Carp::croak("Error: Unable to read file '" . $fname_tmp . "'!");
669 }
670  
671 # Read in the first line.
672 $/ = "\n";
673 $_ = <$fh>;
674  
675 if (defined($_)) {
676 if ($_ eq "0NOCHANGES\n") {
677 $LOG->debug("No changes detected in specified data.");
678 _cleanup($fname_tmp);
679 return ($src_linenums, $tgt_linenums, $diff_types);
680 }
681 if ($_ eq "FAILURE\n") {
682 # Check if diff operation failed.
683 _cleanup($fname_tmp);
684 $LOG->fatal("Error: Unable to diff '" . $src_filename . "' against '" . $tgt_filename ."'.");
685 Carp::croak("Error: Unable to diff '" . $src_filename . "' against '" . $tgt_filename ."'.");
686 }
687 }
688  
689 do {
690 if (/([0-9]+)(?:|,[0-9]+)([a-z])([0-9]+)/) {
691 push (@{$src_linenums}, $1);
692 push (@{$diff_types}, $2);
693 push (@{$tgt_linenums}, $3);
694 }
695 } while (<$fh>);
696  
697 _cleanup($fname_tmp);
698 return ($src_linenums, $tgt_linenums, $diff_types);
699 }
700  
701 # Helper function, to delete a specified temporary file.
702 #
703 # Inputs: tmpfile
704 # Outputs: None
705 sub _cleanup {
706 my $tmpfile = shift;
707 undef $/;
708 if (!unlink($tmpfile)) {
709 $LOG->fatal("Error: Unable to delete temporary file '" . $tmpfile ."'.");
710 Carp::croak("Error: Unable to delete temporary file '" . $tmpfile ."'.");
711 }
712 }
713  
714 # Helper function, designed to filter a given array reference of
715 # registry changes and return a new list that does not contain
716 # any of the excluded directory names.
717 #
718 # Inputs: self, arrayref of changes
719 # Outpus: arrayref of filtered changes
720 sub _filter {
721 # Extract arguments
722 my ($self, $changes) = @_;
723  
724 # Array reference of filtered changes.
725 my $filteredChanges = [ ];
726  
727 # Indicates if the change should be filtered out.
728 my $changeFiltered = 0;
729  
730 foreach my $change (@{$changes}) {
731 $changeFiltered = 0;
732 foreach my $criteria (@{$self->{'key_dirnames_to_ignore'}}) {
733 if ($change->{'key_name'} =~ /$criteria/) {
734 $changeFiltered = 1;
735 last;
736 }
737 }
738 if (!$changeFiltered) {
739 push (@{$filteredChanges}, $change);
740 }
741 }
742  
743 return $filteredChanges;
744 }
745  
746 # Helper function, designed to be called from within the
747 # Search::Binary::binary_search() function, in order to allow
748 # the binary_search to properly read in group line number data from
749 # the default Registry object reference.
750 #
751 # For more information about how this function operates, please
752 # see the Search::Binary POD documentation.
753 #
754 # Inputs: self, value_to_compare, current_array_index
755 # Outputs: comparison, last_valid_array_index
756 sub _search {
757 # Extract arguments.
758 my ($self, $value_to_compare, $current_array_index) = @_;
759  
760 # Increment the search index, if the current one is undef.
761 if (defined($current_array_index)) {
762 $self->{'_last_search_index'} = $current_array_index;
763 } else {
764 $self->{'_last_search_index'}++;
765 }
766  
767 # Perform a comparison, if the array entry is defined.
768 if (defined(@{$self->{'_group_index_linenums'}}[$self->{'_last_search_index'}])) {
769 return($value_to_compare <=> @{$self->{'_group_index_linenums'}}[$self->{'_last_search_index'}],
770 $self->{'_last_search_index'});
771 }
772  
773 # Array entry not found, return undef with this position.
774 return (undef, $self->{'_last_search_index'});
775 }
776  
777 # Helper function, designed to compare the contents of two registry dumps,
778 # where each dump is represented by a Parser object.
779 #
780 # Inputs: before_parser => bparser, after_parser => aparser
781 # Outputs: an arrayref of registry changes
782 sub _compare {
783  
784 # Extract arguments.
785 my ($self, %args) = @_;
786  
787 my $before_parser = $args{'before_parser'};
788 my $after_parser = $args{'after_parser'};
789  
790 # A hashtable reference, containing the latest change found.
791 my $currentChange = { };
792  
793 # Indicates if the $currentChange hashtable is not empty.
794 my $currentChangeExists = 0;
795  
796 # Array reference, containing hashtables, where each
797 # hashtable represents a change between the before and
798 # after parsers.
799 my $changes = [];
800  
801 # State variable:
802 # - Positive value: Keep comparing groups, linearly.
803 # - Zero or Negative value: Stop comparing groups, seek to
804 # next diff.
805 #
806 # Note: When a comparison is different, then this variable's
807 # value remains the same. When a comparison is the same, then
808 # this variable's value is decremented by 1.
809 my $changeState = 1;
810
811 # Array references, reflecting collection of line numbers
812 # found, where differences occur between before and
813 # after the specified files, along with an array reference of
814 # characters ('a', 'd', or 'c') indicating the type of diffs.
815 my ($before_linenums, $after_linenums, $diff_types) = $self->_diff($before_parser, $after_parser);
816  
817 # Helper variable, used to indirectly locate the corresponding
818 # diff type of the current group block.
819 my $found_index = undef;
820  
821 # Helper variables, to extract the latest line number from the diff
822 # operation, along with the latest diff type.
823 my $before_linenum = undef;
824 my $after_linenum = undef;
825 my $diff_type = undef;
826  
827 # Helper variables, to contain the latest parsed group.
828 my $before_group = undef;
829 my $after_group = undef;
830  
831 # Helper variables, to contain the latest parsed key/value pair.
832 my ($before_entry_name, $before_entry_value) = (undef, undef);
833 my ($after_entry_name, $after_entry_value) = (undef, undef);
834  
835 # Helper variables, to keep track of how many total lines
836 # that the parser has actually parsed.
837 my $before_total_linenums = $before_parser->getCurrentLineCount();
838 my $after_total_linenums = $after_parser->getCurrentLineCount();
839  
840 # Helper variables, to indicate whether the before or after group parser
841 # needs to go back more than by more than one group (if the diff type
842 # was an addition or deletion).
843 my $before_adjust_index = 0;
844 my $after_adjust_index = 0;
845  
846 while (1) {
847  
848 if (($changeState <= 0) ||
849 (!defined($before_group) && !defined($after_group))) {
850  
851 # Get the next set of offsets and type.
852 $before_linenum = shift(@{$before_linenums});
853 $after_linenum = shift(@{$after_linenums});
854 $diff_type = shift(@{$diff_types});
855  
856 # Return early, if no changes were found.
857 if (!defined($before_linenum) && !defined($after_linenum)) {
858 return $changes;
859 }
860  
861 # Figure out how many lines we've parsed so far.
862 $before_total_linenums += $before_parser->getCurrentLineCount();
863 $after_total_linenums += $after_parser->getCurrentLineCount();
864  
865 # Seek to nearest common group, that we haven't already parsed.
866 if (($before_linenum >= $before_total_linenums) &&
867 ($after_linenum >= $after_total_linenums)) {
868  
869 $before_adjust_index = 0;
870 $after_adjust_index = 0;
871  
872 # We need to differentiate between 'a' and 'd' diff types that involve
873 # whole directories, and those that involve only a directory's contents.
874 #
875 # If an 'a' or 'd' diff type is localized to within a directory, then
876 # we know that the directory has simply changed (as it exists in both the
877 # before and after files).
878 #
879 # However, if an 'a' or 'd' diff type includes the directory name, then
880 # we know that the directory itself has been added or deleted respectively.
881 #
882 # In order to determine whether we need to alter our diff type accordingly,
883 # we need to see if the starting diff line number matches the line number
884 # containing the directory name. If it does, then we know that the diff
885 # type does not need to be changed. However, if the diff line number is
886 # PAST the line number of the directory name, then we need to change the
887 # diff type to 'c'.
888  
889 # 1) Figure out which before and after group block represents the specified
890 # line number.
891 # 2) Then seek to the PREVIOUS group block in both cases.
892 # 3) The output of the seekToNearestGroup() call should give you an absolute
893 # line number (call it "x").
894 # 4) Then, (x + 1) should be the starting line number containing the directory
895 # name. This assumes that there's always one and only one newline between
896 # each directory group.
897 # 5) If the starting diff line number is GREATER than (x + 1), then change the
898 # diff type to 'c'. Otherwise, do nothing.
899
900 if ($diff_type eq 'a') {
901 # Seek to the previous group block
902 $after_total_linenums = $after_parser->seekToNearestGroup(absolute_linenum => $after_linenum,
903 adjust_index => 0);
904 # This is the line number of the directory name.
905 my $directory_name_linenum = $after_total_linenums + 1;
906
907 if ($after_linenum != $directory_name_linenum) {
908 $diff_type = 'c';
909 }
910 } elsif ($diff_type eq 'd') {
911
912 $before_total_linenums = $before_parser->seekToNearestGroup(absolute_linenum => $before_linenum,
913 adjust_index => 0);
914 # This is the line number of the directory name.
915 my $directory_name_linenum = $before_total_linenums + 1;
916
917 if ($before_linenum != $directory_name_linenum) {
918 $diff_type = 'c';
919 }
920 }
921  
922 if ($diff_type eq 'a') {
923 $after_adjust_index = -1;
924 # Be sure to perform comparisons before (-1), during (0), and after (-1) the diff block.
925 $changeState = 2;
926 } elsif ($diff_type eq 'd') {
927 $before_adjust_index = -1;
928 # Be sure to perform comparisons before (-1), during (0), and after (-1) the diff block.
929 $changeState = 2;
930 } else {
931 # Be sure to perform comparisons during (0) and after (-1) the diff block.
932 $changeState = 2;
933 }
934  
935 $before_total_linenums = $before_parser->seekToNearestGroup(absolute_linenum => $before_linenum,
936 adjust_index => $before_adjust_index);
937 $after_total_linenums = $after_parser->seekToNearestGroup(absolute_linenum => $after_linenum,
938 adjust_index => $after_adjust_index);
939 }
940 }
941  
942 # Get the next registry group from both files.
943 $before_group = $self->_nextGroup($before_parser);
944 $after_group = $self->_nextGroup($after_parser);
945  
946 # While we are able to read the next key from either file...
947 while (($changeState > 0) && (defined($before_group) || defined($after_group))) {
948  
949 # Update the total line count.
950 $before_total_linenums += $before_parser->getCurrentLineCount();
951 $after_total_linenums += $after_parser->getCurrentLineCount();
952  
953 # Specify the array of line numbers to search in.
954 $self->{'_group_index_linenums'} = $before_linenums;
955  
956 if (defined(@{$before_linenums}[0]) &&
957 ($before_total_linenums >= @{$before_linenums}[0])) {
958  
959 # Find the group after the corresponding matched line number.
960 $found_index = binary_search(0, scalar(@{$before_linenums}) - 1, $before_total_linenums, \&_search, $self);
961  
962 # Find the group before the corresponding matched line number.
963 if ($found_index > 0) {
964 $found_index--;
965 }
966
967 # Fetch the corresponding $diff_type
968 $diff_type = @{$diff_types}[$found_index];
969 }
970  
971 # Sanity check.
972 if (!defined($diff_type)) {
973 $diff_type = '';
974 }
975  
976 # Reset the current change hashref.
977 $currentChange = { };
978  
979 # If the next group name extracted from both files is identical...
980 if (defined($before_group) && defined($after_group) &&
981 ($self->_cmpGroup($before_group, $after_group) == 0)) {
982  
983 # Extract the next key/value pair corresponding to this group from
984 # both files.
985 ($before_entry_name, $before_entry_value) = $self->_nextVal($before_parser);
986 ($after_entry_name, $after_entry_value) = $self->_nextVal($after_parser);
987  
988 # While this key name exists in either file...
989 while (defined($before_entry_name) || defined($after_entry_name)) {
990  
991 # If the key name matches in both files...
992 if (defined($before_entry_name) && defined($after_entry_name) &&
993 $self->_cmpEntryName($before_entry_name, $after_entry_name) == 0) {
994  
995 # If the corresponding values in both files are
996 # DIFFERENT...
997 if ($before_entry_value ne $after_entry_value) {
998  
999 # Scenario:
1000 # Same directory name, same entry key name,
1001 # but different entry values.
1002  
1003 # Save the change.
1004 $currentChange->{'key_name'} = $before_group;
1005 $currentChange->{'status'} = $STATUS_MODIFIED;
1006 $currentChange->{'entries'}->{$before_entry_name} = {
1007 old_value => $before_entry_value,
1008 new_value => $after_entry_value,
1009 };
1010 }
1011  
1012 # Get the next corresponding key/value pair from this group.
1013 ($before_entry_name, $before_entry_value) = $self->_nextVal($before_parser);
1014 ($after_entry_name, $after_entry_value) = $self->_nextVal($after_parser);
1015  
1016 # Else, the key names are different in both files...
1017 } else {
1018  
1019 # Scenario:
1020 # Same directory name, different entry key names.
1021  
1022 # Save the change.
1023 $currentChange->{'key_name'} = $before_group;
1024 $currentChange->{'status'} = $STATUS_MODIFIED;
1025  
1026 # If the after key name doesn't exist, or if the before key
1027 # name exists and the before name is alphabetically earlier
1028 # than the after key name...
1029 if (!defined($after_entry_name) || defined($before_entry_name) &&
1030 $self->_cmpEntryName($before_entry_name, $after_entry_name) < 0) {
1031  
1032 # Then we know that the before key name got deleted
1033 # in the after file.
1034 # Check to see if some of this change data already exists...
1035 if (exists($currentChange->{'entries'}->{$before_entry_name})) {
1036  
1037 # Sanity check: Looks like an earlier iteration populated
1038 # this change entry with a 'new_value'. Let's make sure
1039 # the our 'old_value' and 'new_value' are truly different.
1040 if (defined($currentChange->{'entries'}->{$before_entry_name}->{'new_value'}) &&
1041 ($currentChange->{'entries'}->{$before_entry_name}->{'new_value'} ne
1042 $before_entry_value)) {
1043  
1044 # Okay, looks like they're different, so only update the old_value.
1045 $currentChange->{'entries'}->{$before_entry_name}->{'old_value'} = $before_entry_value;
1046 } else {
1047 # Looks like they're the same value, so delete the entry completely.
1048 delete($currentChange->{'entries'}->{$before_entry_name});
1049 }
1050 } else {
1051 # If not, then update both old_value and new_value.
1052 $currentChange->{'entries'}->{$before_entry_name} = {
1053 old_value => $before_entry_value,
1054 new_value => undef,
1055 };
1056 }
1057  
1058 # And get the next corresponding key/value pair from the before group.
1059 ($before_entry_name, $before_entry_value) = $self->_nextVal($before_parser);
1060  
1061 # Else, the after key name exists but the corresponding before key name
1062 # did not exist -- which means that this is a new key/value pair.
1063 } else {
1064  
1065 # Check to see if some of this change data already exists...
1066 if (exists($currentChange->{'entries'}->{$after_entry_name})) {
1067 # Sanity check: Looks like an earlier iteration populated
1068 # this change entry with an 'old_value'. Let's make sure
1069 # the our 'old_value' and 'new_value' are truly different.
1070 if (defined($currentChange->{'entries'}->{$after_entry_name}->{'old_value'}) &&
1071 ($currentChange->{'entries'}->{$after_entry_name}->{'old_value'} ne
1072 $after_entry_value)) {
1073  
1074 # Okay, looks like they're different, so only update the new_value.
1075 $currentChange->{'entries'}->{$after_entry_name}->{'new_value'} = $after_entry_value;
1076 } else {
1077 # Looks like they're the same value, so delete the entry completely.
1078 delete($currentChange->{'entries'}->{$after_entry_name});
1079 }
1080 } else {
1081 # If not, then update both old_value and new_value.
1082 $currentChange->{'entries'}->{$after_entry_name} = {
1083 old_value => undef,
1084 new_value => $after_entry_value,
1085 };
1086 }
1087  
1088 # And get the next corresponding key/value pair from the after group.
1089 ($after_entry_name, $after_entry_value) = $self->_nextVal($after_parser);
1090 }
1091 }
1092 }
1093  
1094 # Once we're out of the previous loop, then we are finished enumerating
1095 # all key/value pairs corresponding to the identical group in either files.
1096  
1097 # And get the next group to compare from both files.
1098 $before_group = $self->_nextGroup($before_parser);
1099 $after_group = $self->_nextGroup($after_parser);
1100  
1101 # Else, if the after group doesn't exist, or if the before group exists and the
1102 # before group name is alphabetically earlier than the after group name...
1103 # but verify that our $diff_type signifies a deletion or change (otherwise, the groups
1104 # may not be sorted alphabetically).
1105 } elsif (!defined($after_group) || (defined($before_group) &&
1106 ((($diff_type eq 'd') || ($diff_type eq 'c')) &&
1107 ($self->_cmpGroup($before_group, $after_group) < 0)))) {
1108  
1109 # Scenario:
1110 # Directory was deleted.
1111  
1112 # Save the change.
1113 $currentChange->{'key_name'} = $before_group;
1114 $currentChange->{'status'} = $STATUS_DELETED;
1115 $currentChange->{'entries'} = { };
1116  
1117 # Get the first key/value pair from this before group.
1118 ($before_entry_name, $before_entry_value) = $self->_nextVal($before_parser);
1119  
1120 # While there are key/values within this before group.
1121 while (defined($before_entry_name)) {
1122 $currentChange->{'entries'}->{$before_entry_name} = {
1123 old_value => $before_entry_value,
1124 new_value => undef,
1125 };
1126  
1127 # And get the next corresponding key/value pair from the before group.
1128 ($before_entry_name, $before_entry_value) = $self->_nextVal($before_parser);
1129 }
1130  
1131 # Get the next group from the before file.
1132 $before_group = $self->_nextGroup($before_parser);
1133  
1134 # Else, the after group exists but the corresponding before group
1135 # did not exist -- which means that this is a new group.
1136 } else {
1137  
1138 # Scenario:
1139 # Directory was added.
1140  
1141 # Save the change.
1142 $currentChange->{'key_name'} = $after_group;
1143 $currentChange->{'status'} = $STATUS_ADDED;
1144 $currentChange->{'entries'} = { };
1145  
1146 # Get the first key/value pair from this after group.
1147 ($after_entry_name, $after_entry_value) = $self->_nextVal($after_parser);
1148  
1149 # While there are key/values within this after group.
1150 while (defined($after_entry_name)) {
1151  
1152 $currentChange->{'entries'}->{$after_entry_name} = {
1153 old_value => undef,
1154 new_value => $after_entry_value,
1155 };
1156  
1157 # Get the next key/value pair from the after group.
1158 ($after_entry_name, $after_entry_value) = $self->_nextVal($after_parser);
1159 }
1160  
1161 # Get the next group from the after file.
1162 $after_group = $self->_nextGroup($after_parser);
1163 }
1164  
1165 # Transform the 'entries' sub-key from a nested hash structure,
1166 # into an array of separate hashtables.
1167 if (exists($currentChange->{'entries'})) {
1168 my $entries = [ ];
1169 while (my ($key, $value) = each(%{$currentChange->{'entries'}})) {
1170 push (@{$entries}, {
1171 name => $key,
1172 old_value => $value->{'old_value'},
1173 new_value => $value->{'new_value'},
1174 });
1175 }
1176 $currentChange->{'entries'} = $entries;
1177 }
1178  
1179 # Determine if $currentChange is empty.
1180 $currentChangeExists = scalar(keys(%{$currentChange}));
1181  
1182 # Push the change onto our array of changes.
1183 if ($currentChangeExists) {
1184 push(@{$changes}, $currentChange);
1185 } else {
1186 $changeState--;
1187 }
1188 }
1189 }
1190 }
1191  
1192 #######################################################################
1193 # Public Methods Implemented #
1194 #######################################################################
1195  
1196 =pod
1197  
1198 =head1 METHODS IMPLEMENTED
1199  
1200 The following functions have been implemented by any Registry object.
1201  
1202 =head2 HoneyClient::Agent::Integrity::Registry->new($param => $value, ...)
1203  
1204 =over 4
1205  
1206 Creates a new Registry object, which contains a hashtable
1207 containing any of the supplied "param => value" arguments. Upon
1208 creation, the Registry object performs a baseline of the Windows
1209 registry.
1210  
1211 I<Inputs>:
1212 B<$param> is an optional parameter variable.
1213 B<$value> is $param's corresponding value.
1214
1215 Note: If any $param(s) are supplied, then an equal number of
1216 corresponding $value(s) B<must> also be specified.
1217  
1218 I<Output>: The instantiated Registry B<$object>, fully initialized.
1219  
1220 =back
1221  
1222 =begin testing
1223  
1224 diag("These tests will create temporary files in /tmp. Be sure to cleanup this directory, if any of these tests fail.");
1225  
1226 # Create a generic Registry object, with test state data.
1227 my $registry = HoneyClient::Agent::Integrity::Registry->new(test => 1, bypass_baseline => 1);
1228 is($registry->{test}, 1, "new(test => 1, bypass_baseline => 1)") or diag("The new() call failed.");
1229 isa_ok($registry, 'HoneyClient::Agent::Integrity::Registry', "new(test => 1, bypass_baseline => 1)") or diag("The new() call failed.");
1230  
1231 diag("Performing baseline check of 'HKEY_CURRENT_USER' hive; this may take some time...");
1232  
1233 # Perform Registry baseline on HKEY_CURRENT_USER.
1234 $registry = HoneyClient::Agent::Integrity::Registry->new(hives_to_check => [ 'HKEY_CURRENT_USER' ]);
1235 isa_ok($registry, 'HoneyClient::Agent::Integrity::Registry', "new(hives_to_check => [ 'HKEY_CURRENT_USER' ])") or diag("The new() call failed.");
1236  
1237 =end testing
1238  
1239 =cut
1240  
1241 sub new {
1242 # - This function takes in an optional hashtable,
1243 # that contains various key => 'value' configuration
1244 # parameters.
1245 #
1246 # - For each parameter given, it overwrites any corresponding
1247 # parameters specified within the default hashtable, %PARAMS,
1248 # with custom entries that were given as parameters.
1249 #
1250 # - Finally, it returns a blessed instance of the
1251 # merged hashtable, as an 'object'.
1252  
1253 # Get the class name.
1254 my $self = shift;
1255  
1256 # Get the rest of the arguments, as a hashtable.
1257 # Hash-based arguments are used, since HoneyClient::Util::SOAP is unable to handle
1258 # hash references directly. Thus, flat hashtables are used throughout the code
1259 # for consistency.
1260 my %args = @_;
1261  
1262 # Log resolved arguments.
1263 $LOG->debug(sub {
1264 # Make Dumper format more terse.
1265 $Data::Dumper::Terse = 1;
1266 $Data::Dumper::Indent = 0;
1267 Dumper(\%args);
1268 });
1269  
1270 # Check to see if the class name is inherited or defined.
1271 my $class = ref($self) || $self;
1272  
1273 # Initialize default parameters.
1274 $self = { };
1275 my %params = %{dclone(\%PARAMS)};
1276 @{$self}{keys %params} = values %params;
1277  
1278 # Now, overwrite any default parameters that were redefined
1279 # in the supplied arguments.
1280 @{$self}{keys %args} = values %args;
1281  
1282 # Now, assign our object the appropriate namespace.
1283 bless $self, $class;
1284  
1285 # Perform registry baselining, if not bypassed.
1286 if (!$self->{'bypass_baseline'}) {
1287 $LOG->info("Baselining registry hives.");
1288 $self->_snapshot($self->{_baseline_parsers});
1289 }
1290  
1291 # Finally, return the blessed object.
1292 return $self;
1293 }
1294  
1295 =pod
1296  
1297 =head2 $object->check(before_file => $before_filename, after_file => $after_filename)
1298  
1299 =over 4
1300  
1301 Checks the registry for any changes, based upon the baseline snapshot
1302 of the registry, when the new() method was invoked.
1303  
1304 I<Inputs>:
1305 B<$before_filename> is an optional parameter, specifying the registry dump to use
1306 as the baseline, rather than using any baseline that was performed during the
1307 $object->new() operation.
1308 B<$after_filename> is an optional parameter, specifying the registry dump to use
1309 as the checkpoint, rather than creating new a registry checkpoint to compare against.
1310  
1311 I<Output>:
1312 B<$changes>, which is an array of hashtable references, where each
1313 hashtable has the following format:
1314
1315 $changes = [ {
1316 # The registry directory name.
1317 'key_name' => 'HKEY_LOCAL_MACHINE\Software...',
1318  
1319 # Indicates if the registry directory was deleted (0),
1320 # added (1), or changed (2).
1321 'status' => 0 | 1 | 2,
1322
1323 # An array containing the list of entries within the
1324 # registry directory that have been deleted, added, or
1325 # changed. If this array is empty, then the corresponding
1326 # registry directory in the original and new hives contained
1327 # no entries.
1328 'entries' => [ {
1329 'name' => "\"string\"", # A (potentially) quoted string;
1330 # "@" for default
1331 'new_value' => "string", # New string; maybe undef, if deleted
1332 'old_value' => "string", # Old string; maybe undef, if added
1333 }, ],
1334 }, ]
1335  
1336 I<Notes>: If B<$before_filename> is specified, then B<$after_filename> must be
1337 specified as well.
1338  
1339 =back
1340  
1341 =begin testing
1342  
1343 my ($foundChanges, $expectedChanges);
1344 my $before_registry_file = $ENV{PWD} . "/" . getVar(name => "before_registry_file",
1345 namespace => "HoneyClient::Agent::Integrity::Registry::Test");
1346 my $after_registry_file = $ENV{PWD} . "/" . getVar(name => "after_registry_file",
1347 namespace => "HoneyClient::Agent::Integrity::Registry::Test");
1348  
1349  
1350 # Create a generic Registry object, with test state data.
1351 my $registry = HoneyClient::Agent::Integrity::Registry->new(bypass_baseline => 1);
1352  
1353 # Verify Changes
1354 $foundChanges = $registry->check(before_file => $before_registry_file,
1355 after_file => $after_registry_file);
1356 $expectedChanges = [
1357 {
1358 'entries' => [
1359 {
1360 'new_value' => undef,
1361 'name' => 'Test_Bin_1',
1362 'old_value' => 'hex:f4,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,bc,02,00,00,00,\\
1363 00,00,00,00,00,00,00,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,f0,77,3f,00,\\
1364 3f,00,3f,00,3f,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,78,00,1c,10,fc,\\
1365 7f,22,14,fc,7f,b0,fe,12,00,00,00,00,00,00,00,00,00,98,23,eb,77',
1366 },
1367 {
1368 'new_value' => 'hex:f4,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,bc,02,00,00,00,\\
1369 00,00,00,00,00,00,00,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,f0,77,3f,00,\\
1370 3f,00,3f,00,3f,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,78,00,1c,10,fc,\\
1371 7f,22,14,fc,7f,b0,fe,12,00,00,00,00,00,00,00,00,00,98,23,eb,77',
1372 'name' => 'Test_Bon_1',
1373 'old_value' => undef,
1374 }
1375 ],
1376 'status' => $HoneyClient::Agent::Integrity::Registry::STATUS_MODIFIED,
1377 'key_name' => 'HKEY_CURRENT_USER\\Testing Group 3',
1378 },
1379 {
1380 'entries' => [],
1381 'status' => $HoneyClient::Agent::Integrity::Registry::STATUS_DELETED,
1382 'key_name' => 'HKEY_CURRENT_USER\\Testing Group 4',
1383 },
1384 {
1385 'entries' => [
1386 {
1387 'new_value' => 'new value',
1388 'name' => '@',
1389 'old_value' => '',
1390 }
1391 ],
1392 'status' => $HoneyClient::Agent::Integrity::Registry::STATUS_MODIFIED,
1393 'key_name' => 'HKEY_CURRENT_USER\\Testing Group 5',
1394 },
1395 {
1396 'entries' => [
1397 {
1398 'new_value' => 'hex:f5,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,00,00,\\
1399 00,00,00,00,00,00,00,4d,00,69,00,63,00,72,00,6f,00,73,00,6f,00,66,00,74,00,\\
1400 20,00,53,00,61,00,6e,00,73,00,20,00,53,00,65,00,72,00,69,00,66,00,00,00,f0,\\
1401 77,00,20,14,00,00,00,00,10,80,05,14,00,f0,1f,14,00,00,00,14,00',
1402 'name' => 'Test_Bin_3',
1403 'old_value' => undef,
1404 }
1405 ],
1406 'status' => $HoneyClient::Agent::Integrity::Registry::STATUS_ADDED,
1407 'key_name' => 'HKEY_CURRENT_USER\\Testing Group 6',
1408 },
1409 {
1410 'entries' => [
1411 {
1412 'new_value' => 'C:\\\\WINDOWSsystem32\\\\',
1413 'name' => 'InstallerLocation',
1414 'old_value' => 'C:\\\\WINDOWS\\\\system32\\\\',
1415 }
1416 ],
1417 'status' => $HoneyClient::Agent::Integrity::Registry::STATUS_MODIFIED,
1418 'key_name' => 'HKEY_CURRENT_USER\\Testing Group 6\\With\\Really\\Deep\\Nested\\Directory\\Structure',
1419 },
1420 {
1421 'entries' => [
1422 {
1423 'new_value' => '',
1424 'name' => 'C:\\\\WINDOWS\\\\Installer\\\\{6855XXXX-BDF9-48E4-B80A-80DFB96FE36C}\\\\',
1425 'old_value' => undef,
1426 },
1427 {
1428 'new_value' => undef,
1429 'name' => 'C:\\\\WINDOWS\\\\Installer\\\\{6855CCDD-BDF9-48E4-B80A-80DFB96FE36C}\\\\',
1430 'old_value' => '',
1431 }
1432 ],
1433 'status' => $HoneyClient::Agent::Integrity::Registry::STATUS_MODIFIED,
1434 'key_name' => 'HKEY_CURRENT_USER\\Testing Group 7',
1435 },
1436 {
1437 'entries' => [
1438 {
1439 'new_value' => undef,
1440 'name' => '000',
1441 'old_value' => 'String Value',
1442 }
1443 ],
1444 'status' => $HoneyClient::Agent::Integrity::Registry::STATUS_DELETED,
1445 'key_name' => 'HKEY_CURRENT_USER\\Testing Group 8\\{00021492-0000-0000-C000-000000000046}',
1446 },
1447 {
1448 'entries' => [
1449 {
1450 'new_value' => 'String Value',
1451 'name' => '000',
1452 'old_value' => undef,
1453 }
1454 ],
1455 'status' => $HoneyClient::Agent::Integrity::Registry::STATUS_ADDED,
1456 'key_name' => 'HKEY_CURRENT_USER\\Testing Group 8\\{01021492-0000-0000-C000-000000000046}',
1457 },
1458 {
1459 'entries' => [
1460 {
1461 'new_value' => 'newvalue',
1462 'name' => 'newkey',
1463 'old_value' => undef,
1464 }
1465 ],
1466 'status' => $HoneyClient::Agent::Integrity::Registry::STATUS_ADDED,
1467 'key_name' => 'HKEY_CURRENT_USER\\Tsting Group 9',
1468 }
1469 ];
1470  
1471 is_deeply($foundChanges, $expectedChanges, "check(before_file => '" . $before_registry_file . "', after_file => '" . $after_registry_file . "')") or diag("The check() call failed.");
1472  
1473 =end testing
1474  
1475 =cut
1476  
1477 sub check {
1478  
1479 # Extract arguments.
1480 my ($self, %args) = @_;
1481  
1482 # Sanity check: Make sure we've been fed an object.
1483 unless (ref($self)) {
1484 $LOG->error("Error: Function must be called in reference to a " .
1485 __PACKAGE__ . "->new() object!");
1486 Carp::croak "Error: Function must be called in reference to a " .
1487 __PACKAGE__ . "->new() object!\n";
1488 }
1489  
1490 # Log resolved arguments.
1491 $LOG->debug(sub {
1492 # Make Dumper format more terse.
1493 $Data::Dumper::Terse = 1;
1494 $Data::Dumper::Indent = 0;
1495 Dumper(\%args);
1496 });
1497  
1498 # Define before/after parsers.
1499 my ($before_parser, $after_parser);
1500  
1501 # Sanity checks; check if any args were specified.
1502 my $argsExist = scalar(%args);
1503 if ($argsExist &&
1504 exists($args{'before_file'}) &&
1505 defined($args{'before_file'})) {
1506 $LOG->info("Before file '" . $args{'before_file'} . "' manually specified; " .
1507 "using this file as basis, instead of any previous registry snapshot.");
1508 $before_parser = HoneyClient::Agent::Integrity::Registry::Parser->init(input_file => $args{'before_file'},
1509 index_groups => 1);
1510 }
1511  
1512 if ($argsExist &&
1513 exists($args{'after_file'}) &&
1514 defined($args{'after_file'})) {
1515 $LOG->info("After file '" . $args{'after_file'} . "' manually specified; " .
1516 "using this file for comparison, instead of snapshotting the registry.");
1517 $after_parser = HoneyClient::Agent::Integrity::Registry::Parser->init(input_file => $args{'after_file'},
1518 index_groups => 1);
1519 }
1520  
1521 # Array references, containing hashtables, where each
1522 # hashtable represents a change between the registry hives.
1523 my $changes = [];
1524 my $local_changes = [];
1525  
1526 # Check to see if a before and after file were specified.
1527 if (defined($before_parser) && defined($after_parser)) {
1528  
1529 $changes = $self->_compare(before_parser => $before_parser,
1530 after_parser => $after_parser);
1531  
1532 } else {
1533 # Checkpoint the registry.
1534 $LOG->info("Analyzing registry.");
1535 $self->_snapshot($self->{_checkpoint_parsers});
1536  
1537 $LOG->info("Checking for registry changes.");
1538 # Iterate through each hive...
1539 foreach my $hive (@{$self->{hives_to_check}}) {
1540  
1541 $LOG->debug("Checking '" . $hive . "' hive.");
1542  
1543 $before_parser = $self->{_baseline_parsers}->{$hive};
1544 $after_parser = $self->{_checkpoint_parsers}->{$hive};
1545  
1546 # Obtain local changes per hive.
1547 $local_changes = $self->_compare(before_parser => $before_parser,
1548 after_parser => $after_parser);
1549 # Concatinate these changes, to obtain a complete picture.
1550 $changes = [ @{$changes}, @{$local_changes}, ];
1551  
1552 $LOG->debug("Finished checking '" . $hive . "' hive.");
1553 }
1554  
1555 # Cleanup temporary files created by checkpointing.
1556 $self->_cleanupParsers($self->{_checkpoint_parsers});
1557 }
1558  
1559 # Finally, return the array of detected (but filtered) changes.
1560 $changes = $self->_filter($changes);
1561 if (scalar(@{$changes})) {
1562 $LOG->warn("Registry changes found.");
1563 } else {
1564 $LOG->info("No registry changes found.");
1565 }
1566 return $changes;
1567 }
1568  
1569 =pod
1570  
1571 =head2 $object->getFilesCreated()
1572  
1573 =over 4
1574  
1575 Returns a list of temporary filenames that have been created by the
1576 Registry B<$object>.
1577  
1578 I<Output>: Returns a list of filenames.
1579  
1580 =back
1581  
1582 =begin testing
1583  
1584 # Perform Registry baseline on HKEY_CURRENT_CONFIG.
1585 diag("Performing baseline check of 'HKEY_CURRENT_CONFIG' hive; this may take some time...");
1586 my $registry = HoneyClient::Agent::Integrity::Registry->new(hives_to_check => [ 'HKEY_CURRENT_CONFIG' ]);
1587 my @files_created = $registry->getFilesCreated();
1588 use Data::Dumper;
1589 my $tmpfile = tmpnam();
1590 unlink($tmpfile);
1591 my $tmpdir = dirname($tmpfile);
1592 foreach my $file (@files_created) {
1593 like($file, qr/$tmpdir/, "getFilesCreated()") or diag("The getFilesCreated() call failed.");
1594 }
1595  
1596 =end testing
1597  
1598 =cut
1599  
1600 sub getFilesCreated {
1601 # Extract arguments.
1602 my ($self, %args) = @_;
1603  
1604 # Sanity check: Make sure we've been fed an object.
1605 unless (ref($self)) {
1606 $LOG->error("Error: Function must be called in reference to a " .
1607 __PACKAGE__ . "->new() object!");
1608 Carp::croak "Error: Function must be called in reference to a " .
1609 __PACKAGE__ . "->new() object!\n";
1610 }
1611  
1612 # Log resolved arguments.
1613 $LOG->debug(sub {
1614 # Make Dumper format more terse.
1615 $Data::Dumper::Terse = 1;
1616 $Data::Dumper::Indent = 0;
1617 Dumper(\%args);
1618 });
1619  
1620 my @parsers = values(%{$self->{_baseline_parsers}});
1621 push (@parsers, values(%{$self->{_checkpoint_parsers}}));
1622  
1623 my @files;
1624 foreach my $parser (@parsers) {
1625 push (@files, $parser->getFilename());
1626 }
1627  
1628 return @files;
1629 }
1630  
1631 =pod
1632  
1633 =head2 $object->closeFiles()
1634  
1635 =over 4
1636  
1637 Closes any temporary files that have been created by the
1638 Registry B<$object>. By performing this operation, the
1639 Registry B<$object> can become serializable.
1640  
1641 =back
1642  
1643 =begin testing
1644  
1645 # Perform Registry baseline on HKEY_CURRENT_CONFIG.
1646 diag("Performing baseline check of 'HKEY_CURRENT_CONFIG' hive; this may take some time...");
1647 my $registry = HoneyClient::Agent::Integrity::Registry->new(hives_to_check => [ 'HKEY_CURRENT_CONFIG' ]);
1648 $registry->closeFiles();
1649 my @files_created = $registry->getFilesCreated();
1650 use Data::Dumper;
1651 my $tmpfile = tmpnam();
1652 unlink($tmpfile);
1653 my $tmpdir = dirname($tmpfile);
1654 foreach my $file (@files_created) {
1655 like($file, qr/$tmpdir/, "closeFiles()") or diag("The closeFiles() call failed.");
1656 }
1657  
1658 =end testing
1659  
1660 =cut
1661  
1662 sub closeFiles {
1663 # Extract arguments.
1664 my ($self, %args) = @_;
1665  
1666 # Sanity check: Make sure we've been fed an object.
1667 unless (ref($self)) {
1668 $LOG->error("Error: Function must be called in reference to a " .
1669 __PACKAGE__ . "->new() object!");
1670 Carp::croak "Error: Function must be called in reference to a " .
1671 __PACKAGE__ . "->new() object!\n";
1672 }
1673  
1674 # Log resolved arguments.
1675 $LOG->debug(sub {
1676 # Make Dumper format more terse.
1677 $Data::Dumper::Terse = 1;
1678 $Data::Dumper::Indent = 0;
1679 Dumper(\%args);
1680 });
1681  
1682 # Close any temporary files created.
1683 my $parser = undef;
1684 foreach my $hive (@{$self->{hives_to_check}}) {
1685 $parser = $self->{_baseline_parsers}->{$hive};
1686 if (defined($parser)) {
1687 $parser->closeFileHandle();
1688 }
1689 $parser = $self->{_checkpoint_parsers}->{$hive};
1690 if (defined($parser)) {
1691 $parser->closeFileHandle();
1692 }
1693 }
1694 }
1695  
1696 1;
1697  
1698 #######################################################################
1699 # Additional Module Documentation #
1700 #######################################################################
1701  
1702 __END__