Agent/Integrity/Filesystem.pm untested

filter: Statementstmt 0.0% 0 / 354 Branchbran 0.0% 0 / 68 Conditioncond 0.0% 0 / 48 MC/DCmcdc 0.0% 0 / 29 Subroutinesub 0.0% 0 / 30 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 541 CC 35 SCAR 39.7
CC
35
Cov
0%
_diff
182.0
_filter
72.0
_prepare
30.0
CRAP 53.1
1 ################################################################################
2 # Created on: April 12, 2007
3 # Package: HoneyClient::Agent::Integrity::Filesystem
4 # File: Filesystem.pm
5 # Description: Performs static checks of the Windows OS filesystem.
6 #
7 # CVS: $Id: Filesystem.pm 773 2007-07-26 19:04:55Z kindlund $
8 #
9 # @author xkovah, kindlund, stephenson
10 #
11 # Copyright (C) 2007 The MITRE Corporation. All rights reserved.
12 #
13 # This program is free software; you can redistribute it and/or
14 # modify it under the terms of the GNU General Public License
15 # as published by the Free Software Foundation, using version 2
16 # of the License.
17 #
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 # 02110-1301, USA.
27 #
28 ################################################################################
29  
30 =pod
31  
32 =head1 NAME
33  
34 HoneyClient::Agent::Integrity::Filesystem - Perl extension to perform static
35 checks of the Windows OS filesystem.
36  
37 =head1 VERSION
38  
39 This documentation refers to HoneyClient::Agent::Integrity::Filesystem version 0.98.
40  
41 =head1 SYNOPSIS
42  
43 use HoneyClient::Agent::Integrity::Filesystem;
44 use Data::Dumper;
45  
46 # Create the filesystem object. Upon creation, the object will
47 # be initialized, by performing a baseline of the filesystem.
48 my $filesystem = HoneyClient::Agent::Integrity::Filesystem->new();
49  
50 # ... Some time elapses ...
51  
52 # Check the filesystem, for any violations.
53 my $changes = $filesystem->check();
54  
55 if (!defined($changes)) {
56 print "No filesystem changes have occurred.\n";
57 } else {
58 print "Filesystem has changed:\n";
59 print Dumper($changes);
60 }
61  
62 # $changes refers to an array of hashtable references, where
63 # each hashtable has the following format:
64 #
65 # $changes = [ {
66 # # Indicates if the filesystem entry was deleted,
67 # # added, or changed.
68 # 'status' => $STATUS_DELETED | $STATUS_ADDED | $STATUS_MODIFIED,
69 # 'name' => 'C:\WINDOWS\SYSTEM32...',
70 # 'mtime' => 'YYYY-MM-DD HH:MM:SS', # new mtime for added/modified files;
71 # # old mtime for deleted files
72 #
73 # # content will only exist for added/modified files
74 # 'content' => {
75 # 'size' => 1263, # size of new content
76 # 'type' => 'application/octect-stream', # type of new content
77 # 'md5' => 'b1946ac92492d2347c6235b4d2611184', # md5 of new content
78 # 'sha1' => 'f572d396fae9206628714fb2ce00f72e94f2258f', # sha1 of new content
79 # },
80 # }, ]
81  
82 =head1 DESCRIPTION
83  
84 This library allows the Integrity module to easily baseline and check
85 the Windows OS filesystem for any changes that may occur, while
86 instrumenting a target application.
87  
88 =cut
89  
90 package HoneyClient::Agent::Integrity::Filesystem;
91  
92 use strict;
93 use warnings;
94 use Carp ();
95  
96 # Include Global Configuration Processing Library
97 use HoneyClient::Util::Config qw(getVar);
98  
99 # Include the File/Directory Search Library
100 use File::Find qw(find);
101  
102 # Include the Diff algorithm for comparing files
103 use Algorithm::Diff;
104  
105 # Include Cygwin Path Conversion Library.
106 use Filesys::CygwinPaths qw(:all);
107  
108 # Use Storable Library
109 use Storable qw(nfreeze thaw dclone);
110 $Storable::Deparse = 1;
111 $Storable::Eval = 1;
112  
113 # Use Dumper Library
114 use Data::Dumper;
115  
116 # Use Basename Library
117 use File::Basename qw(dirname);
118  
119 # Include Logging Library
120 use Log::Log4perl qw(:easy);
121  
122 # Use DateTime Library
123 use DateTime;
124  
125 # Use MD5 Library
126 use Digest::MD5;
127  
128 # Use SHA Library
129 use Digest::SHA;
130  
131 # Use File::Type Library
132 use File::Type;
133  
134 # Use IO::File Library
135 use IO::File;
136  
137 #######################################################################
138 # Module Initialization #
139 #######################################################################
140  
141 BEGIN {
142 # Defines which functions can be called externally.
143 require Exporter;
144 our (@ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS, $VERSION);
145  
146 # Set our package version.
147 $VERSION = 0.98;
148  
149 @ISA = qw(Exporter);
150  
151 # Symbols to export automatically
152 @EXPORT = qw( );
153  
154 # Items to export into callers namespace by default. Note: do not export
155 # names by default without a very good reason. Use EXPORT_OK instead.
156 # Do not simply export all your public functions/methods/constants.
157  
158 # This allows declaration use HoneyClient::Agent::Integrity::Filesystem ':all';
159 # If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
160 # will save memory.
161  
162 %EXPORT_TAGS = (
163 'all' => [ qw( ) ],
164 );
165  
166 # Symbols to autoexport (when qw(:all) tag is used)
167 @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
168  
169 $SIG{PIPE} = 'IGNORE'; # Do not exit on broken pipes.
170 }
171 our (@EXPORT_OK, $VERSION);
172  
173 =pod
174  
175 =begin testing
176  
177 # Make sure Log::Log4perl loads
178 BEGIN { use_ok('Log::Log4perl', qw(:nowarn))
179 or diag("Can't load Log::Log4perl package. Check to make sure the package library is correctly listed within the path.");
180  
181 # Suppress all logging messages, since we need clean output for unit testing.
182 Log::Log4perl->init({
183 "log4perl.rootLogger" => "DEBUG, Buffer",
184 "log4perl.appender.Buffer" => "Log::Log4perl::Appender::TestBuffer",
185 "log4perl.appender.Buffer.min_level" => "fatal",
186 "log4perl.appender.Buffer.layout" => "Log::Log4perl::Layout::PatternLayout",
187 "log4perl.appender.Buffer.layout.ConversionPattern" => "%d{yyyy-MM-dd HH:mm:ss} %5p [%M] (%F:%L) - %m%n",
188 });
189 }
190 require_ok('Log::Log4perl');
191 use Log::Log4perl qw(:easy);
192  
193 # Make sure the module loads properly, with the exportable
194 # functions shared.
195 BEGIN { use_ok('HoneyClient::Util::Config', qw(getVar setVar))
196 or diag("Can't load HoneyClient::Util::Config package. Check to make sure the package library is correctly listed within the path."); }
197 require_ok('HoneyClient::Util::Config');
198 can_ok('HoneyClient::Util::Config', 'getVar');
199 can_ok('HoneyClient::Util::Config', 'setVar');
200 use HoneyClient::Util::Config qw(getVar setVar);
201  
202 # Suppress all logging messages, since we need clean output for unit testing.
203 Log::Log4perl->init({
204 "log4perl.rootLogger" => "DEBUG, Buffer",
205 "log4perl.appender.Buffer" => "Log::Log4perl::Appender::TestBuffer",
206 "log4perl.appender.Buffer.min_level" => "fatal",
207 "log4perl.appender.Buffer.layout" => "Log::Log4perl::Layout::PatternLayout",
208 "log4perl.appender.Buffer.layout.ConversionPattern" => "%d{yyyy-MM-dd HH:mm:ss} %5p [%M] (%F:%L) - %m%n",
209 });
210  
211 # Make sure Data::Dumper loads
212 BEGIN { use_ok('Data::Dumper')
213 or diag("Can't load Data::Dumper package. Check to make sure the package library is correctly listed within the path."); }
214 require_ok('Data::Dumper');
215 use Data::Dumper;
216  
217 # Make sure Storable loads
218 BEGIN { use_ok('Storable', qw(nfreeze thaw dclone))
219 or diag("Can't load Storable package. Check to make sure the package library is correctly listed within the path."); }
220 require_ok('Storable');
221 can_ok('Storable', 'nfreeze');
222 can_ok('Storable', 'thaw');
223 can_ok('Storable', 'dclone');
224 use Storable qw(nfreeze thaw dclone);
225  
226 # Make sure File::Find loads.
227 BEGIN { use_ok('File::Find', qw(find)) or diag("Can't load File::Find package. Check to make sure the package library is correctly listed within the path."); }
228 require_ok('File::Find');
229 can_ok('File::Find', 'find');
230 use File::Find;
231  
232 # Make sure Filesys::CygwinPaths loads
233 BEGIN { use_ok('Filesys::CygwinPaths')
234 or diag("Can't load Filesys::CygwinPaths package. Check to make sure the package library is correctly listed within the path."); }
235 require_ok('Filesys::CygwinPaths');
236 use Filesys::CygwinPaths qw(:all);
237  
238 # Make sure Algorithm::Diff loads.
239 BEGIN { use_ok('Algorithm::Diff') or diag("Can't load Algorithm::Diff package. Check to make sure the package library is correctly listed within the path."); }
240 require_ok('Algorithm::Diff');
241 use Algorithm::Diff;
242  
243 # Make sure File::Basename loads.
244 BEGIN { use_ok('File::Basename', qw(dirname)) or diag("Can't load File::Basename package. Check to make sure the package library is correctly listed within the path."); }
245 require_ok('File::Basename');
246 can_ok('File::Basename', 'dirname');
247 use File::Basename qw(dirname);
248  
249 # Make sure HoneyClient::Agent::Integrity::Filesystem loads.
250 BEGIN { use_ok('HoneyClient::Agent::Integrity::Filesystem') or diag("Can't load HoneyClient::Agent::Integrity::Filesystem package. Check to make sure the package library is correctly listed within the path."); }
251 require_ok('HoneyClient::Agent::Integrity::Filesystem');
252 use HoneyClient::Agent::Integrity::Filesystem;
253  
254 # Make sure DateTime loads.
255 BEGIN { use_ok('DateTime') or diag("Can't load DateTime package. Check to make sure the package library is correctly listed within the path."); }
256 require_ok('DateTime');
257 use DateTime;
258  
259 # Make sure Digest::MD5 loads.
260 BEGIN { use_ok('Digest::MD5') or diag("Can't load Digest::MD5 package. Check to make sure the package library is correctly listed within the path."); }
261 require_ok('Digest::MD5');
262 use Digest::MD5;
263  
264 # Make sure Digest::SHA loads.
265 BEGIN { use_ok('Digest::SHA') or diag("Can't load Digest::SHA package. Check to make sure the package library is correctly listed within the path."); }
266 require_ok('Digest::SHA');
267 use Digest::SHA;
268  
269 # Make sure File::Type loads.
270 BEGIN { use_ok('File::Type') or diag("Can't load File::Type package. Check to make sure the package library is correctly listed within the path."); }
271 require_ok('File::Type');
272 use File::Type;
273  
274 # Make sure IO::File loads.
275 BEGIN { use_ok('IO::File') or diag("Can't load IO::File package. Check to make sure the package library is correctly listed within the path."); }
276 require_ok('IO::File');
277 use IO::File;
278  
279 =end testing
280  
281 =cut
282  
283 #######################################################################
284 # Global Configuration Variables #
285 #######################################################################
286  
287 # TODO: Need to link these constants with DB code.
288 # Filesystem Status Identifiers
289 our $STATUS_DELETED = 0;
290 our $STATUS_ADDED = 1;
291 our $STATUS_MODIFIED = 2;
292  
293 # TODO: Need to link these constants with DB code.
294 # Set hash value to this constant, if unable to compute.
295 our $HASH_UNKNOWN = 'UNKNOWN';
296 # Set type value to this constant, if unable to compute.
297 our $TYPE_UNKNOWN = 'UNKNOWN';
298  
299 # The global logging object.
300 our $LOG = get_logger();
301  
302 # Temporary global array reference, used to hold the file analysis information,
303 # for the baseline and check operations.
304 my $file_analysis = [ ];
305  
306 # The global delimeter used for storing file analysis information inside
307 # a single string.
308 our $DELIMETER = ":";
309  
310 # Make Dumper format more terse.
311 $Data::Dumper::Terse = 1;
312 $Data::Dumper::Indent = 0;
313  
314 =pod
315  
316 =head1 DEFAULT PARAMETER LIST
317  
318 When a Filesystem B<$object> is instantiated using the B<new()> function,
319 the following parameters are supplied default values. Each value
320 can be overridden by specifying the new (key => value) pair into the
321 B<new()> function, as arguments.
322  
323 =head2 bypass_baseline
324  
325 =over 4
326  
327 When set to 1, the object will forgo any type of initial baselining
328 process, upon initialization. Otherwise, baselining will occur
329 as normal, upon initialization.
330  
331 =back
332  
333 =head2 baseline_analysis
334  
335 =over 4
336  
337 An array of hashtables used to hold the file analysis information,
338 for the baseline filesystem operation.
339  
340 =back
341  
342 =head2 monitored_directories
343  
344 =over 4
345  
346 The base list of drives, directories, and/or files to monitor.
347  
348 =back
349  
350 =head2 ignored_entries
351  
352 =over 4
353  
354 The list of regular expressions that match drives, directories,
355 and/or files to exclude from analysis.
356  
357 =back
358  
359 =cut
360  
361 my %PARAMS = (
362 # When set to 1, the object will forgo any type of initial baselining
363 # process, upon initialization. Otherwise, baselining will occur
364 # as normal, upon initialization.
365 bypass_baseline => 0,
366  
367 # An array of hashtables used to hold the file analysis information,
368 # for the baseline filesystem operation.
369 baseline_analysis => [ ],
370  
371 # The base list of drives/directories/files to monitor.
372 monitored_directories => getVar(name => 'directories_to_check')->{name},
373  
374 # The list of drives/directories/files to ignore.
375 ignored_entries => getVar(name => 'exclude_list')->{regex},
376 );
377  
378 #######################################################################
379 # Private Methods Implemented #
380 #######################################################################
381  
382 # A helper function, designed to baseline the filesystem.
383 #
384 # Input: self
385 # Output: none
386 sub _baseline {
387 # Extract arguments.
388 my ($self) = @_;
389  
390 # Convert monitored directories to a Cygwin-style format.
391 my @search_dirs;
392 foreach (@{$self->{monitored_directories}}) {
393 push (@search_dirs, posixpath($_));
394 }
395  
396 # Save converted results back into our object.
397 $self->{monitored_directories} = \@search_dirs;
398
399 # Convert ignored entires to a Cygwin-style format.
400 my @ignored_entries;
401 foreach (@{$self->{ignored_entries}}) {
402 push (@ignored_entries, posixpath($_));
403 }
404  
405 # Save converted results back into our object.
406 $self->{ignored_entries} = \@ignored_entries;
407  
408 # Analyze filesystem.
409 $self->_analyze();
410  
411 # Save analyzed results to object's baseline array.
412 $self->{baseline_analysis} = $file_analysis;
413 }
414  
415 # A helper function, designed to analyze the filesystem
416 # and create entries of filesystem objects.
417 #
418 # Input: self
419 # Output: none
420 sub _analyze {
421 # Extract arguments.
422 my ($self) = @_;
423  
424 # Clear previous analysis array.
425 $file_analysis = [ ];
426  
427 # Search the filesystem.
428 # Trap and ignore all warnings from the find operation.
429 {
430 no warnings;
431 find(\&_processFile, @{$self->{monitored_directories}});
432 };
433 }
434  
435 # A helper callback function, designed to populate the $file_analysis
436 # global array reference with hashtable entries about filesystem objects.
437 #
438 # Input: none
439 # Output: none
440 sub _processFile {
441 # Get file stats.
442 my @attr = stat($File::Find::name);
443  
444 # Create a new entry.
445 my $entry = {
446 name => defined($File::Find::name) ? $File::Find::name : 'UNKNOWN',
447 size => defined($attr[7]) ? $attr[7] : 0,
448 mtime => defined($attr[9]) ? $attr[9] : 0,
449 };
450  
451 # Push entry onto analysis array.
452 push (@{$file_analysis}, $entry);
453 }
454  
455 # A helper callback function, designed to stringify each filesystem
456 # entry object. Used by Algorithm::Diff operations.
457 #
458 # Input: filesystem entry
459 # Output: unique string
460 sub _toString {
461 # Extract arguments.
462 my ($entry) = @_;
463  
464 # Check to make sure that each entry is defined.
465 my $name = defined($entry->{name}) ? $entry->{name} : "";
466 my $size = defined($entry->{size}) ? $entry->{size} : "";
467 my $mtime = defined($entry->{mtime}) ? $entry->{mtime} : "";
468  
469 my $string = $name . $DELIMETER .
470 $size . $DELIMETER .
471 $mtime . $DELIMETER;
472  
473 return $string;
474 }
475  
476 # A helper function, designed to take the output of an Algorithm::Diff object
477 # and return a list of changes found in the filesystem.
478 #
479 # Input: Algorithm::Diff object
480 # Output: Array reference of hashtables
481 # Notes: This function returns hashtables in the following
482 # format:
483 #
484 # $changes = [ {
485 # # Indicates if the filesystem entry was deleted,
486 # # added, or changed.
487 # 'status' => $STATUS_DELETED | $STATUS_ADDED | $STATUS_MODIFIED,
488 #
489 # # If the entry has been added/changed, then this
490 # # hashtable contains the file/directory's new information.
491 # 'new' => {
492 # 'name' => 'C:\WINDOWS\SYSTEM32...',
493 # 'size' => 1263, # in bytes
494 # 'mtime' => 1178135092, # modification time, seconds since epoch
495 # },
496 #
497 # # If the entry has been deleted/changed, then this
498 # # hashtable contains the file/directory's old information.
499 # 'old' => {
500 # 'name' => 'C:\WINDOWS\SYSTEM32...',
501 # 'size' => 802, # in bytes
502 # 'mtime' => 1178135028, # modification time, seconds since epoch
503 # },
504 # }, ]
505 sub _diff {
506  
507 # Extract arguments.
508 my ($self, $diff) = @_;
509  
510 # List of changes found.
511 my $ret = [ ];
512  
513 # Temporary variables.
514 my $index;
515 my $old_entry;
516 my $new_entry;
517  
518 while ($diff->Next()) {
519 # Ignore all matches.
520 next if $diff->Same();
521  
522 # Check if entries were deleted.
523 if(!$diff->Items(2)) {
524 for ($diff->Items(1)) {
525 # Make Dumper format more terse.
526 $Data::Dumper::Terse = 1;
527 $Data::Dumper::Indent = 0;
528 $LOG->debug("File Deleted - " . Dumper($_));
529  
530 push (@{$ret}, {
531 'status' => $STATUS_DELETED,
532 'old' => $_,
533 });
534 }
535 # Check if entries were added.
536 } elsif(!$diff->Items(1)) {
537 for ($diff->Items(2)) {
538 # Make Dumper format more terse.
539 $Data::Dumper::Terse = 1;
540 $Data::Dumper::Indent = 0;
541 $LOG->debug("File Added - " . Dumper($_));
542  
543 push (@{$ret}, {
544 'status' => $STATUS_ADDED,
545 'new' => $_,
546 });
547 }
548 # Check if entries are different.
549 } else {
550 # This is the complicated case where there may be a single change or
551 # multiple changes which are contiguous
552 my $size_of_1 = scalar($diff->Items(1));
553 my $size_of_2 = scalar($diff->Items(2));
554  
555 # There are multiples, but the same number from each scan
556 if ($size_of_1 == $size_of_2) {
557  
558 $index = 0;
559 for ($diff->Items(1)) {
560 $old_entry = $_;
561 $new_entry = ($diff->Items(2))[$index];
562  
563 # If the entry names are the same, then we know the contents
564 # of the entry have changed.
565 if ($old_entry->{name} eq $new_entry->{name}) {
566  
567 # Make Dumper format more terse.
568 $Data::Dumper::Terse = 1;
569 $Data::Dumper::Indent = 0;
570 $LOG->debug("File Changed - Old - " . Dumper($old_entry) .
571 " - New - " . Dumper($new_entry));
572  
573 push (@{$ret}, {
574 'status' => $STATUS_MODIFIED,
575 'old' => $old_entry,
576 'new' => $new_entry,
577 });
578 # Otherwise, the old entry got deleted and the new entry got
579 # added.
580 } else {
581 # Make Dumper format more terse.
582 $Data::Dumper::Terse = 1;
583 $Data::Dumper::Indent = 0;
584 $LOG->debug("File Deleted - " . Dumper($old_entry));
585 $LOG->debug("File Added - " . Dumper($new_entry));
586  
587 push (@{$ret}, {
588 'status' => $STATUS_DELETED,
589 'old' => $old_entry,
590 });
591 push (@{$ret}, {
592 'status' => $STATUS_ADDED,
593 'new' => $new_entry,
594 });
595 }
596  
597 $index++;
598 }
599 # There are more contiguous entries in the baseline.
600 } elsif ($size_of_1 > $size_of_2) {
601 $index = 0;
602 for ($diff->Items(1)) {
603 $old_entry = $_;
604 $new_entry = ($diff->Items(2))[$index];
605  
606 # If the entry names are the same, then we know the contents
607 # of the entry have changed.
608 if (defined($new_entry) && ($old_entry->{name} eq $new_entry->{name})) {
609 # Make Dumper format more terse.
610 $Data::Dumper::Terse = 1;
611 $Data::Dumper::Indent = 0;
612 $LOG->debug("File Changed - Old - " . Dumper($old_entry) .
613 " - New - " . Dumper($new_entry));
614  
615 push (@{$ret}, {
616 'status' => $STATUS_MODIFIED,
617 'old' => $old_entry,
618 'new' => $new_entry,
619 });
620 $index++;
621 # Otherwise, the old entry got deleted and the new entry got
622 # added (possibly).
623 } else {
624 # Make Dumper format more terse.
625 $Data::Dumper::Terse = 1;
626 $Data::Dumper::Indent = 0;
627 $LOG->debug("File Deleted - " . Dumper($old_entry));
628  
629 push (@{$ret}, {
630 'status' => $STATUS_DELETED,
631 'old' => $old_entry,
632 });
633 # Mark the new entry as added, if and only if it's defined
634 # and NOT the final new entry in this chunk.
635 if (defined($new_entry) && ($index < ($size_of_2 - 1))) {
636 # Make Dumper format more terse.
637 $Data::Dumper::Terse = 1;
638 $Data::Dumper::Indent = 0;
639 $LOG->debug("File Added - " . Dumper($new_entry));
640 push (@{$ret}, {
641 'status' => $STATUS_ADDED,
642 'new' => $new_entry,
643 });
644 $index++;
645 }
646 }
647 }
648 # If we still have a final new entry to process, and we're finished
649 # with all old entries, then we know the new entry was a filesystem
650 # addition.
651 if ($index < $size_of_2) {
652 # Make Dumper format more terse.
653 $Data::Dumper::Terse = 1;
654 $Data::Dumper::Indent = 0;
655 $LOG->debug("File Added - " . Dumper($new_entry));
656 push (@{$ret}, {
657 'status' => $STATUS_ADDED,
658 'new' => $new_entry,
659 });
660 }
661 # There are more contiguous entries in the second scan.
662 } else {
663 $index = 0;
664 for ($diff->Items(2)) {
665 $old_entry = ($diff->Items(1))[$index];
666 $new_entry = $_;
667  
668 # If the entry names are the same, then we know the contents
669 # of the entry have changed.
670 if (defined($old_entry) && ($old_entry->{name} eq $new_entry->{name})) {
671 # Make Dumper format more terse.
672 $Data::Dumper::Terse = 1;
673 $Data::Dumper::Indent = 0;
674 $LOG->debug("File Changed - Old - " . Dumper($old_entry) .
675 " - New - " . Dumper($new_entry));
676 push (@{$ret}, {
677 'status' => $STATUS_MODIFIED,
678 'old' => $old_entry,
679 'new' => $new_entry,
680 });
681 $index++;
682 # Otherwise, the old entry got (possibly) deleted and the new entry got
683 # added.
684 } else {
685 # Make Dumper format more terse.
686 $Data::Dumper::Terse = 1;
687 $Data::Dumper::Indent = 0;
688 $LOG->debug("File Added - " . Dumper($new_entry));
689 push (@{$ret}, {
690 'status' => $STATUS_ADDED,
691 'new' => $new_entry,
692 });
693 # Mark the old entry as deleted, if and only if it's defined
694 # and NOT the final old entry in this chunk.
695 if (defined($old_entry) && ($index < ($size_of_1 - 1))) {
696 # Make Dumper format more terse.
697 $Data::Dumper::Terse = 1;
698 $Data::Dumper::Indent = 0;
699 $LOG->debug("File Deleted - " . Dumper($old_entry));
700 push (@{$ret}, {
701 'status' => $STATUS_DELETED,
702 'old' => $old_entry,
703 });
704 $index++;
705 }
706 }
707 }
708 # If we still have a final old entry to process, and we're finished
709 # with all the new entries, then we know the old entry was a filesystem
710 # deletion.
711 if ($index < $size_of_1) {
712 # Make Dumper format more terse.
713 $Data::Dumper::Terse = 1;
714 $Data::Dumper::Indent = 0;
715 $LOG->debug("File Deleted - " . Dumper($old_entry));
716 push (@{$ret}, {
717 'status' => $STATUS_DELETED,
718 'old' => $old_entry,
719 });
720 }
721 }
722 }
723 }
724 return $ret;
725 }
726  
727 # A helper function, designed to filter out changes that should be
728 # ignored and correlate matching add/delete entries as changes,
729 # instead of separate add/delete entries.
730 #
731 # Input: Array reference of hashtables
732 # Output: Array reference of hashtables (filtered)
733 # Notes: This function expects and returns hashtables in the following
734 # format:
735 #
736 # $changes = [ {
737 # # Indicates if the filesystem entry was deleted,
738 # # added, or changed.
739 # 'status' => $STATUS_DELETED | $STATUS_ADDED | $STATUS_MODIFIED,
740 #
741 # # If the entry has been added/changed, then this
742 # # hashtable contains the file/directory's new information.
743 # 'new' => {
744 # 'name' => 'C:\WINDOWS\SYSTEM32...',
745 # 'size' => 1263, # in bytes
746 # 'mtime' => 1178135092, # modification time, seconds since epoch
747 # },
748 #
749 # # If the entry has been deleted/changed, then this
750 # # hashtable contains the file/directory's old information.
751 # 'old' => {
752 # 'name' => 'C:\WINDOWS\SYSTEM32...',
753 # 'size' => 802, # in bytes
754 # 'mtime' => 1178135028, # modification time, seconds since epoch
755 # },
756 # }, ]
757 sub _filter {
758 my ($self, $changes) = @_;
759 my $ret = [];
760  
761 my $entries_by_name = { };
762 foreach (@{$changes}) {
763 # Extract the file name from each entry.
764 my $name = undef;
765 if (($_->{status} == $STATUS_ADDED) or ($_->{status} == $STATUS_MODIFIED)) {
766 $name = $_->{'new'}->{name};
767 } else {
768 $name = $_->{'old'}->{name};
769 }
770
771 # Check to make sure a name exists, skip if not found.
772 if (!defined($name)) {
773 next;
774 }
775  
776 # Set an exclude flag.
777 my $exclude_flag = 0;
778 foreach (@{$self->{ignored_entries}}) {
779 if ($name =~ /^$_$/i) {
780 $exclude_flag = 1;
781 last; # We only need to set the flag once.
782 }
783 }
784
785 # Skip if excluded.
786 if ($exclude_flag) {
787 $LOG->debug("Excluding '" . win32path($name) . "' from integrity checks.");
788 next;
789 }
790  
791 # Check to see if an entry with the same name has already
792 # been pushed onto our return array.
793 if (exists($entries_by_name->{$name}) &&
794 defined($entries_by_name->{$name})) {
795  
796 $LOG->debug("Correlating multiple filesystem changes for '" . $name . "'.");
797  
798 my $prev_entry = $entries_by_name->{$name};
799 my $curr_entry = $_;
800  
801 # Sanity check.
802 if ((($prev_entry->{status} == $STATUS_MODIFIED) ||
803 ($curr_entry->{status} == $STATUS_MODIFIED)) ||
804 (($prev_entry->{status} == $STATUS_ADDED) &&
805 ($curr_entry->{status} == $STATUS_ADDED)) ||
806 (($prev_entry->{status} == $STATUS_DELETED) &&
807 ($curr_entry->{status} == $STATUS_DELETED))) {
808 $LOG->error("Duplicate filesystem change entries were found. " .
809 "Previous Entry - " . Dumper($prev_entry) . " - ".
810 "Current Entry - " . Dumper($curr_entry));
811 push (@{$ret}, $_);
812 next;
813 }
814  
815 # If the previous entry was added and the current
816 # was deleted.
817 if (($prev_entry->{status} == $STATUS_ADDED) &&
818 ($curr_entry->{status} == $STATUS_DELETED)) {
819 $prev_entry->{status} = $STATUS_MODIFIED;
820 $prev_entry->{old} = $curr_entry->{old};
821  
822 # Otherwise, if the previous entry was deleted and the
823 # current was added.
824 } else {
825 $prev_entry->{status} = $STATUS_MODIFIED;
826 $prev_entry->{'new'} = $curr_entry->{'new'};
827 }
828  
829 } else {
830 # The entry is completely new, so record it.
831 $entries_by_name->{$name} = $_;
832  
833 # And push it onto our return array.
834 push (@{$ret}, $_);
835 }
836 }
837 return $ret;
838 }
839  
840 # A helper function, designed to manipulate the array of changes into
841 # a format that is expected by the check() function -- collecting
842 # more forensic data about each change along the way.
843 #
844 # Input: Array reference of hashtables
845 # Output: Array reference of hashtables (manipulated)
846 # Notes: This function expects hashtables in the following
847 # format:
848 #
849 # $inputChanges = [ {
850 # # Indicates if the filesystem entry was deleted,
851 # # added, or changed.
852 # 'status' => $STATUS_DELETED | $STATUS_ADDED | $STATUS_MODIFIED,
853 #
854 # # If the entry has been added/changed, then this
855 # # hashtable contains the file/directory's new information.
856 # 'new' => {
857 # 'name' => 'C:\WINDOWS\SYSTEM32...',
858 # 'size' => 1263, # in bytes
859 # 'mtime' => 1178135092, # modification time, seconds since epoch
860 # },
861 #
862 # # If the entry has been deleted/changed, then this
863 # # hashtable contains the file/directory's old information.
864 # 'old' => {
865 # 'name' => 'C:\WINDOWS\SYSTEM32...',
866 # 'size' => 802, # in bytes
867 # 'mtime' => 1178135028, # modification time, seconds since epoch
868 # },
869 # }, ]
870 #
871 # And outputs hashtables in the following format:
872 #
873 # $outputChanges = [ {
874 # # Indicates if the filesystem entry was deleted,
875 # # added, or changed.
876 # 'status' => $STATUS_DELETED | $STATUS_ADDED | $STATUS_MODIFIED,
877 # 'name' => 'C:\WINDOWS\SYSTEM32...',
878 # 'mtime' => 'YYYY-MM-DD HH:MM:SS', # new mtime for added/modified files;
879 # # old mtime for deleted files
880 #
881 # # content will only exist for added/modified files
882 # 'content' => {
883 # 'size' => 1263, # size of new content
884 # 'type' => 'application/octet-stream', # type of new content
885 # 'md5' => 'b1946ac92492d2347c6235b4d2611184', # md5 of new content
886 # 'sha1' => 'f572d396fae9206628714fb2ce00f72e94f2258f', # sha1 of new content
887 # },
888 # }, ]
889 #
890 sub _prepare {
891 my ($self, $changes) = @_;
892 my $ret = [];
893  
894 $LOG->debug("Preparing changes.");
895  
896 my $md5_ctx = Digest::MD5->new();
897 my $sha1_ctx = Digest::SHA->new("1");
898 my $type_ctx = File::Type->new();
899  
900 foreach my $entry (@{$changes}) {
901 # Construct a new entry in the new format.
902 my $newEntry = {
903 'status' => $entry->{'status'},
904 };
905  
906 # Figure out which type of entry it is.
907 if ($entry->{'status'} == $STATUS_DELETED) {
908 # Convert Filename
909 $newEntry->{'name'} = _convertFilename($entry->{'old'}->{'name'});
910 $newEntry->{'mtime'} = _convertTime($entry->{'old'}->{'mtime'});
911
912 $LOG->debug("Filename: " . $newEntry->{'name'});
913 } else {
914 $newEntry->{'name'} = $entry->{'new'}->{'name'};
915 $newEntry->{'mtime'} = _convertTime($entry->{'new'}->{'mtime'});
916  
917 $LOG->debug("Filename: " . $newEntry->{'name'});
918  
919 # Create a new file handle.
920 my $fh = IO::File->new($newEntry->{'name'}, "r");
921 my $md5 = $HASH_UNKNOWN;
922 my $sha1 = $HASH_UNKNOWN;
923 my $type = $TYPE_UNKNOWN;
924  
925 # Check to make sure the new/changed file exists.
926 if (defined($fh)) {
927 # If the entry is a directory.
928 if (-d $fh) {
929 $type = "directory";
930 undef $fh;
931  
932 # XXX: We currently skip all entries that
933 # only correspond to directories.
934 # This is a known limitation.
935 next;
936  
937 # If the entry is a symlink.
938 } elsif (-l $newEntry->{'name'}) {
939 $type = "symlink";
940 undef $fh;
941  
942 # XXX: We currently skip all entries that
943 # only correspond to symlinks.
944 # This is a known limitation.
945 next;
946  
947 # If the entry is a file.
948 } else {
949 # Compute MD5 Checksum.
950 $md5_ctx->addfile($fh);
951 $md5 = $md5_ctx->hexdigest();
952  
953 # Rewind file handle.
954 seek($fh, 0, 0);
955  
956 # Compute SHA1 Checksum.
957 $sha1_ctx->addfile($fh);
958 $sha1 = $sha1_ctx->hexdigest();
959  
960 # Close the file handle.
961 undef $fh;
962  
963 # Compute File Type.
964 $type = $type_ctx->mime_type($newEntry->{'name'});
965 }
966 }
967
968 # Populate the content, accordingly.
969 $newEntry->{'content'} = {
970 'size' => $entry->{'new'}->{'size'},
971 'type' => $type,
972 'md5' => $md5,
973 'sha1' => $sha1,
974 };
975  
976 # Convert Filename
977 $newEntry->{'name'} = _convertFilename($newEntry->{'name'});
978 }
979  
980 # Finally, push it onto our return array.
981 push (@{$ret}, $newEntry);
982 }
983 return $ret;
984 }
985  
986 # Helper function, designed to convert seconds since epoch to
987 # an ISO 8601 date time format.
988 #
989 # Input: epoch
990 # Output: iso8601 date/time
991 sub _convertTime {
992 my $dt = DateTime->from_epoch(epoch => shift);
993 return $dt->ymd('-') . " " . $dt->hms(':');
994 }
995  
996 # Helper function, designed to convert Cygwin filename paths to
997 # a Windows format, where the output is always lowercase.
998 #
999 # Input: cygwin filename path
1000 # Output: absolute windows filename path
1001 sub _convertFilename {
1002 my $path = shift;
1003  
1004 # Unfortunately Filesys::CygwinPaths seems to like
1005 # to follow symbolic links, when resolving win32 paths.
1006 # This is bad. To counter this, we make sure the filename
1007 # we give it isn't a valid symlink so that it can properly
1008 # perform the conversion.
1009 if (-l $path) {
1010 $path .= "*";
1011 $path = lc(fullwin32path($path));
1012 chop($path);
1013 return $path;
1014 } else {
1015 return lc(fullwin32path($path));
1016 }
1017 }
1018  
1019 #######################################################################
1020 # Public Methods Implemented #
1021 #######################################################################
1022  
1023 =pod
1024  
1025 =head1 METHODS IMPLEMENTED
1026  
1027 The following functions have been implemented by any Filesystem object.
1028  
1029 =head2 HoneyClient::Agent::Integrity::Filesystem->new($param => $value, ...)
1030  
1031 =over 4
1032  
1033 Creates a new Filesystem object, which contains a hashtable
1034 containing any of the supplied "param => value" arguments. Upon
1035 creation, the Filesystem object performs a baseline of the Windows
1036 filesystem.
1037  
1038 I<Inputs>:
1039 B<$param> is an optional parameter variable.
1040 B<$value> is $param's corresponding value.
1041  
1042 Note: If any $param(s) are supplied, then an equal number of
1043 corresponding $value(s) B<must> also be specified.
1044  
1045 I<Output>: The instantiated Filesystem B<$object>, fully initialized.
1046  
1047 =back
1048  
1049 =begin testing
1050  
1051 diag("These tests will create temporary files in /tmp. Be sure to cleanup this directory, if any of these tests fail.");
1052  
1053 # Create a generic Filesystem object, with test state data.
1054 my $filesystem = HoneyClient::Agent::Integrity::Filesystem->new(test => 1, bypass_baseline => 1);
1055 is($filesystem->{test}, 1, "new(test => 1, bypass_baseline => 1)") or diag("The new() call failed.");
1056 isa_ok($filesystem, 'HoneyClient::Agent::Integrity::Filesystem', "new(test => 1, bypass_baseline => 1)") or diag("The new() call failed.");
1057  
1058 diag("Performing baseline check of the filesystem; this may take some time...");
1059  
1060 # Perform baseline.
1061 $filesystem = HoneyClient::Agent::Integrity::Filesystem->new();
1062 isa_ok($filesystem, 'HoneyClient::Agent::Integrity::Filesystem', "new()") or diag("The new() call failed.");
1063  
1064 =end testing
1065  
1066 =cut
1067  
1068 sub new {
1069 # - This function takes in an optional hashtable,
1070 # that contains various key => 'value' configuration
1071 # parameters.
1072 #
1073 # - For each parameter given, it overwrites any corresponding
1074 # parameters specified within the default hashtable, %PARAMS,
1075 # with custom entries that were given as parameters.
1076 #
1077 # - Finally, it returns a blessed instance of the
1078 # merged hashtable, as an 'object'.
1079  
1080 # Get the class name.
1081 my $self = shift;
1082  
1083 # Get the rest of the arguments, as a hashtable.
1084 # Hash-based arguments are used, since HoneyClient::Util::SOAP is unable to handle
1085 # hash references directly. Thus, flat hashtables are used throughout the code
1086 # for consistency.
1087 my %args = @_;
1088  
1089 # Check to see if the class name is inherited or defined.
1090 my $class = ref($self) || $self;
1091  
1092 # Initialize default parameters.
1093 $self = { };
1094 my %params = %{dclone(\%PARAMS)};
1095 @{$self}{keys %params} = values %params;
1096  
1097 # Now, overwrite any default parameters that were redefined
1098 # in the supplied arguments.
1099 @{$self}{keys %args} = values %args;
1100  
1101 # Now, assign our object the appropriate namespace.
1102 bless $self, $class;
1103  
1104 # Perform baselining, if not bypassed.
1105 if (!$self->{'bypass_baseline'}) {
1106 $LOG->info("Baselining filesystem.");
1107 $self->_baseline();
1108 }
1109  
1110 # Finally, return the blessed object.
1111 return $self;
1112 }
1113  
1114 =pod
1115  
1116 =head2 $object->check(no_prepare => $no_prepare)
1117  
1118 =over 4
1119  
1120 Checks the filesystem for various changes, based upon
1121 the filesystem baseline, when the new() method was invoked.
1122  
1123 I<Inputs>:
1124 B<$no_prepare> is an optional parameter, specifying the output
1125 format of the changes found.
1126  
1127 I<Output>:
1128 B<$changes>, which is an array of hashtable references, where each
1129 hashtable has the following format:
1130  
1131 If $no_prepare == 1, then the format will be:
1132  
1133 $changes = [ {
1134 # Indicates if the filesystem entry was deleted,
1135 # added, or changed.
1136 'status' => $STATUS_DELETED | $STATUS_ADDED | $STATUS_MODIFIED,
1137  
1138 # If the entry has been added/changed, then this
1139 # hashtable contains the file/directory's new information.
1140 'new' => {
1141 'name' => 'C:\WINDOWS\SYSTEM32...',
1142 'size' => 1263, # in bytes
1143 'mtime' => 1178135092, # modification time, seconds since epoch
1144 },
1145  
1146 # If the entry has been deleted/changed, then this
1147 # hashtable contains the file/directory's old information.
1148 'old' => {
1149 'name' => 'C:\WINDOWS\SYSTEM32...',
1150 'size' => 802, # in bytes
1151 'mtime' => 1178135028, # modification time, seconds since epoch
1152 },
1153 }, ]
1154  
1155 Otherwise, the format will be:
1156  
1157 $changes = [ {
1158 # Indicates if the filesystem entry was deleted,
1159 # added, or changed.
1160 'status' => $STATUS_DELETED | $STATUS_ADDED | $STATUS_MODIFIED,
1161 'name' => 'C:\WINDOWS\SYSTEM32...',
1162 'mtime' => 'YYYY-MM-DD HH:MM:SS', # new mtime for added/modified files;
1163 # old mtime for deleted files
1164  
1165 # content will only exist for added/modified files
1166 'content' => {
1167 'size' => 1263, # size of new content
1168 'type' => 'application/octet-stream', # type of new content
1169 'md5' => 'b1946ac92492d2347c6235b4d2611184', # md5 of new content
1170 'sha1' => 'f572d396fae9206628714fb2ce00f72e94f2258f', # sha1 of new content
1171 },
1172 }, ]
1173  
1174 I<Notes>:
1175 If $no_prepare != 1 or $no_prepare == undef, then the outputted changes will B<NEVER> refer to
1176 any directories. All the changes will correspond to individual files.
1177  
1178 =back
1179  
1180 =begin testing
1181  
1182 ### Get the test directory to monitor.
1183 my $monitor_dir = $ENV{PWD} . "/" . getVar(name => "monitor_dir",
1184 namespace => "HoneyClient::Agent::Integrity::Filesystem::Test");
1185  
1186 ### Seed the directory with test data.
1187 my $delete_file = $monitor_dir . "/" . "to_delete.txt";
1188 my $change_file = $monitor_dir . "/" . "to_change.txt";
1189 my $add_file = $monitor_dir . "/" . "to_add.txt";
1190  
1191 my $delete_string = "Test string for the file to be deleted.";
1192 my $add_string = "Test string for the added file.";
1193 my $change_string1 = "Original test string for the file to be changed.";
1194 my $change_string2 = "Final test string for the changed file.";
1195  
1196 my @file_attr;
1197  
1198 open(DELETE_FILE, ">", $delete_file) or BAIL_OUT("Unable to create test file '" . $delete_file . "'.");
1199 print DELETE_FILE $delete_string;
1200 close DELETE_FILE;
1201  
1202 @file_attr = stat($delete_file);
1203 my $delete_file_size = $file_attr[7];
1204 my $delete_file_mtime = $file_attr[9];
1205  
1206 open(CHANGE_FILE, ">", $change_file) or BAIL_OUT("Unable to create test file '" . $change_file . "'.");
1207 print CHANGE_FILE $change_string1;
1208 close CHANGE_FILE;
1209  
1210 @file_attr = stat($change_file);
1211 my $change_file_size1 = $file_attr[7];
1212 my $change_file_mtime1 = $file_attr[9];
1213  
1214 # Make sure the $add_file isn't present.
1215 unlink($add_file);
1216  
1217 ### Perform baseline.
1218 my $filesystem = HoneyClient::Agent::Integrity::Filesystem->new(monitored_directories => [ $monitor_dir ],
1219 ignored_entries => [ $monitor_dir ]);
1220  
1221 ### Change data in our test directory on the filesystem.
1222 # Delete the target test file.
1223 if (!unlink($delete_file)) {
1224 fail("Unable to delete test file '" . $delete_file . "'.");
1225 }
1226  
1227 # Add the target test file.
1228 open(ADD_FILE, ">", $add_file) or BAIL_OUT("Unable to create test file '" . $add_file . "'.");
1229 print ADD_FILE $add_string;
1230 close ADD_FILE;
1231  
1232 my $md5_ctx = Digest::MD5->new();
1233 my $sha1_ctx = Digest::SHA->new("1");
1234 my $type_ctx = File::Type->new();
1235  
1236 my $add_fh = IO::File->new($add_file, "r");
1237 $md5_ctx->addfile($add_fh);
1238 my $add_file_md5 = $md5_ctx->hexdigest();
1239 seek($add_fh, 0, 0);
1240 $sha1_ctx->addfile($add_fh);
1241 my $add_file_sha1 = $sha1_ctx->hexdigest();
1242 undef $add_fh;
1243 my $add_file_type = $type_ctx->mime_type($add_file);
1244  
1245 @file_attr = stat($add_file);
1246 my $add_file_size = $file_attr[7];
1247 my $add_file_mtime = $file_attr[9];
1248  
1249 # Change the target test file.
1250 open(CHANGE_FILE, ">", $change_file) or BAIL_OUT("Unable to create test file '" . $change_file . "'.");
1251 print CHANGE_FILE $change_string2;
1252 close CHANGE_FILE;
1253  
1254 my $change_fh = IO::File->new($change_file, "r");
1255 $md5_ctx->addfile($change_fh);
1256 my $change_file_md5 = $md5_ctx->hexdigest();
1257 seek($change_fh, 0, 0);
1258 $sha1_ctx->addfile($change_fh);
1259 my $change_file_sha1 = $sha1_ctx->hexdigest();
1260 undef $change_fh;
1261 my $change_file_type = $type_ctx->mime_type($change_file);
1262  
1263 @file_attr = stat($change_file);
1264 my $change_file_size2 = $file_attr[7];
1265 my $change_file_mtime2 = $file_attr[9];
1266  
1267 ### Perform check.
1268 my $foundChanges = $filesystem->check(no_prepare => 1);
1269  
1270 # Uncomment these lines, if you want to see more
1271 # detailed information about the changes found.
1272 #$Data::Dumper::Terse = 0;
1273 #$Data::Dumper::Indent = 1;
1274 #diag(Dumper($foundChanges));
1275  
1276 ### Verify changes.
1277 my $expectedChanges = [
1278 {
1279 'status' => $HoneyClient::Agent::Integrity::Filesystem::STATUS_MODIFIED,
1280 'new' => {
1281 'name' => $change_file,
1282 'size' => $change_file_size2,
1283 'mtime' => $change_file_mtime2,
1284 },
1285 'old' => {
1286 'name' => $change_file,
1287 'size' => $change_file_size1,
1288 'mtime' => $change_file_mtime1,
1289 },
1290 },
1291 {
1292 'status' => $HoneyClient::Agent::Integrity::Filesystem::STATUS_ADDED,
1293 'new' => {
1294 'name' => $add_file,
1295 'size' => $add_file_size,
1296 'mtime' => $add_file_mtime,
1297 },
1298 },
1299 {
1300 'status' => $HoneyClient::Agent::Integrity::Filesystem::STATUS_DELETED,
1301 'old' => {
1302 'name' => $delete_file,
1303 'size' => $delete_file_size,
1304 'mtime' => $delete_file_mtime,
1305 },
1306 },
1307 ];
1308  
1309 is_deeply($foundChanges, $expectedChanges, "check(no_prepare => 1)") or diag("The check() call failed.");
1310  
1311 ### Perform check.
1312 $foundChanges = $filesystem->check();
1313  
1314 # Uncomment these lines, if you want to see more
1315 # detailed information about the changes found.
1316 #$Data::Dumper::Terse = 0;
1317 #$Data::Dumper::Indent = 1;
1318 #diag(Dumper($foundChanges));
1319  
1320 ### Verify changes.
1321 $expectedChanges = [
1322 {
1323 'status' => $HoneyClient::Agent::Integrity::Filesystem::STATUS_MODIFIED,
1324 'name' => HoneyClient::Agent::Integrity::Filesystem::_convertFilename($change_file),
1325 'mtime' => HoneyClient::Agent::Integrity::Filesystem::_convertTime($change_file_mtime2),
1326 'content' => {
1327 'size' => $change_file_size2,
1328 'type' => $change_file_type,
1329 'sha1' => $change_file_sha1,
1330 'md5' => $change_file_md5,
1331 },
1332 },
1333 {
1334 'status' => $HoneyClient::Agent::Integrity::Filesystem::STATUS_ADDED,
1335 'name' => HoneyClient::Agent::Integrity::Filesystem::_convertFilename($add_file),
1336 'mtime' => HoneyClient::Agent::Integrity::Filesystem::_convertTime($add_file_mtime),
1337 'content' => {
1338 'size' => $add_file_size,
1339 'type' => $add_file_type,
1340 'sha1' => $add_file_sha1,
1341 'md5' => $add_file_md5,
1342 },
1343 },
1344 {
1345 'status' => $HoneyClient::Agent::Integrity::Filesystem::STATUS_DELETED,
1346 'name' => HoneyClient::Agent::Integrity::Filesystem::_convertFilename($delete_file),
1347 'mtime' => HoneyClient::Agent::Integrity::Filesystem::_convertTime($delete_file_mtime),
1348 },
1349 ];
1350  
1351 is_deeply($foundChanges, $expectedChanges, "check()") or diag("The check() call failed.");
1352  
1353 ### Clean up test data.
1354 close DELETE_FILE;
1355 unlink($delete_file);
1356  
1357 close CHANGE_FILE;
1358 unlink($change_file);
1359  
1360 close ADD_FILE;
1361 unlink($add_file);
1362  
1363 =end testing
1364  
1365 =cut
1366  
1367 sub check {
1368  
1369 # Extract arguments.
1370 my ($self, %args) = @_;
1371  
1372 # Sanity check: Make sure we've been fed an object.
1373 unless (ref($self)) {
1374 $LOG->error("Error: Function must be called in reference to a " .
1375 __PACKAGE__ . "->new() object!");
1376 Carp::croak "Error: Function must be called in reference to a " .
1377 __PACKAGE__ . "->new() object!\n";
1378 }
1379  
1380 # Log resolved arguments.
1381 $LOG->debug(sub {
1382 # Make Dumper format more terse.
1383 $Data::Dumper::Terse = 1;
1384 $Data::Dumper::Indent = 0;
1385 Dumper(\%args);
1386 });
1387  
1388 # Sanity checks; check if any args were specified.
1389 my $argsExist = scalar(%args);
1390  
1391 # Analyze the filesystem.
1392 $LOG->info("Analyzing filesystem.");
1393 $self->_analyze();
1394  
1395 # Compare analysis with baseline.
1396 $LOG->info("Checking for filesystem changes.");
1397 my $changes = $self->_diff(Algorithm::Diff->new($self->{baseline_analysis},
1398 $file_analysis,
1399 { keyGen => \&_toString }));
1400 # Filter results.
1401 $changes = $self->_filter($changes);
1402 if (scalar(@{$changes})) {
1403 $LOG->warn("Filesystem changes found.");
1404 } else {
1405 $LOG->info("No filesystem changes found.");
1406 }
1407  
1408 # Prepare results, if not directed otherwise.
1409 if (!$argsExist ||
1410 !exists($args{'no_prepare'}) ||
1411 !defined($args{'no_prepare'}) ||
1412 !$args{'no_prepare'}) {
1413 $changes = $self->_prepare($changes);
1414 }
1415  
1416 # Return formatted results.
1417 return $changes;
1418 }
1419  
1420 1;
1421  
1422 =pod
1423  
1424 =head1 BUGS & ASSUMPTIONS
1425  
1426 This library performs B<STATIC> checks of the Windows filesystem.
1427 If malware modifies the filesystem between the time the $object->new()
1428 and $object->check() methods are called, then this library may B<FAIL>
1429 to detect those changes if:
1430  
1431 =over 4
1432  
1433 =item *
1434  
1435 Malware writes itself to one of the regions of the filesystem that is
1436 excluded. See the <HoneyClient/><Agent/><Integrity/><exclude_list/>
1437 element, in the etc/honeyclient.xml file.
1438  
1439 =item *
1440  
1441 Malware writes itself to a monitored region of the filesystem but
1442 reverses all its activity (including self-deletion).
1443  
1444 =back
1445  
1446 This library also only monitors B<FILE> changes. Thus, if malware
1447 manipulates B<EMPTY DIRECTORIES> or B<SYMLINKS> on the system, then
1448 this library will B<NOT> report those changes.
1449  
1450 =head1 SEE ALSO
1451  
1452 L<http://www.honeyclient.org/trac>
1453  
1454 =head1 REPORTING BUGS
1455  
1456 L<http://www.honeyclient.org/trac/newticket>
1457  
1458 =head1 ACKNOWLEDGEMENTS
1459  
1460 Mark-Jason Dominus E<lt>mjd-perl-diff@plover.comE<gt>,
1461 Ned Konz E<lt>perl@bike-nomad.comE<gt>, and Tye McQueen,
1462 for using their Algorithm::Diff code.
1463  
1464 =head1 AUTHORS
1465  
1466 Xeno Kovah, E<lt>xkovah@mitre.orgE<gt>
1467  
1468 Darien Kindlund, E<lt>kindlund@mitre.orgE<gt>
1469  
1470 Brad Stephenson, E<lt>stephenson@mitre.orgE<gt>
1471  
1472 =head1 COPYRIGHT & LICENSE
1473  
1474 Copyright (C) 2007 The MITRE Corporation. All rights reserved.
1475  
1476 This program is free software; you can redistribute it and/or
1477 modify it under the terms of the GNU General Public License
1478 as published by the Free Software Foundation, using version 2
1479 of the License.
1480
1481 This program is distributed in the hope that it will be useful,
1482 but WITHOUT ANY WARRANTY; without even the implied warranty of
1483 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1484 GNU General Public License for more details.
1485
1486 You should have received a copy of the GNU General Public License
1487 along with this program; if not, write to the Free Software
1488 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
1489 02110-1301, USA.
1490  
1491 =cut