Agent/Integrity.pm untested

filter: Statementstmt 0.0% 0 / 95 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 6 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 143 CC 9 SCAR 20.6
CC
9
Cov
0%
check
20.0
closeFiles
12.0
destroy
12.0
CRAP 7.8
1 ################################################################################
2 # Created on: June 01, 2006
3 # Package: HoneyClient::Agent::Integrity
4 # File: Integrity.pm
5 # Description: Module for checking the system integrity for possible
6 # modifications.
7 #
8 # CVS: $Id: Integrity.pm 773 2007-07-26 19:04:55Z kindlund $
9 #
10 # @author knwang, xkovah, ttruong, kindlund, stephenson
11 #
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 - Perl extension to perform configurable
36 integrity checks of the Agent VM OS.
37  
38 =head1 VERSION
39  
40 This documentation refers to HoneyClient::Agent::Integrity version 0.98.
41  
42 =head1 SYNOPSIS
43  
44 use HoneyClient::Agent::Integrity;
45 use Data::Dumper;
46  
47 # Create the Integrity object. Upon creation, the object will
48 # be initialized, by performing a baseline of the Agent VM OS.
49 my $integrity = HoneyClient::Agent::Integrity->new();
50  
51 # ... Some time elapses ...
52  
53 # Check the Agent VM, for any violations.
54 my $changes = $integrity->check();
55  
56 if (!defined($changes)) {
57 print "No integrity violations have occurred.\n";
58 } else {
59 print "System integrity has been compromised:\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 # registry => [ {
68 # # The registry directory name.
69 # 'key' => 'HKEY_LOCAL_MACHINE\Software...',
70 #
71 # # Indicates if the registry directory was deleted,
72 # # added, or changed.
73 # 'status' => 'deleted' | 'added' | 'changed',
74 #
75 # # An array containing the list of entries within the
76 # # registry directory that have been deleted, added, or
77 # # changed. If this array is empty, then the corresponding
78 # # registry directory in the original and new hives contained
79 # # no entries.
80 # 'entries' => [ {
81 # 'name' => "\"string\"", # A (potentially) quoted string;
82 # # "@" for default
83 # 'new_value' => "string", # New string; maybe undef, if deleted
84 # 'old_value' => "string", # Old string; maybe undef, if added
85 # }, ],
86 # }, ],
87 #
88 # filesystem => [ {
89 # # Indicates if the filesystem entry was deleted,
90 # # added, or changed.
91 # 'status' => 'deleted' | 'added' | 'changed',
92 #
93 # # If the entry has been added/changed, then this
94 # # hashtable contains the file/directory's new information.
95 # 'new' => {
96 # 'name' => 'C:\WINDOWS\SYSTEM32...',
97 # 'size' => 1263, # in bytes
98 # 'mtime' => 1178135092, # modification time, seconds since epoch
99 # },
100 #
101 # # If the entry has been deleted/changed, then this
102 # # hashtable contains the file/directory's old information.
103 # 'old' => {
104 # 'name' => 'C:\WINDOWS\SYSTEM32...',
105 # 'size' => 802, # in bytes
106 # 'mtime' => 1178135028, # modification time, seconds since epoch
107 # },
108 # }, ],
109 # }
110  
111 =head1 DESCRIPTION
112  
113 # TODO: This text needs to change.
114  
115 =head2 INITIALIZATION
116  
117 # TODO: This text needs to change.
118  
119 In order to properly check the system, a snapshot must be taken of a known-good
120 state.
121  
122 For the filesystem this means a listing is created which contains
123 cryptographic hashes of files in their start state. The only files what are
124 checked are those which are explicitly specified in the checklist file (or are
125 found in a specified directory) and are not in the exclusion list will be checked.
126 Initialization of the filesystem is done with the initFileSystem() function,
127 described later.
128  
129 For the registry a similar logic applies in that the only the specified keys are
130 checked and only if they are not in the exclusion list. The desired registry keys
131 are exported to a text file via the command line functionality of regedit. This
132 is done via initRegistry().
133  
134  
135 =head2 CHECKING
136  
137 # TODO: This text needs to change.
138  
139 Checking the filesystem entails running mostly the same code as the initialization
140 piece in order to obtain a snapshot of the current state of the filesystem. At that
141 point additional checks are performed to look for additions, deletions, and
142 modifications to the filesystem. These checks are done with checkFileSystem().
143  
144 A speed-optimized check of the registry is performed by first dumping the current
145 state, again with the command line version of regedit. Then the unix "diff"
146 utility is used to compare the clean registry dump to the current one. The output
147 from a diff is in a format which shows the minimum possible changes which can be
148 done to the first file in order to yield the same content as the second file.
149 Therefore this format must be parsed in order to determine what specific additions,
150 deletions, and modifications were made to the clean registry. Further, because
151 the output of diff need not exactly reflect changes (for instance when the same
152 content would be the first line of the previous value and the last line of the new
153 value) this requires some cases to re-consult the original and current state in order
154 to disambiguate the changes which were made. These tests are done in checkRegistry().
155  
156 NOTE: Because these are simple, static, user-space checks, they can fail in the
157 presense of even user-space rootkits. Therefore these checks should not be taken as
158 definitive proof of the absense of malicious software until they are integrated more
159 tightly with the system.
160  
161 =cut
162  
163 package HoneyClient::Agent::Integrity;
164  
165 use strict;
166 use warnings;
167 use Carp ();
168  
169  
170 # Include Global Configuration Processing Library
171 use HoneyClient::Util::Config qw(getVar);
172  
173 # Include the Registry Checking Library
174 use HoneyClient::Agent::Integrity::Registry;
175  
176 # Include the Filesystem Checking Library
177 use HoneyClient::Agent::Integrity::Filesystem;
178  
179 # Use Storable Library
180 use Storable qw(nfreeze thaw dclone);
181 $Storable::Deparse = 1;
182 $Storable::Eval = 1;
183  
184 # Use Dumper Library
185 use Data::Dumper;
186  
187 # Include Logging Library
188 use Log::Log4perl qw(:easy);
189  
190 #######################################################################
191 # Module Initialization #
192 #######################################################################
193  
194 BEGIN {
195 # Defines which functions can be called externally.
196 require Exporter;
197 our (@ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS, $VERSION);
198  
199 # Set our package version.
200 $VERSION = 0.98;
201  
202 @ISA = qw(Exporter);
203  
204 # Symbols to export automatically
205 @EXPORT = qw( );
206  
207 # Items to export into callers namespace by default. Note: do not export
208 # names by default without a very good reason. Use EXPORT_OK instead.
209 # Do not simply export all your public functions/methods/constants.
210  
211 # This allows declaration use HoneyClient::Agent::Integrity ':all';
212 # If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
213 # will save memory.
214  
215 %EXPORT_TAGS = (
216 'all' => [ qw( ) ],
217 );
218  
219 # Symbols to autoexport (when qw(:all) tag is used)
220 @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
221  
222 $SIG{PIPE} = 'IGNORE'; # Do not exit on broken pipes.
223 }
224 our (@EXPORT_OK, $VERSION);
225  
226 =pod
227  
228 =begin testing
229  
230 # Make sure Log::Log4perl loads
231 BEGIN { use_ok('Log::Log4perl', qw(:nowarn))
232 or diag("Can't load Log::Log4perl package. Check to make sure the package library is correctly listed within the path.");
233
234 # Suppress all logging messages, since we need clean output for unit testing.
235 Log::Log4perl->init({
236 "log4perl.rootLogger" => "DEBUG, Buffer",
237 "log4perl.appender.Buffer" => "Log::Log4perl::Appender::TestBuffer",
238 "log4perl.appender.Buffer.min_level" => "fatal",
239 "log4perl.appender.Buffer.layout" => "Log::Log4perl::Layout::PatternLayout",
240 "log4perl.appender.Buffer.layout.ConversionPattern" => "%d{yyyy-MM-dd HH:mm:ss} %5p [%M] (%F:%L) - %m%n",
241 });
242 }
243 require_ok('Log::Log4perl');
244 use Log::Log4perl qw(:easy);
245  
246 # Make sure the module loads properly, with the exportable
247 # functions shared.
248 BEGIN { use_ok('HoneyClient::Util::Config', qw(getVar setVar))
249 or diag("Can't load HoneyClient::Util::Config package. Check to make sure the package library is correctly listed within the path."); }
250 require_ok('HoneyClient::Util::Config');
251 can_ok('HoneyClient::Util::Config', 'getVar');
252 can_ok('HoneyClient::Util::Config', 'setVar');
253 use HoneyClient::Util::Config qw(getVar setVar);
254  
255 # Suppress all logging messages, since we need clean output for unit testing.
256 Log::Log4perl->init({
257 "log4perl.rootLogger" => "DEBUG, Buffer",
258 "log4perl.appender.Buffer" => "Log::Log4perl::Appender::TestBuffer",
259 "log4perl.appender.Buffer.min_level" => "fatal",
260 "log4perl.appender.Buffer.layout" => "Log::Log4perl::Layout::PatternLayout",
261 "log4perl.appender.Buffer.layout.ConversionPattern" => "%d{yyyy-MM-dd HH:mm:ss} %5p [%M] (%F:%L) - %m%n",
262 });
263  
264 # Make sure Data::Dumper loads
265 BEGIN { use_ok('Data::Dumper')
266 or diag("Can't load Data::Dumper package. Check to make sure the package library is correctly listed within the path."); }
267 require_ok('Data::Dumper');
268 use Data::Dumper;
269  
270 # Make sure Storable loads
271 BEGIN { use_ok('Storable', qw(nfreeze thaw dclone))
272 or diag("Can't load Storable package. Check to make sure the package library is correctly listed within the path."); }
273 require_ok('Storable');
274 can_ok('Storable', 'nfreeze');
275 can_ok('Storable', 'thaw');
276 can_ok('Storable', 'dclone');
277 use Storable qw(nfreeze thaw dclone);
278  
279 # Make sure HoneyClient::Agent::Integrity::Registry loads
280 BEGIN { use_ok('HoneyClient::Agent::Integrity::Registry')
281 or diag("Can't load HoneyClient::Agent::Integrity::Registry package. Check to make sure the package library is correctly listed within the path."); }
282 require_ok('HoneyClient::Agent::Integrity::Registry');
283 use HoneyClient::Agent::Integrity::Registry;
284  
285 # Make sure HoneyClient::Agent::Integrity::Filesystem loads
286 BEGIN { use_ok('HoneyClient::Agent::Integrity::Filesystem')
287 or diag("Can't load HoneyClient::Agent::Integrity::Filesystem package. Check to make sure the package library is correctly listed within the path."); }
288 require_ok('HoneyClient::Agent::Integrity::Filesystem');
289 use HoneyClient::Agent::Integrity::Filesystem;
290  
291 # Make sure HoneyClient::Agent::Integrity loads.
292 BEGIN { use_ok('HoneyClient::Agent::Integrity') or diag("Can't load HoneyClient::Agent::Integrity package. Check to make sure the package library is correctly listed within the path."); }
293 require_ok('HoneyClient::Agent::Integrity');
294 use HoneyClient::Agent::Integrity;
295  
296 =end testing
297  
298 =cut
299  
300 #######################################################################
301 # Global Configuration Variables #
302 #######################################################################
303  
304 # The global logging object.
305 our $LOG = get_logger();
306  
307 =pod
308  
309 =head1 DEFAULT PARAMETER LIST
310  
311 When an Integrity B<$object> is instantiated using the B<new()> function,
312 the following parameters are supplied default values. Each value
313 can be overridden by specifying the new (key => value) pair into the
314 B<new()> function, as arguments.
315  
316 =head2 bypass_baseline
317  
318 =over 4
319  
320 When set to 1, the object will forgo any type of initial baselining
321 process, upon initialization. Otherwise, baselining will occur
322 as normal, upon initialization.
323  
324 =back
325  
326 =cut
327  
328 my %PARAMS = (
329 # When set to 1, the object will forgo any type of initial baselining
330 # process, upon initialization. Otherwise, baselining will occur
331 # as normal, upon initialization.
332 bypass_baseline => 0,
333  
334 # Contains the Registry object, once initialized.
335 # (For internal use only.)
336 _registry => undef,
337  
338 # Contains the Filesystem object, once initialized.
339 # (For internal use only.)
340 _filesystem => undef,
341  
342 # XXX: comment this
343 _changes_found_file => getVar(name => 'changes_found_file'),
344 );
345  
346 #######################################################################
347 # Private Methods Implemented #
348 #######################################################################
349  
350 # Helper function, designed to baseline the system.
351 #
352 # Inputs: None.
353 # Outputs: None.
354 sub _baseline {
355 my $self = shift;
356 # XXX: The Registry object MUST be created before the Filesystem object, since
357 # the Registry object creates new files that must exist to be added to the
358 # Filesystem's baseline list of files that exist on the system.
359 $self->{'_registry'} = HoneyClient::Agent::Integrity::Registry->new();
360 $self->{'_filesystem'} = HoneyClient::Agent::Integrity::Filesystem->new();
361 }
362  
363 #######################################################################
364 # Public Methods Implemented #
365 #######################################################################
366  
367 =pod
368  
369 =head1 METHODS IMPLEMENTED
370  
371 The following functions have been implemented by any Integrity object.
372  
373 =head2 HoneyClient::Agent::Integrity->new($param => $value, ...)
374  
375 =over 4
376  
377 Creates a new Integrity object, which contains a hashtable
378 containing any of the supplied "param => value" arguments. Upon
379 creation, the Integrity object initializes all of its sub-modules,
380 by creating a baseline of the operating system.
381  
382 I<Inputs>:
383 B<$param> is an optional parameter variable.
384 B<$value> is $param's corresponding value.
385
386 Note: If any $param(s) are supplied, then an equal number of
387 corresponding $value(s) B<must> also be specified.
388  
389 I<Output>: The instantiated Integrity B<$object>, fully initialized.
390  
391 =back
392  
393 =begin testing
394  
395 diag("These tests will create temporary files in /tmp. Be sure to cleanup this directory, if any of these tests fail.");
396  
397 # Create a generic Integrity object, with test state data.
398 my $integrity = HoneyClient::Agent::Integrity->new(test => 1, bypass_baseline => 1);
399 is($integrity->{test}, 1, "new(test => 1, bypass_baseline => 1)") or diag("The new() call failed.");
400 isa_ok($integrity, 'HoneyClient::Agent::Integrity', "new(test => 1, bypass_baseline => 1)") or diag("The new() call failed.");
401  
402 diag("Performing baseline check of the system; this may take some time...");
403  
404 # XXX: Uncomment this next check, eventually. (It's commented out right now, in order to save some time).
405 # Perform baseline.
406 $integrity = HoneyClient::Agent::Integrity->new();
407 isa_ok($integrity, 'HoneyClient::Agent::Integrity', "new()") or diag("The new() call failed.");
408  
409 =end testing
410  
411 =cut
412  
413 sub new {
414 # - This function takes in an optional hashtable,
415 # that contains various key => 'value' configuration
416 # parameters.
417 #
418 # - For each parameter given, it overwrites any corresponding
419 # parameters specified within the default hashtable, %PARAMS,
420 # with custom entries that were given as parameters.
421 #
422 # - Finally, it returns a blessed instance of the
423 # merged hashtable, as an 'object'.
424  
425 # Get the class name.
426 my $self = shift;
427  
428 # Get the rest of the arguments, as a hashtable.
429 # Hash-based arguments are used, since HoneyClient::Util::SOAP is unable to handle
430 # hash references directly. Thus, flat hashtables are used throughout the code
431 # for consistency.
432 my %args = @_;
433  
434 # Check to see if the class name is inherited or defined.
435 my $class = ref($self) || $self;
436  
437 # Initialize default parameters.
438 $self = { };
439 my %params = %{dclone(\%PARAMS)};
440 @{$self}{keys %params} = values %params;
441  
442 # Now, overwrite any default parameters that were redefined
443 # in the supplied arguments.
444 @{$self}{keys %args} = values %args;
445  
446 # Now, assign our object the appropriate namespace.
447 bless $self, $class;
448  
449 # Perform baselining, if not bypassed.
450 if (!$self->{'bypass_baseline'}) {
451 $LOG->info("Baselining system.");
452 $self->_baseline();
453 }
454  
455 # Finally, return the blessed object.
456 return $self;
457 }
458  
459  
460 =pod
461  
462 =head2 $object->check()
463  
464 =over 4
465  
466 Checks the operating system for various changes, based upon
467 the baseline snapshot of the system, when the new() method
468 was invoked.
469  
470 I<Output>:
471 B<$changes>, which is an array of hashtable references, where each
472 hashtable has the following format:
473
474 $changes = {
475 registry => [ {
476 # The registry directory name.
477 'key' => 'HKEY_LOCAL_MACHINE\Software...',
478  
479 # Indicates if the registry directory was deleted,
480 # added, or changed.
481 'status' => 'deleted' | 'added' | 'changed',
482
483 # An array containing the list of entries within the
484 # registry directory that have been deleted, added, or
485 # changed. If this array is empty, then the corresponding
486 # registry directory in the original and new hives contained
487 # no entries.
488 'entries' => [ {
489 'name' => "\"string\"", # A (potentially) quoted string;
490 # "@" for default
491 'new_value' => "string", # New string; maybe undef, if deleted
492 'old_value' => "string", # Old string; maybe undef, if added
493 }, ],
494 }, ],
495  
496 filesystem => [ {
497 # Indicates if the filesystem entry was deleted,
498 # added, or changed.
499 'status' => 'deleted' | 'added' | 'changed',
500  
501 # If the entry has been added/changed, then this
502 # hashtable contains the file/directory's new information.
503 'new' => {
504 'name' => 'C:\WINDOWS\SYSTEM32...',
505 'size' => 1263, # in bytes
506 'mtime' => 1178135092, # modification time, seconds since epoch
507 },
508  
509 # If the entry has been deleted/changed, then this
510 # hashtable contains the file/directory's old information.
511 'old' => {
512 'name' => 'C:\WINDOWS\SYSTEM32...',
513 'size' => 802, # in bytes
514 'mtime' => 1178135028, # modification time, seconds since epoch
515 },
516 }, ],
517 }
518  
519 I<Notes>:
520  
521 =back
522  
523 #=begin testing
524 #
525 # TODO:
526 #
527 #=end testing
528  
529 =cut
530  
531 sub check {
532  
533 # Extract arguments.
534 my ($self, %args) = @_;
535  
536 # Sanity check: Make sure we've been fed an object.
537 unless (ref($self)) {
538 $LOG->error("Error: Function must be called in reference to a " .
539 __PACKAGE__ . "->new() object!");
540 Carp::croak "Error: Function must be called in reference to a " .
541 __PACKAGE__ . "->new() object!\n";
542 }
543  
544 # Log resolved arguments.
545 $LOG->debug(sub {
546 # Make Dumper format more terse.
547 $Data::Dumper::Terse = 1;
548 $Data::Dumper::Indent = 0;
549 Dumper(\%args);
550 });
551  
552 my $changes = {
553 'registry' => $self->{'_registry'}->check(),
554 'filesystem' => $self->{'_filesystem'}->check(),
555 };
556  
557 # If any changes were found, write them out to the
558 # filesystem.
559 if (scalar(@{$changes->{registry}}) ||
560 scalar(@{$changes->{filesystem}})) {
561 if (!open(CHANGE_FILE, ">>" . $self->{_changes_found_file})) {
562 $LOG->error("Unable to write changes to file '" . $self->{_changes_found_file} . "'.");
563 } else {
564 $Data::Dumper::Terse = 1;
565 $Data::Dumper::Indent = 1;
566 print CHANGE_FILE Dumper($changes);
567 close CHANGE_FILE;
568 }
569 }
570  
571 return $changes;
572 }
573  
574 # TODO: Comment this.
575 sub closeFiles {
576 my $self = shift;
577  
578 # Sanity check: Make sure we've been fed an object.
579 unless (ref($self)) {
580 $LOG->error("Error: Function must be called in reference to a " .
581 __PACKAGE__ . "->new() object!");
582 Carp::croak "Error: Function must be called in reference to a " .
583 __PACKAGE__ . "->new() object!\n";
584 }
585  
586 if (defined($self->{'_registry'})) {
587 $self->{'_registry'}->closeFiles();
588 }
589 }
590  
591 # TODO: Comment this.
592 sub destroy {
593 my $self = shift;
594  
595 # Sanity check: Make sure we've been fed an object.
596 unless (ref($self)) {
597 $LOG->error("Error: Function must be called in reference to a " .
598 __PACKAGE__ . "->new() object!");
599 Carp::croak "Error: Function must be called in reference to a " .
600 __PACKAGE__ . "->new() object!\n";
601 }
602  
603 if (defined($self->{'_registry'})) {
604 $self->{'_registry'}->destroy();
605 }
606 }
607  
608 1;
609  
610 =pod
611  
612 =head1 BUGS & ASSUMPTIONS
613  
614 # XXX: Fill this in.
615  
616 =head1 TODO
617  
618 Need to add sub-modules that support the following capabilities:
619  
620 =over 4
621  
622 =item *
623  
624 Static or real-time rogue process detection.
625  
626 =item *
627  
628 Static or real-time memory alteration detection.
629  
630 =back
631  
632 =head1 SEE ALSO
633  
634 L<http://www.honeyclient.org/trac>
635  
636 =head1 REPORTING BUGS
637  
638 L<http://www.honeyclient.org/trac/newticket>
639  
640 =head1 ACKNOWLEDGEMENTS
641  
642 XXX: Fill this in.
643  
644 =head1 AUTHORS
645  
646 Kathy Wang, E<lt>knwang@mitre.orgE<gt>
647  
648 Xeno Kovah, E<lt>xkovah@mitre.orgE<gt>
649  
650 Thanh Truong, E<lt>ttruong@mitre.orgE<gt>
651  
652 Darien Kindlund, E<lt>kindlund@mitre.orgE<gt>
653  
654 Brad Stephenson, E<lt>stephenson@mitre.orgE<gt>
655  
656 =head1 COPYRIGHT & LICENSE
657  
658 Copyright (C) 2007 The MITRE Corporation. All rights reserved.
659  
660 This program is free software; you can redistribute it and/or
661 modify it under the terms of the GNU General Public License
662 as published by the Free Software Foundation, using version 2
663 of the License.
664
665 This program is distributed in the hope that it will be useful,
666 but WITHOUT ANY WARRANTY; without even the implied warranty of
667 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
668 GNU General Public License for more details.
669
670 You should have received a copy of the GNU General Public License
671 along with this program; if not, write to the Free Software
672 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
673 02110-1301, USA.
674  
675  
676 =cut
677