Agent/Integrity/Registry/Parser.pm untested

filter: Statementstmt 0.0% 0 / 405 Branchbran 0.0% 0 / 98 Conditioncond 0.0% 0 / 33 MC/DCmcdc 0.0% 0 / 17 Subroutinesub 0.0% 0 / 30 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 599 CC 50 SCAR 44.3
CC
50
Cov
0%
seekToNearestGroup
240.0
_lexer
182.0
_search
30.0
CRAP 84.0
1 ####################################################################
2 #
3 # This file was generated using Parse::Yapp version 1.05.
4 #
5 # Don't edit this file, use source file instead.
6 #
7 # ANY CHANGE MADE HERE WILL BE LOST !
8 #
9 ####################################################################
10 package HoneyClient::Agent::Integrity::Registry::Parser;
11 use vars qw ( @ISA );
12 use strict;
13  
14 @ISA= qw ( Parse::Yapp::Driver );
15 use Parse::Yapp::Driver;
16  
17 #line 1 "Parser.yp"
18  
19 #######################################################################
20 # Created on: Dec 10, 2006
21 # Package: HoneyClient::Agent::Integrity::Registry::Parser
22 # File: Parser.pm
23 # Description: Parses static hive dumps of the Windows OS registry.
24 #
25 # CVS: $Id: Parser.pm 773 2007-07-26 19:04:55Z kindlund $
26 #
27 # @author kindlund
28 #
29 # Copyright (C) 2007 The MITRE Corporation. All rights reserved.
30 #
31 # This program is free software; you can redistribute it and/or
32 # modify it under the terms of the GNU General Public License
33 # as published by the Free Software Foundation, using version 2
34 # of the License.
35 #
36 # This program is distributed in the hope that it will be useful,
37 # but WITHOUT ANY WARRANTY; without even the implied warranty of
38 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39 # GNU General Public License for more details.
40 #
41 # You should have received a copy of the GNU General Public License
42 # along with this program; if not, write to the Free Software
43 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
44 # 02110-1301, USA.
45 #
46 #######################################################################
47  
48 =pod
49  
50 =head1 NAME
51  
52 HoneyClient::Agent::Integrity::Registry::Parser - Perl extension to parse
53 static hive dumps of the Windows OS registry.
54  
55 =head1 VERSION
56  
57 This documentation refers to HoneyClient::Agent::Integrity::Registry::Parser version 0.98.
58  
59 =head1 SYNOPSIS
60  
61 use HoneyClient::Agent::Integrity::Registry::Parser;
62 use IO::File;
63 use Data::Dumper;
64  
65 # Initialize the parser object.
66 my $parser = HoneyClient::Agent::Integrity::Registry::Parser->init(
67 input_file => "dump.reg",
68 );
69  
70 # Print each registry group found, until there are no more left.
71 my $registryGroup = $parser->nextGroup();
72 while(scalar(keys(%{$registryGroup}))) {
73 print Dumper($registryGroup);
74 $registryGroup = $parser->nextGroup();
75 }
76  
77 # $registryGroup refers to hashtable reference, which has the
78 # following format:
79 #
80 # $registryGroup = {
81 # # The registry directory name.
82 # 'key' => 'HKEY_LOCAL_MACHINE\Software...',
83 #
84 # # An array containing the list of entries within the
85 # # registry directory.
86 # 'entries' => [ {
87 # 'name' => "\"string\"", # A (potentially) quoted string;
88 # # "@" for default
89 # 'value' => "data",
90 # }, ],
91 # };
92  
93 =head1 DESCRIPTION
94  
95 This library allows the Registry module to easily parse and enumerate
96 each Windows OS registry hive.
97  
98 =cut
99  
100 use strict;
101 use warnings;
102 use Carp ();
103  
104 # Include Global Configuration Processing Library
105 use HoneyClient::Util::Config qw(getVar);
106  
107 # Include Logging Library
108 use Log::Log4perl qw(:easy);
109  
110 # Use Dumper Library.
111 use Data::Dumper;
112  
113 # Use IO File Library.
114 use IO::File;
115  
116 # Use Seek Library.
117 use Fcntl qw(:seek);
118  
119 # Use Binary Search Library.
120 use Search::Binary;
121  
122 # Use Progress Bar Library.
123 use Term::ProgressBar;
124  
125 #######################################################################
126 # Module Initialization #
127 #######################################################################
128  
129 BEGIN {
130 # Defines which functions can be called externally.
131 require Exporter;
132 our (@ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS, $VERSION);
133  
134 # Set our package version.
135 $VERSION = 0.98;
136  
137 @ISA = qw(Exporter);
138  
139 # Symbols to export automatically
140 @EXPORT = qw( );
141  
142 # Items to export into callers namespace by default. Note: do not export
143 # names by default without a very good reason. Use EXPORT_OK instead.
144 # Do not simply export all your public functions/methods/constants.
145  
146 # This allows declaration use HoneyClient::Agent::Integrity::Registry ':all';
147 # If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
148 # will save memory.
149  
150 %EXPORT_TAGS = (
151 'all' => [ qw( ) ],
152 );
153  
154 # Symbols to autoexport (when qw(:all) tag is used)
155 @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
156  
157 $SIG{PIPE} = 'IGNORE'; # Do not exit on broken pipes.
158 }
159 our (@EXPORT_OK, $VERSION);
160  
161 =pod
162  
163 =begin testing
164  
165 # Make sure Log::Log4perl loads
166 BEGIN { use_ok('Log::Log4perl', qw(:nowarn))
167 or diag("Can't load Log::Log4perl package. Check to make sure the package library is correctly listed within the path.");
168
169 # Suppress all logging messages, since we need clean output for unit testing.
170 Log::Log4perl->init({
171 "log4perl.rootLogger" => "DEBUG, Buffer",
172 "log4perl.appender.Buffer" => "Log::Log4perl::Appender::TestBuffer",
173 "log4perl.appender.Buffer.min_level" => "fatal",
174 "log4perl.appender.Buffer.layout" => "Log::Log4perl::Layout::PatternLayout",
175 "log4perl.appender.Buffer.layout.ConversionPattern" => "%d{yyyy-MM-dd HH:mm:ss} %5p [%M] (%F:%L) - %m%n",
176 });
177 }
178 require_ok('Log::Log4perl');
179 use Log::Log4perl qw(:easy);
180  
181 # Make sure the module loads properly, with the exportable
182 # functions shared.
183 BEGIN { use_ok('HoneyClient::Util::Config', qw(getVar setVar))
184 or diag("Can't load HoneyClient::Util::Config package. Check to make sure the package library is correctly listed within the path."); }
185 require_ok('HoneyClient::Util::Config');
186 can_ok('HoneyClient::Util::Config', 'getVar');
187 can_ok('HoneyClient::Util::Config', 'setVar');
188 use HoneyClient::Util::Config qw(getVar setVar);
189  
190 # Suppress all logging messages, since we need clean output for unit testing.
191 Log::Log4perl->init({
192 "log4perl.rootLogger" => "DEBUG, Buffer",
193 "log4perl.appender.Buffer" => "Log::Log4perl::Appender::TestBuffer",
194 "log4perl.appender.Buffer.min_level" => "fatal",
195 "log4perl.appender.Buffer.layout" => "Log::Log4perl::Layout::PatternLayout",
196 "log4perl.appender.Buffer.layout.ConversionPattern" => "%d{yyyy-MM-dd HH:mm:ss} %5p [%M] (%F:%L) - %m%n",
197 });
198  
199 # Make sure Data::Dumper loads
200 BEGIN { use_ok('Data::Dumper')
201 or diag("Can't load Data::Dumper package. Check to make sure the package library is correctly listed within the path."); }
202 require_ok('Data::Dumper');
203 use Data::Dumper;
204  
205 # Make sure IO::File loads
206 BEGIN { use_ok('IO::File')
207 or diag("Can't load IO::File package. Check to make sure the package library is correctly listed within the path."); }
208 require_ok('IO::File');
209 use IO::File;
210  
211 # Make sure Fcntl loads
212 BEGIN { use_ok('Fcntl')
213 or diag("Can't load Fcntl package. Check to make sure the package library is correctly listed within the path."); }
214 require_ok('Fcntl');
215 use Fcntl qw(:seek);
216  
217 # Make sure Search::Binary loads
218 BEGIN { use_ok('Search::Binary')
219 or diag("Can't load Search::Binary package. Check to make sure the package library is correctly listed within the path."); }
220 require_ok('Search::Binary');
221 can_ok('Search::Binary', 'binary_search');
222 use Search::Binary;
223  
224 # Make sure Term::ProgressBar loads
225 BEGIN { use_ok('Term::ProgressBar')
226 or diag("Can't load Term::ProgressBar package. Check to make sure the package library is correctly listed within the path."); }
227 require_ok('Term::ProgressBar');
228 use Term::ProgressBar;
229  
230 # Make sure HoneyClient::Agent::Integrity::Registry::Parser loads
231 BEGIN { use_ok('HoneyClient::Agent::Integrity::Registry::Parser')
232 or diag("Can't load HoneyClient::Agent::Integrity::Registry::Parser package. Check to make sure the package library is correctly listed within the path."); }
233 require_ok('HoneyClient::Agent::Integrity::Registry::Parser');
234 use HoneyClient::Agent::Integrity::Registry::Parser;
235  
236 =end testing
237  
238 =cut
239  
240 #######################################################################
241 # Global Configuration Variables
242 #######################################################################
243  
244 # The global logging object.
245 our $LOG = get_logger();
246  
247 # Make Dumper format more terse.
248 $Data::Dumper::Terse = 1;
249 $Data::Dumper::Indent = 1;
250  
251  
252  
253 sub new {
254 my($class)=shift;
255 ref($class)
256 and $class=ref($class);
257  
258 my($self)=$class->SUPER::new( yyversion => '1.05',
259 yystates =>
260 [
261 {#State 0
262 ACTIONS => {
263 'DIR_NAME' => 2,
264 'HEADER' => 5,
265 'NEWLINE' => 6
266 },
267 DEFAULT => -1,
268 GOTOS => {
269 'group' => 1,
270 'registry' => 3,
271 'groups' => 4
272 }
273 },
274 {#State 1
275 DEFAULT => -4
276 },
277 {#State 2
278 ACTIONS => {
279 'KEY_NAME' => 7
280 },
281 DEFAULT => -9,
282 GOTOS => {
283 'entry' => 8,
284 'entries' => 9
285 }
286 },
287 {#State 3
288 ACTIONS => {
289 '' => 10
290 }
291 },
292 {#State 4
293 DEFAULT => -2
294 },
295 {#State 5
296 ACTIONS => {
297 'DIR_NAME' => 2,
298 'NEWLINE' => 6
299 },
300 GOTOS => {
301 'group' => 1,
302 'groups' => 11
303 }
304 },
305 {#State 6
306 ACTIONS => {
307 'DIR_NAME' => 2
308 },
309 GOTOS => {
310 'group' => 12
311 }
312 },
313 {#State 7
314 ACTIONS => {
315 'KEY_VALUE' => 13
316 }
317 },
318 {#State 8
319 ACTIONS => {
320 'KEY_NAME' => 7
321 },
322 DEFAULT => -10,
323 GOTOS => {
324 'entry' => 8,
325 'entries' => 14
326 }
327 },
328 {#State 9
329 DEFAULT => -8
330 },
331 {#State 10
332 DEFAULT => 0
333 },
334 {#State 11
335 DEFAULT => -3
336 },
337 {#State 12
338 ACTIONS => {
339 'DIR_NAME' => 2,
340 'NEWLINE' => 16
341 },
342 DEFAULT => -5,
343 GOTOS => {
344 'group' => 1,
345 'groups' => 15
346 }
347 },
348 {#State 13
349 DEFAULT => -12
350 },
351 {#State 14
352 DEFAULT => -11
353 },
354 {#State 15
355 DEFAULT => -7
356 },
357 {#State 16
358 ACTIONS => {
359 'DIR_NAME' => 2
360 },
361 DEFAULT => -6,
362 GOTOS => {
363 'group' => 12
364 }
365 }
366 ],
367 yyrules =>
368 [
369 [#Rule 0
370 '$start', 2, undef
371 ],
372 [#Rule 1
373 'registry', 0,
374 sub
375 #line 247 "Parser.yp"
376 {
377 $LOG->debug("Reached end of input stream.");
378 # Finished parsing the entire file, return empty hash ref.
379 return { };
380 }
381 ],
382 [#Rule 2
383 'registry', 1,
384 sub
385 #line 252 "Parser.yp"
386 {
387 $LOG->debug("Reached end of input stream.");
388 # Finished parsing the entire file, return empty hash ref.
389 return { };
390 }
391 ],
392 [#Rule 3
393 'registry', 2,
394 sub
395 #line 257 "Parser.yp"
396 {
397 $LOG->debug("Reached end of input stream.");
398 # Finished parsing the entire file, return empty hash ref.
399 return { };
400 }
401 ],
402 [#Rule 4
403 'groups', 1, undef
404 ],
405 [#Rule 5
406 'groups', 2, undef
407 ],
408 [#Rule 6
409 'groups', 3, undef
410 ],
411 [#Rule 7
412 'groups', 3, undef
413 ],
414 [#Rule 8
415 'group', 2,
416 sub
417 #line 274 "Parser.yp"
418 {
419 my $ret = { };
420 $_[0]->YYData->{'latest_group'}->{'key'} = $_[1];
421 if (!exists($_[0]->YYData->{'latest_group'}->{'entries'})) {
422 # Make sure the 'entries' key exists.
423 $_[0]->YYData->{'latest_group'}->{'entries'} = [];
424 }
425 $ret = $_[0]->YYData->{'latest_group'};
426 $_[0]->YYData->{'latest_group'} = { };
427 $_[0]->YYData->{'dir_count'}++;
428 $_[0]->YYAccept; # Terminate the parse, early.
429  
430 return $ret;
431 }
432 ],
433 [#Rule 9
434 'group', 1,
435 sub
436 #line 288 "Parser.yp"
437 {
438 my $ret = { };
439 $_[0]->YYData->{'latest_group'}->{'key'} = $_[1];
440 if (!exists($_[0]->YYData->{'latest_group'}->{'entries'})) {
441 # Make sure the 'entries' key exists.
442 $_[0]->YYData->{'latest_group'}->{'entries'} = [];
443 }
444 $ret = $_[0]->YYData->{'latest_group'};
445 $_[0]->YYData->{'latest_group'} = { };
446 $_[0]->YYData->{'dir_count'}++;
447 $_[0]->YYAccept; # Terminate the parse, early.
448  
449 return $ret;
450 }
451 ],
452 [#Rule 10
453 'entries', 1, undef
454 ],
455 [#Rule 11
456 'entries', 2, undef
457 ],
458 [#Rule 12
459 'entry', 2,
460 sub
461 #line 312 "Parser.yp"
462 {
463 my $entry = {
464 name => $_[1],
465 value => $_[2],
466 };
467 push(@{$_[0]->YYData->{'latest_group'}->{entries}}, $entry);
468 $_[0]->YYData->{'entry_count'}++;
469 }
470 ]
471 ],
472 @_);
473 bless($self,$class);
474 }
475  
476 #line 322 "Parser.yp"
477  
478  
479 #######################################################################
480 # Private Methods Implemented #
481 #######################################################################
482  
483 # Helper function, designed to tokenize specific data from the input stream.
484 #
485 # Inputs: parser
486 # Outputs: (token_id, data) pair
487 sub _lexer {
488 # Identify NEWLINE token.
489 if ($_[0]->YYData->{DATA} =~ m/\G\n/cg) {
490 $_[0]->YYData->{'in_group'} = 0;
491 $LOG->debug("Found NEWLINE token ending at offset (" . pos($_[0]->YYData->{DATA}) . ").");
492 $_[0]->YYData->{'line_count'}++;
493 return ("NEWLINE", "\n");
494 }
495  
496 # Check to see if we're inside a group block...
497 if (!$_[0]->YYData->{'in_group'}) {
498  
499 $_[0]->YYData->{'input_pos'} = pos($_[0]->YYData->{DATA});
500 $_[0]->YYData->{'input_pos'} = $_[0]->YYData->{'input_pos'} ?
501 $_[0]->YYData->{'input_pos'} : 0;
502 $_[0]->YYData->{'input_pos'} = $_[0]->YYData->{'input_pos'} +
503 $_[0]->YYData->{'abs_offset'};
504  
505 # Update progress bar, if defined.
506 if (defined($_[0]->YYData->{'progress'}) &&
507 ($_[0]->YYData->{'input_pos'} > $_[0]->YYData->{'progress_next_update'})) {
508 $_[0]->YYData->{'progress_next_update'} =
509 $_[0]->YYData->{'progress'}->update($_[0]->YYData->{'input_pos'});
510 }
511  
512 # Identify DIR_NAME token.
513 if ($_[0]->YYData->{DATA} =~ m/\G\[(.*)\]\n/cg) {
514 $_[0]->YYData->{'in_group'} = 1;
515 $LOG->debug("Found DIR_NAME token ending at offset (" . pos($_[0]->YYData->{DATA}) . ").");
516 $_[0]->YYData->{'last_group_line_number'} = $_[0]->YYData->{'line_count'};
517 $_[0]->YYData->{'line_count'}++;
518 return ("DIR_NAME", $1);
519 }
520  
521 # Identify HEADER token. It's always only at the beginning.
522 if ($_[0]->YYData->{DATA} =~ m/\GREGEDIT4\n/cg) {
523 $LOG->debug("Found HEADER token ending at offset (" . pos($_[0]->YYData->{DATA}) . ").");
524 $_[0]->YYData->{'line_count'}++;
525 return ("HEADER", "REGEDIT4\n");
526 }
527  
528 } else {
529  
530 # Check to see if we're in a value segment...
531 if (!$_[0]->YYData->{'in_value'}) {
532  
533 # Identify KEY_NAME token.
534 if ($_[0]->YYData->{DATA} =~ m/\G\"(|[^\\]|.*(?:\\[^\\]|\\\\|[^\\][^\\]))\"(?==)/cg) {
535 $_[0]->YYData->{'in_value'} = 1;
536 $LOG->debug("Found KEY_NAME token ending at offset (" . pos($_[0]->YYData->{DATA}) . ").");
537 return ("KEY_NAME", $1);
538 }
539  
540 # Identify default KEY_NAME token (@).
541 if ($_[0]->YYData->{DATA} =~ m/\G\@(?==)/cg) {
542 $_[0]->YYData->{'in_value'} = 1;
543 $LOG->debug("Found KEY_NAME token ending at offset (" . pos($_[0]->YYData->{DATA}) . ").");
544 return ("KEY_NAME", "@");
545 }
546  
547 } else {
548  
549 # Identify string KEY_VALUE token.
550 if ($_[0]->YYData->{DATA} =~ m/\G=\"(|[^\\]|.*?(?:\\[^\\]|\\\\|[^\\][^\\]))\"\n/cgs) {
551 $_[0]->YYData->{'in_value'} = 0;
552 $LOG->debug("Found KEY_VALUE token ending at offset (" . pos($_[0]->YYData->{DATA}) . ").");
553 $_[0]->YYData->{'line_count'} += 1 + @{[$1 =~ /\n/g]};
554 return ("KEY_VALUE", $1);
555 }
556  
557 # Identify binary KEY_VALUE token.
558 if ($_[0]->YYData->{DATA} =~ m/\G=(|.*?[^\\])\n/cgs) {
559 $_[0]->YYData->{'in_value'} = 0;
560 $LOG->debug("Found KEY_VALUE token ending at offset (" . pos($_[0]->YYData->{DATA}) . ").");
561 $_[0]->YYData->{'line_count'} += 1 + @{[$1 =~ /\n/g]};
562 return ("KEY_VALUE", $1);
563 }
564 }
565 }
566
567 # Croak if encountered a token error.
568 if ($_[0]->YYData->{DATA} =~ m/\G(.*\n)/cg) {
569 $_[0]->YYData->{'input_pos'} = pos($_[0]->YYData->{DATA});
570 $LOG->fatal("Error: Unknown token (" . $1 . ") at offset (". $_[0]->YYData->{'input_pos'} .")");
571 Carp::croak("Error: Unknown token (" . $1 . ") at offset (". $_[0]->YYData->{'input_pos'} .")");
572 }
573 return ('', undef);
574 }
575  
576 # Helper function, designed to report when any parsing error
577 # occurs.
578 #
579 # Inputs: parser
580 # Outputs: None
581 sub _error {
582  
583 $LOG->fatal("Error: Malformed input found at offset (" . $_[0]->YYData->{'input_pos'} . ").");
584 Carp::croak("Error: Malformed input found at offset (" . $_[0]->YYData->{'input_pos'} . ").");
585 }
586  
587 # Helper function, designed to reset the parser's file stream back to the
588 # beginning, allowing the parser to reparse from the beginning. Or, if
589 # specified, the function will seek the parser to the specified offset.
590 #
591 # Inputs: parser, absolute offset (optional)
592 # Outputs: none
593 sub _reset {
594 # Extract arguments.
595 my ($self, $offset) = @_;
596  
597 $LOG->debug("Resetting parser.");
598  
599 $self->YYData->{'file_handle'} = undef;
600  
601 my $fh = new IO::File($self->YYData->{'filename'}, "r");
602 if (!defined($fh)) {
603 $LOG->fatal("Error: Unable to read file '" . $self->YYData->{'filename'} . "'!");
604 Carp::croak("Error: Unable to read file '" . $self->YYData->{'filename'} . "'!");
605 }
606  
607 $self->YYData->{'file_handle'} = $fh;
608  
609 # Check the offset.
610 if (!defined($offset)) {
611 $offset = 0;
612 }
613 seek($fh, $offset, SEEK_SET);
614  
615 undef $/;
616 $self->YYData->{DATA} = <$fh>;
617  
618 # Strip all CRs.
619 $self->YYData->{DATA} =~ s/\r//g;
620  
621 # Total size of input file.
622 $self->YYData->{'file_size'} = (stat($fh))[7];
623  
624 # Reinitialize helper variables.
625 # Hashtable, to represent the latest, extracted group chunk.
626 $self->YYData->{'latest_group'} = { };
627  
628 # Boolean, to indicate when we're parsing inside a group chunk.
629 $self->YYData->{'in_group'} = 0;
630  
631 # Boolean, to indicate when we're parsing inside a value segment.
632 $self->YYData->{'in_value'} = 0;
633
634 # Regexp offset, used to record where the parser is within
635 # the file (relative position).
636 $self->YYData->{'input_pos'} = 0;
637  
638 # Absolute offset, recording where the parser initially seeked to.
639 $self->YYData->{'abs_offset'} = $offset;
640  
641 # Initialize statistics.
642 # Total number of directories parsed.
643 $self->YYData->{'dir_count'} = 0;
644  
645 # Total number of key/value pairs parsed.
646 $self->YYData->{'entry_count'} = 0;
647  
648 # Total number of lines parsed.
649 $self->YYData->{'line_count'} = 0;
650  
651 # Last line number that corresponded to a group separation point.
652 $self->YYData->{'last_group_line_number'} = 0;
653  
654 # Progress bar information.
655 if ($self->YYData->{'show_progress'}) {
656 $self->YYData->{'progress'} = Term::ProgressBar->new({ name => 'Progress',
657 count => $self->YYData->{'file_size'},
658 ETA => 'linear', });
659 $self->YYData->{'progress'}->minor(0);
660 $self->YYData->{'progress'}->max_update_rate(1);
661 $self->YYData->{'progress_next_update'} = $self->YYData->{'progress'}->update($offset);
662 } else {
663 $self->YYData->{'progress'} = undef;
664 }
665 }
666  
667 # Helper function, designed to index all groups, based upon beginning file
668 # offsets.
669 #
670 # Inputs: parser
671 # Outputs: None
672 sub _index {
673 # Extract arguments.
674 my $self = shift;
675  
676 $LOG->debug("Starting group index process.");
677  
678 $self->YYData->{'group_index_offsets'} = [0, ];
679 $self->YYData->{'group_index_linenums'} = [0, ];
680  
681 my $registryGroup = $self->nextGroup();
682 while(scalar(keys(%{$registryGroup}))) {
683 push (@{$self->YYData->{'group_index_offsets'}}, $self->YYData->{'input_pos'});
684 push (@{$self->YYData->{'group_index_linenums'}}, $self->YYData->{'last_group_line_number'});
685 $registryGroup = $self->nextGroup();
686 }
687  
688 # Reset the parser.
689 $self->_reset();
690  
691 $LOG->debug("Finished group index process.");
692 }
693  
694 # Helper function, designed to be called from within the
695 # Search::Binary::binary_search() function, in order to allow
696 # the binary_search to properly read in group index data from
697 # the default parser reference.
698 #
699 # For more information about how this function operates, please
700 # see the Search::Binary POD documentation.
701 #
702 # Inputs: parser, value_to_compare, current_array_index
703 # Outputs: comparison, last_valid_array_index
704 sub _search {
705 # Extract arguments.
706 my ($parser, $value_to_compare, $current_array_index) = @_;
707  
708 # Increment the search index, if the current one is undef.
709 if (defined($current_array_index)) {
710 $parser->YYData->{'last_search_index'} = $current_array_index;
711 } else {
712 $parser->YYData->{'last_search_index'}++;
713 }
714  
715 # Perform a comparison, if the array entry is defined.
716 # Check to see if the search is for line numbers or offsets.
717 if ($parser->YYData->{'search_is_linenum'}) {
718 if (defined(@{$parser->YYData->{'group_index_linenums'}}[$parser->YYData->{'last_search_index'}])) {
719 return($value_to_compare <=> @{$parser->YYData->{'group_index_linenums'}}[$parser->YYData->{'last_search_index'}],
720 $parser->YYData->{'last_search_index'});
721 }
722 } else {
723 if (defined(@{$parser->YYData->{'group_index_offsets'}}[$parser->YYData->{'last_search_index'}])) {
724 return($value_to_compare <=> @{$parser->YYData->{'group_index_offsets'}}[$parser->YYData->{'last_search_index'}],
725 $parser->YYData->{'last_search_index'});
726 }
727 }
728  
729 # Array entry not found, return undef with this position.
730 return (undef, $parser->YYData->{'last_search_index'});
731 }
732  
733 #######################################################################
734 # Public Methods Implemented #
735 #######################################################################
736  
737 =pod
738  
739 =head1 METHODS IMPLEMENTED
740  
741 The following functions have been implemented by any Parser object.
742  
743 =head2 HoneyClient::Agent::Integrity::Registry::Parser->init(input_file => $filename,
744 index_groups => $perform_index,
745 show_progress => $progress)
746  
747 =over 4
748  
749 Creates a new Parser object, using the specified input file as its data
750 source.
751  
752 I<Inputs>:
753 B<$filename> is an required parameter, specifying the file to open for parsing.
754 B<$perform_index> is an optional parameter. 1 specifies that the parser should go
755 ahead and scan the entire file, indexing the file offsets of where groups start and
756 end. Otherwise, this indexing process is not performed.
757 B<$progress> is an optional parameter. 1 specifies that the parser should display
758 a progress bar, as it scans through a specified file. Otherwise, a progress bar
759 is not displayed.
760
761 I<Output>: The instantiated Parser B<$object>, fully initialized.
762  
763 =back
764  
765 =begin testing
766  
767 my $test_registry_file = $ENV{PWD} . "/" . getVar(name => "registry_file",
768 namespace => "HoneyClient::Agent::Integrity::Registry::Parser::Test");
769  
770 # Create a generic Parser object, with test state data.
771 my $parser = HoneyClient::Agent::Integrity::Registry::Parser->init(input_file => $test_registry_file);
772 isa_ok($parser, 'HoneyClient::Agent::Integrity::Registry::Parser', "init(input_file => $test_registry_file)") or diag("The init() call failed.");
773  
774 =end testing
775  
776 =cut
777  
778 sub init {
779  
780 # Extract arguments.
781 my ($self, %args) = @_;
782  
783 # Log resolved arguments.
784 $LOG->debug(sub {
785 # Make Dumper format more terse.
786 $Data::Dumper::Terse = 1;
787 $Data::Dumper::Indent = 0;
788 Dumper(\%args);
789 });
790  
791 # Sanity check, don't initialize, unless input_file_handle
792 # was provided.
793 my $argsExist = scalar(%args);
794 if (!$argsExist ||
795 !exists($args{'input_file'}) ||
796 !defined($args{'input_file'})) {
797 $LOG->fatal("Error: Unable to create parser - no 'input_file' specified!");
798 Carp::croak("Error: Unable to create parser - no 'input_file' specified!");
799 }
800  
801 my $parser = HoneyClient::Agent::Integrity::Registry::Parser->new();
802 my $fh = new IO::File($args{'input_file'}, "r");
803 if (!defined($fh)) {
804 $LOG->fatal("Error: Unable to read file '" . $args{'input_file'} . "'!");
805 Carp::croak("Error: Unable to read file '" . $args{'input_file'} . "'!");
806 }
807
808 # Check if show progress was specified.
809 if ($argsExist &&
810 exists($args{'show_progress'}) &&
811 defined($args{'show_progress'}) &&
812 $args{'show_progress'}) {
813 $parser->YYData->{'show_progress'} = 1;
814 } else {
815 $parser->YYData->{'show_progress'} = 0;
816 }
817  
818 # Save the file name.
819 $parser->YYData->{'filename'} = $args{'input_file'};
820  
821 # Save the file handle.
822 $parser->YYData->{'file_handle'} = $fh;
823  
824 # Reset the parser.
825 $parser->_reset();
826  
827 # Perform group indexing, if specified.
828 if ($argsExist &&
829 exists($args{'index_groups'}) &&
830 defined($args{'index_groups'}) &&
831 $args{'index_groups'}) {
832 $parser->_index();
833 } else {
834 $parser->YYData->{'group_index_offsets'} = [0, ];
835 $parser->YYData->{'group_index_linenums'} = [0, ];
836 }
837  
838 # Return parser object.
839 return $parser;
840 }
841  
842 =pod
843  
844 =head2 $object->nextGroup()
845  
846 =over 4
847  
848 Provides the next registry group, in the form of a hashtable reference.
849 This hashtable has the following format:
850  
851 {
852 # The registry directory name.
853 'key' => 'HKEY_LOCAL_MACHINE\Software...',
854
855 # An array containing the list of entries within the
856 # registry directory.
857 'entries' => [ {
858 'name' => "\"string\"", # A (potentially) quoted string;
859 # "@" for default
860 'value' => "data",
861 }, ],
862 };
863  
864 I<Output>: A hashtable reference if the next group was parsed successfully;
865 returns an empty hash ref, if the Parser B<$object> has reached the end of
866 the input stream.
867  
868 =back
869  
870 =begin testing
871  
872 my ($nextGroup, $expectedGroup);
873 my $test_registry_file = $ENV{PWD} . "/" . getVar(name => "registry_file",
874 namespace => "HoneyClient::Agent::Integrity::Registry::Parser::Test");
875  
876 # Create a generic Parser object, with test state data.
877 my $parser = HoneyClient::Agent::Integrity::Registry::Parser->init(input_file => $test_registry_file, index_groups => 1);
878  
879 # Verify Test Group #1
880 $nextGroup = $parser->nextGroup();
881 $expectedGroup = {
882 key => 'HKEY_CURRENT_USER\]Testing Group 1[',
883 entries => [ {
884 name => '@',
885 value => 'Default',
886 }, {
887 name => 'Foo',
888 value => 'Bar',
889 }, ],
890 };
891 is_deeply($nextGroup, $expectedGroup, "nextGroup() - 1") or diag("The nextGroup() call failed.");
892  
893 # Verify Test Group #2
894 $nextGroup = $parser->nextGroup();
895 $expectedGroup = {
896 key => 'HKEY_CURRENT_USER\Testing Group 2',
897 entries => [ {
898 name => '@',
899 value => '\\"Annoying=Value\\"',
900 }, {
901 name => '\\"Annoying=Key\\"',
902 value => 'Bar',
903 }, {
904 name => 'Multiline',
905 value => 'This
906 value spans
907 multiple lines
908 ',
909 }, {
910 name => 'Sane_Key',
911 value => '\\"Wierd=\\"Value',
912 }, ],
913 };
914 is_deeply($nextGroup, $expectedGroup, "nextGroup() - 2") or diag("The nextGroup() call failed.");
915  
916 # Verify Test Group #3
917 $nextGroup = $parser->nextGroup();
918 $expectedGroup = {
919 key => 'HKEY_CURRENT_USER\Testing Group 3',
920 entries => [ {
921 name => 'Test_Bin_1',
922 value => 'hex:f4,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,bc,02,00,00,00,\
923 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,\
924 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,\
925 7f,22,14,fc,7f,b0,fe,12,00,00,00,00,00,00,00,00,00,98,23,eb,77'
926 }, {
927 name => 'Test_Bin_2',
928 value => 'hex:f5,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,00,00,\
929 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,\
930 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,\
931 77,00,20,14,00,00,00,00,10,80,05,14,00,f0,1f,14,00,00,00,14,00'
932 }, ],
933 };
934 is_deeply($nextGroup, $expectedGroup, "nextGroup() - 3") or diag("The nextGroup() call failed.");
935  
936 # Verify Test Group #4
937 $nextGroup = $parser->nextGroup();
938 $expectedGroup = {
939 key => 'HKEY_CURRENT_USER\Testing Group 4',
940 entries => [],
941 };
942 is_deeply($nextGroup, $expectedGroup, "nextGroup() - 4") or diag("The nextGroup() call failed.");
943  
944 # Verify Test Group #5
945 $nextGroup = $parser->nextGroup();
946 $expectedGroup = {
947 key => 'HKEY_CURRENT_USER\Testing Group 5',
948 entries => [ {
949 name => '@',
950 value => '',
951 }, ],
952 };
953 is_deeply($nextGroup, $expectedGroup, "nextGroup() - 5") or diag("The nextGroup() call failed.");
954  
955 # Verify Test Group #6
956 $nextGroup = $parser->nextGroup();
957 $expectedGroup = {
958 key => 'HKEY_CURRENT_USER\Testing Group 6\With\Really\Deep\Nested\Directory\Structure',
959 entries => [ {
960 name => 'InstallerLocation',
961 value => 'C:\\\\WINDOWS\\\\system32\\\\',
962 }, ],
963 };
964 is_deeply($nextGroup, $expectedGroup, "nextGroup() - 6") or diag("The nextGroup() call failed.");
965  
966 # Verify Test Group #7
967 $nextGroup = $parser->nextGroup();
968 $expectedGroup = {
969 key => 'HKEY_CURRENT_USER\Testing Group 7',
970 entries => [ {
971 name => 'C:\\\\Program Files\\\\Common Files\\\\Microsoft Shared\\\\Web Folders\\\\',
972 value => '',
973 }, {
974 name => 'C:\\\\WINDOWS\\\\Installer\\\\{350C97B0-3D7C-4EE8-BAA9-00BCB3D54227}\\\\',
975 value => '',
976 }, {
977 name => 'C:\\\\Program Files\\\\Support Tools\\\\',
978 value => '',
979 }, {
980 name => 'C:\\\\Documents and Settings\\\\All Users\\\\Start Menu\\\\Programs\\\\Windows Support Tools\\\\',
981 value => '',
982 }, {
983 name => 'C:\\\\WINDOWS\\\\Installer\\\\{6855CCDD-BDF9-48E4-B80A-80DFB96FE36C}\\\\',
984 value => '',
985 }, {
986 name => 'C:\\\\WINDOWS\\\\Installer\\\\{F251B999-08A9-4704-999C-9962F0DFD88E}\\\\',
987 value => '',
988 }, {
989 name => 'C:\\\\WINDOWS\\\\Installer\\\\{1CB92574-96F2-467B-B793-5CEB35C40C29}\\\\',
990 value => '',
991 }, {
992 name => 'C:\\\\WINDOWS\\\\Installer\\\\{B37C842A-B624-46B8-A727-654E72F1C91A}\\\\',
993 value => '',
994 }, ],
995 };
996 is_deeply($nextGroup, $expectedGroup, "nextGroup() - 7") or diag("The nextGroup() call failed.");
997  
998 # Verify Test Group #8
999 $nextGroup = $parser->nextGroup();
1000 $expectedGroup = {
1001 key => 'HKEY_CURRENT_USER\Testing Group 8\{00021492-0000-0000-C000-000000000046}',
1002 entries => [ {
1003 name => '000',
1004 value => 'String Value',
1005 }, ],
1006 };
1007 is_deeply($nextGroup, $expectedGroup, "nextGroup() - 8") or diag("The nextGroup() call failed.");
1008  
1009 # Verify Test Group #9
1010 $nextGroup = $parser->nextGroup();
1011 is_deeply($nextGroup, { }, "nextGroup() - 9") or diag("The nextGroup() call failed.");
1012  
1013 =end testing
1014  
1015 =cut
1016  
1017 sub nextGroup {
1018 # Extract arguments.
1019 my ($self, %args) = @_;
1020  
1021 # Sanity check: Make sure we've been fed an object.
1022 unless (ref($self)) {
1023 $LOG->error("Error: Function must be called in reference to a " .
1024 __PACKAGE__ . "->new() object!");
1025 Carp::croak "Error: Function must be called in reference to a " .
1026 __PACKAGE__ . "->new() object!\n";
1027 }
1028  
1029 # Log resolved arguments.
1030 $LOG->debug(sub {
1031 # Make Dumper format more terse.
1032 $Data::Dumper::Terse = 1;
1033 $Data::Dumper::Indent = 0;
1034 Dumper(\%args);
1035 });
1036  
1037 # Reopen the file_handle, if it's been closed.
1038 if (!defined($self->YYData->{'file_handle'})) {
1039 $self->_reset();
1040 }
1041  
1042 if ($self->YYData->{'input_pos'} == 0) {
1043 $LOG->debug("Beginning parse of input stream.");
1044 }
1045  
1046 # Update progress bar, if defined.
1047 if (defined($_[0]->YYData->{'progress'}) &&
1048 ($_[0]->YYData->{'file_size'} <= $_[0]->YYData->{'progress_next_update'})) {
1049  
1050 $_[0]->YYData->{'progress'}->update($_[0]->YYData->{'file_size'});
1051 }
1052  
1053 # Return the next group parsed.
1054 return $self->YYParse(yylex => \&_lexer,
1055 yyerror => \&_error);
1056 }
1057  
1058 =pod
1059  
1060 =head2 $object->dirsParsed()
1061  
1062 =over 4
1063  
1064 Indicates how many registry directories the Parser B<$object> has
1065 parsed within the specified file, so far.
1066  
1067 I<Output>: Returns the number of directory groups parsed so far;
1068 returns 0, if none parsed yet.
1069  
1070 =back
1071  
1072 =begin testing
1073  
1074 my ($nextGroup);
1075 my $test_registry_file = $ENV{PWD} . "/" . getVar(name => "registry_file",
1076 namespace => "HoneyClient::Agent::Integrity::Registry::Parser::Test");
1077  
1078 # Create a generic Parser object, with test state data.
1079 my $parser = HoneyClient::Agent::Integrity::Registry::Parser->init(input_file => $test_registry_file);
1080  
1081 $nextGroup = $parser->nextGroup();
1082 while(scalar(keys(%{$nextGroup}))) {
1083 $nextGroup = $parser->nextGroup();
1084 }
1085  
1086 is($parser->dirsParsed(), 8, "dirsParsed()") or diag("The dirsParsed() call failed.");
1087  
1088 =end testing
1089  
1090 =cut
1091  
1092 sub dirsParsed {
1093 # Extract arguments.
1094 my ($self, %args) = @_;
1095  
1096 # Sanity check: Make sure we've been fed an object.
1097 unless (ref($self)) {
1098 $LOG->error("Error: Function must be called in reference to a " .
1099 __PACKAGE__ . "->new() object!");
1100 Carp::croak "Error: Function must be called in reference to a " .
1101 __PACKAGE__ . "->new() object!\n";
1102 }
1103
1104 # Log resolved arguments.
1105 $LOG->debug(sub {
1106 # Make Dumper format more terse.
1107 $Data::Dumper::Terse = 1;
1108 $Data::Dumper::Indent = 0;
1109 Dumper(\%args);
1110 });
1111  
1112 return $self->YYData->{'dir_count'};
1113 }
1114  
1115 =pod
1116  
1117 =head2 $object->entriesParsed()
1118  
1119 =over 4
1120  
1121 Indicates how many registry key/value pairs the Parser B<$object> has
1122 parsed within the specified file, so far.
1123  
1124 I<Output>: Returns the number of key/value pairs parsed so far;
1125 returns 0, if none parsed yet.
1126  
1127 =back
1128  
1129 =begin testing
1130  
1131 my ($nextGroup);
1132 my $test_registry_file = $ENV{PWD} . "/" . getVar(name => "registry_file",
1133 namespace => "HoneyClient::Agent::Integrity::Registry::Parser::Test");
1134  
1135 # Create a generic Parser object, with test state data.
1136 my $parser = HoneyClient::Agent::Integrity::Registry::Parser->init(input_file => $test_registry_file);
1137  
1138 $nextGroup = $parser->nextGroup();
1139 while(scalar(keys(%{$nextGroup}))) {
1140 $nextGroup = $parser->nextGroup();
1141 }
1142  
1143 is($parser->entriesParsed(), 19, "entriesParsed()") or diag("The entriesParsed() call failed.");
1144  
1145 =end testing
1146  
1147 =cut
1148  
1149 sub entriesParsed {
1150 # Extract arguments.
1151 my ($self, %args) = @_;
1152  
1153 # Sanity check: Make sure we've been fed an object.
1154 unless (ref($self)) {
1155 $LOG->error("Error: Function must be called in reference to a " .
1156 __PACKAGE__ . "->new() object!");
1157 Carp::croak "Error: Function must be called in reference to a " .
1158 __PACKAGE__ . "->new() object!\n";
1159 }
1160  
1161 # Log resolved arguments.
1162 $LOG->debug(sub {
1163 # Make Dumper format more terse.
1164 $Data::Dumper::Terse = 1;
1165 $Data::Dumper::Indent = 0;
1166 Dumper(\%args);
1167 });
1168  
1169 return $self->YYData->{'entry_count'};
1170 }
1171  
1172 =pod
1173  
1174 =head2 $object->getFileHandle()
1175  
1176 =over 4
1177  
1178 Returns the file handle associated with the current Parser B<$object>.
1179  
1180 I<Output>: Returns the file handle in use.
1181  
1182 =back
1183  
1184 =begin testing
1185  
1186 my ($handle);
1187 my $test_registry_file = $ENV{PWD} . "/" . getVar(name => "registry_file",
1188 namespace => "HoneyClient::Agent::Integrity::Registry::Parser::Test");
1189  
1190 # Create a generic Parser object, with test state data.
1191 my $parser = HoneyClient::Agent::Integrity::Registry::Parser->init(input_file => $test_registry_file);
1192  
1193 $handle = $parser->getFileHandle();
1194  
1195 isa_ok($handle, 'IO::File', "getFileHandle()") or diag("The getFileHandle() call failed.");
1196  
1197 =end testing
1198  
1199 =cut
1200  
1201 sub getFileHandle {
1202 # Extract arguments.
1203 my ($self, %args) = @_;
1204  
1205 # Sanity check: Make sure we've been fed an object.
1206 unless (ref($self)) {
1207 $LOG->error("Error: Function must be called in reference to a " .
1208 __PACKAGE__ . "->new() object!");
1209 Carp::croak "Error: Function must be called in reference to a " .
1210 __PACKAGE__ . "->new() object!\n";
1211 }
1212  
1213 # Log resolved arguments.
1214 $LOG->debug(sub {
1215 # Make Dumper format more terse.
1216 $Data::Dumper::Terse = 1;
1217 $Data::Dumper::Indent = 0;
1218 Dumper(\%args);
1219 });
1220  
1221 return $self->YYData->{'file_handle'};
1222 }
1223  
1224 =pod
1225  
1226 =head2 $object->getFilename()
1227  
1228 =over 4
1229  
1230 Returns the file name associated with the current Parser B<$object>.
1231  
1232 I<Output>: Returns the file name in use.
1233  
1234 =back
1235  
1236 =begin testing
1237  
1238 my ($filename);
1239 my $test_registry_file = $ENV{PWD} . "/" . getVar(name => "registry_file",
1240 namespace => "HoneyClient::Agent::Integrity::Registry::Parser::Test");
1241  
1242 # Create a generic Parser object, with test state data.
1243 my $parser = HoneyClient::Agent::Integrity::Registry::Parser->init(input_file => $test_registry_file);
1244  
1245 $filename = $parser->getFilename();
1246  
1247 is($filename, $test_registry_file, "getFilename()") or diag("The getFilename() call failed.");
1248  
1249 =end testing
1250  
1251 =cut
1252  
1253 sub getFilename {
1254 # Extract arguments.
1255 my ($self, %args) = @_;
1256  
1257 # Sanity check: Make sure we've been fed an object.
1258 unless (ref($self)) {
1259 $LOG->error("Error: Function must be called in reference to a " .
1260 __PACKAGE__ . "->new() object!");
1261 Carp::croak "Error: Function must be called in reference to a " .
1262 __PACKAGE__ . "->new() object!\n";
1263 }
1264  
1265 # Log resolved arguments.
1266 $LOG->debug(sub {
1267 # Make Dumper format more terse.
1268 $Data::Dumper::Terse = 1;
1269 $Data::Dumper::Indent = 0;
1270 Dumper(\%args);
1271 });
1272  
1273 return $self->YYData->{'filename'};
1274 }
1275  
1276 =pod
1277  
1278 =head2 $object->closeFileHandle()
1279  
1280 =over 4
1281  
1282 Closes the file handle associated with the current Parser B<$object>.
1283  
1284 =back
1285  
1286 =begin testing
1287  
1288 my ($handle);
1289 my $test_registry_file = $ENV{PWD} . "/" . getVar(name => "registry_file",
1290 namespace => "HoneyClient::Agent::Integrity::Registry::Parser::Test");
1291  
1292 # Create a generic Parser object, with test state data.
1293 my $parser = HoneyClient::Agent::Integrity::Registry::Parser->init(input_file => $test_registry_file);
1294 $parser->closeFileHandle();
1295  
1296 # Verify Test Group #1
1297 my $nextGroup = $parser->nextGroup();
1298 my $expectedGroup = {
1299 key => 'HKEY_CURRENT_USER\]Testing Group 1[',
1300 entries => [ {
1301 name => '@',
1302 value => 'Default',
1303 }, {
1304 name => 'Foo',
1305 value => 'Bar',
1306 }, ],
1307 };
1308 is_deeply($nextGroup, $expectedGroup, "closeFileHandle()") or diag("The closeFileHandle() call failed.");
1309  
1310 =end testing
1311  
1312 =cut
1313  
1314 sub closeFileHandle {
1315 # Extract arguments.
1316 my ($self, %args) = @_;
1317  
1318 # Sanity check: Make sure we've been fed an object.
1319 unless (ref($self)) {
1320 $LOG->error("Error: Function must be called in reference to a " .
1321 __PACKAGE__ . "->new() object!");
1322 Carp::croak "Error: Function must be called in reference to a " .
1323 __PACKAGE__ . "->new() object!\n";
1324 }
1325  
1326 # Log resolved arguments.
1327 $LOG->debug(sub {
1328 # Make Dumper format more terse.
1329 $Data::Dumper::Terse = 1;
1330 $Data::Dumper::Indent = 0;
1331 Dumper(\%args);
1332 });
1333  
1334 $self->YYData->{'file_handle'} = undef;
1335 }
1336  
1337 =pod
1338  
1339 =head2 $object->getCurrentLineCount()
1340  
1341 =over 4
1342  
1343 Returns the number of lines parsed by the Parser B<$object>
1344 within the specified file and resets the counter back to
1345 zero.
1346  
1347 I<Output>: Returns the current line count of the parser.
1348  
1349 B<Note>: Calling this function will reset the parser's
1350 line count.
1351  
1352 =back
1353  
1354 =begin testing
1355  
1356 my ($handle);
1357 my $test_registry_file = $ENV{PWD} . "/" . getVar(name => "registry_file",
1358 namespace => "HoneyClient::Agent::Integrity::Registry::Parser::Test");
1359  
1360 # Create a generic Parser object, with test state data.
1361 my $parser = HoneyClient::Agent::Integrity::Registry::Parser->init(input_file => $test_registry_file, index_groups => 1);
1362  
1363 $parser->seekToNearestGroup(absolute_offset => 84);
1364 my $nextGroup = $parser->nextGroup();
1365  
1366 is($parser->getCurrentLineCount(), 9, "getCurrentLineCount()") or diag("The getCurrentLineCount() call failed.");
1367  
1368 =end testing
1369  
1370 =cut
1371  
1372 sub getCurrentLineCount {
1373 # Extract arguments.
1374 my ($self, %args) = @_;
1375  
1376 # Sanity check: Make sure we've been fed an object.
1377 unless (ref($self)) {
1378 $LOG->error("Error: Function must be called in reference to a " .
1379 __PACKAGE__ . "->new() object!");
1380 Carp::croak "Error: Function must be called in reference to a " .
1381 __PACKAGE__ . "->new() object!\n";
1382 }
1383  
1384 # Log resolved arguments.
1385 $LOG->debug(sub {
1386 # Make Dumper format more terse.
1387 $Data::Dumper::Terse = 1;
1388 $Data::Dumper::Indent = 0;
1389 Dumper(\%args);
1390 });
1391  
1392 my $ret = $self->YYData->{'line_count'};
1393 $self->YYData->{'line_count'} = 0;
1394 return $ret;
1395 }
1396  
1397 =pod
1398  
1399 =head2 $object->seekToNearestGroup(absolute_offset => $offset, absolute_linenum => $linenum, adjust_index => $index)
1400  
1401 =over 4
1402  
1403 Given an absolute offset or line number within the file, this function
1404 will seek the parser to the nearest group found B<before>
1405 the specified offset.
1406  
1407 I<Inputs>:
1408 B<$offset> is an required parameter, specifying the absolute offset
1409 within the file to seek to.
1410 B<$linenum> is a required parameter, specifying the absolute line
1411 number within the file to seek to.
1412 B<$index> is an optional parameter, specifying to seek to a group
1413 before or after the target group. If unspecified, $index = 0.
1414  
1415 I<Outputs>: None.
1416  
1417 B<Notes>: Either B<$offset> or B<$linnum> must be specified. To seek to the
1418 target group, specify $index = 0 or leave undefined. To seek to the previous
1419 group before the target group, specify $index = -1. To seek to the next
1420 group after the target group, specify $index = 1.
1421  
1422 Once called, B<all> corresponding statistical counters will be reset. This means,
1423 that the output from $object->dirsParsed() and $object->entriesParsed() will be
1424 zero, if called immediately after this function.
1425  
1426 =back
1427  
1428 =begin testing
1429  
1430 my ($nextGroup, $expectedGroup);
1431 my $test_registry_file = $ENV{PWD} . "/" . getVar(name => "registry_file",
1432 namespace => "HoneyClient::Agent::Integrity::Registry::Parser::Test");
1433  
1434 # Create a generic Parser object, with test state data.
1435 my $parser = HoneyClient::Agent::Integrity::Registry::Parser->init(input_file => $test_registry_file, index_groups => 1);
1436  
1437 # Verify Test Group #2
1438 $expectedGroup = {
1439 key => 'HKEY_CURRENT_USER\Testing Group 2',
1440 entries => [ {
1441 name => '@',
1442 value => '\\"Annoying=Value\\"',
1443 }, {
1444 name => '\\"Annoying=Key\\"',
1445 value => 'Bar',
1446 }, {
1447 name => 'Multiline',
1448 value => 'This
1449 value spans
1450 multiple lines
1451 ',
1452 }, {
1453 name => 'Sane_Key',
1454 value => '\\"Wierd=\\"Value',
1455 }, ],
1456 };
1457 is($parser->seekToNearestGroup(absolute_offset => 84), 73, "seekToNearestGroup(absolute_offset => 84)") or diag("The seekToNearestGroup() call failed.");
1458 $nextGroup = $parser->nextGroup();
1459 is_deeply($nextGroup, $expectedGroup, "seekToNearestGroup(absolute_offset => 84)") or diag("The seekToNearestGroup() call failed.");
1460  
1461 is($parser->seekToNearestGroup(absolute_linenum => 7), 6, "seekToNearestGroup(absolute_linenum => 7)") or diag("The seekToNearestGroup() call failed.");
1462 $nextGroup = $parser->nextGroup();
1463 is_deeply($nextGroup, $expectedGroup, "seekToNearestGroup(absolute_linenum => 7)") or diag("The seekToNearestGroup() call failed.");
1464  
1465 # Verify Test Group #3
1466 $expectedGroup = {
1467 key => 'HKEY_CURRENT_USER\Testing Group 3',
1468 entries => [ {
1469 name => 'Test_Bin_1',
1470 value => 'hex:f4,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,bc,02,00,00,00,\
1471 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,\
1472 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,\
1473 7f,22,14,fc,7f,b0,fe,12,00,00,00,00,00,00,00,00,00,98,23,eb,77'
1474 }, {
1475 name => 'Test_Bin_2',
1476 value => 'hex:f5,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,00,00,\
1477 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,\
1478 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,\
1479 77,00,20,14,00,00,00,00,10,80,05,14,00,f0,1f,14,00,00,00,14,00'
1480 }, ],
1481 };
1482  
1483 is($parser->seekToNearestGroup(absolute_offset => 301), 234, "seekToNearestGroup(absolute_offset => 301)") or diag("The seekToNearestGroup() call failed.");
1484 $nextGroup = $parser->nextGroup();
1485 is_deeply($nextGroup, $expectedGroup, "seekToNearestGroup(absolute_offset => 301)") or diag("The seekToNearestGroup() call failed.");
1486  
1487 is($parser->seekToNearestGroup(absolute_linenum => 16), 15, "seekToNearestGroup(absolute_linenum => 16)") or diag("The seekToNearestGroup() call failed.");
1488 $nextGroup = $parser->nextGroup();
1489 is_deeply($nextGroup, $expectedGroup, "seekToNearestGroup(absolute_linenum => 16)") or diag("The seekToNearestGroup() call failed.");
1490  
1491 is($parser->seekToNearestGroup(absolute_linenum => 26, adjust_index => -1), 15, "seekToNearestGroup(absolute_linenum => 26, adjust_index => -1)") or diag("The seekToNearestGroup() call failed.");
1492 $nextGroup = $parser->nextGroup();
1493 is_deeply($nextGroup, $expectedGroup, "seekToNearestGroup(absolute_linenum => 26, adjust_index => -1)") or diag("The seekToNearestGroup() call failed.");
1494  
1495 # Verify Test Group #4
1496 $expectedGroup = {
1497 key => 'HKEY_CURRENT_USER\Testing Group 4',
1498 entries => [],
1499 };
1500  
1501 is($parser->seekToNearestGroup(absolute_offset => 898), 881, "seekToNearestGroup(absolute_offset => 898)") or diag("The seekToNearestGroup() call failed.");
1502 $nextGroup = $parser->nextGroup();
1503 is_deeply($nextGroup, $expectedGroup, "seekToNearestGroup(absolute_offset => 898)") or diag("The seekToNearestGroup() call failed.");
1504  
1505 is($parser->seekToNearestGroup(absolute_linenum => 26), 25, "seekToNearestGroup(absolute_linenum => 26)") or diag("The seekToNearestGroup() call failed.");
1506 $nextGroup = $parser->nextGroup();
1507 is_deeply($nextGroup, $expectedGroup, "seekToNearestGroup(absolute_linenum => 26)") or diag("The seekToNearestGroup() call failed.");
1508  
1509 # Verify Test Group #8
1510 $expectedGroup = {
1511 key => 'HKEY_CURRENT_USER\Testing Group 8\{00021492-0000-0000-C000-000000000046}',
1512 entries => [ {
1513 name => '000',
1514 value => 'String Value',
1515 }, ],
1516 };
1517 is($parser->seekToNearestGroup(absolute_offset => 898, adjust_index => 99), 1674, "seekToNearestGroup(absolute_offset => 898, adjust_index => 99)") or diag("The seekToNearestGroup() call failed.");
1518 $nextGroup = $parser->nextGroup();
1519 is_deeply($nextGroup, $expectedGroup, "seekToNearestGroup(absolute_offset => 898, adjust_index => 99)") or diag("The seekToNearestGroup() call failed.");
1520  
1521 # Verify Test Group #1
1522 $expectedGroup = {
1523 key => 'HKEY_CURRENT_USER\]Testing Group 1[',
1524 entries => [ {
1525 name => '@',
1526 value => 'Default',
1527 }, {
1528 name => 'Foo',
1529 value => 'Bar',
1530 }, ],
1531 };
1532 is($parser->seekToNearestGroup(absolute_offset => 898, adjust_index => -99), 0, "seekToNearestGroup(absolute_offset => 898, adjust_index => -99)") or diag("The seekToNearestGroup() call failed.");
1533 $nextGroup = $parser->nextGroup();
1534 is_deeply($nextGroup, $expectedGroup, "seekToNearestGroup(absolute_offset => 898, adjust_index => -99)") or diag("The seekToNearestGroup() call failed.");
1535  
1536 =end testing
1537  
1538 =cut
1539  
1540 sub seekToNearestGroup {
1541 # Extract arguments.
1542 my ($self, %args) = @_;
1543  
1544 # Sanity check: Make sure we've been fed an object.
1545 unless (ref($self)) {
1546 $LOG->error("Error: Function must be called in reference to a " .
1547 __PACKAGE__ . "->new() object!");
1548 Carp::croak "Error: Function must be called in reference to a " .
1549 __PACKAGE__ . "->new() object!\n";
1550 }
1551  
1552 # Log resolved arguments.
1553 $LOG->debug(sub {
1554 # Make Dumper format more terse.
1555 $Data::Dumper::Terse = 1;
1556 $Data::Dumper::Indent = 0;
1557 Dumper(\%args);
1558 });
1559  
1560 # Sanity check, don't continue, unless absolute_offset or absolute_linennum
1561 # was provided.
1562 my $argsExist = scalar(%args);
1563 if (!$argsExist) {
1564 $LOG->fatal("Error: Unable to seek parser - no 'absolute_offset' or 'absolute_linenum' specified!");
1565 Carp::croak("Error: Unable to seek parser - no 'absolute_offset' or 'absolute_linenum' specified!");
1566 }
1567  
1568 # Check if adjust_index was provided.
1569 my $adjust_index = 0;
1570 if (exists($args{'adjust_index'})) {
1571 if(!defined($args{'adjust_index'})) {
1572 $LOG->fatal("Error: Unable to seek parser - invalid 'adjust_index' specified!");
1573 Carp::croak("Error: Unable to seek parser - invalid 'adjust_index' specified!");
1574 } else {
1575 $adjust_index = $args{'adjust_index'};
1576 }
1577 }
1578
1579 # Define helper variables.
1580 my $search_arrayref = undef;
1581 my $search_target = undef;
1582  
1583 # Specify the search type.
1584 $self->YYData->{'search_is_linenum'} = 0;
1585  
1586 # Check if absolute_offset was provided.
1587 if (exists($args{'absolute_offset'})) {
1588 if (!defined($args{'absolute_offset'})) {
1589 $LOG->fatal("Error: Unable to seek parser - no 'absolute_offset' or 'absolute_linenum' specified!");
1590 Carp::croak("Error: Unable to seek parser - no 'absolute_offset' or 'absolute_linenum' specified!");
1591 }
1592 $search_arrayref = $self->YYData->{'group_index_offsets'};
1593 $search_target = $args{'absolute_offset'};
1594 } else {
1595 # Check if absolute_linenum was provided.
1596 if (!defined($args{'absolute_linenum'})) {
1597 $LOG->fatal("Error: Unable to seek parser - no 'absolute_offset' or 'absolute_linenum' specified!");
1598 Carp::croak("Error: Unable to seek parser - no 'absolute_offset' or 'absolute_linenum' specified!");
1599 }
1600 $search_arrayref = $self->YYData->{'group_index_linenums'};
1601 $search_target = $args{'absolute_linenum'};
1602 $self->YYData->{'search_is_linenum'} = 1;
1603 }
1604  
1605 # Final sanity check.
1606 if (!defined($search_target)) {
1607 $LOG->fatal("Error: Unable to seek parser - no 'absolute_offset' or 'absolute_linenum' specified!");
1608 Carp::croak("Error: Unable to seek parser - no 'absolute_offset' or 'absolute_linenum' specified!");
1609 }
1610  
1611 # Check to see if the $search_arrayref has been initialized.
1612 # We assume that if it has [0, ], then this has not been
1613 # done.
1614 my $numIndices = scalar(@{$search_arrayref});
1615 if ($numIndices < 2) {
1616 $self->_index();
1617 }
1618 $numIndices = scalar(@{$search_arrayref});
1619  
1620 # Find the nearest index after the offset.
1621 my $found_index = binary_search(0, $numIndices - 1, $search_target, \&_search, $self);
1622  
1623 # Now, find the nearest index before the offset.
1624 if ($found_index > 0) {
1625 $found_index--;
1626 # Adjust the index, if specified.
1627 if ($found_index > 0) {
1628 my $test_index = ($found_index + $adjust_index);
1629 # Make sure the adjustment doesn't exceed the min or max.
1630 if ($test_index >= $numIndices) {
1631 $found_index = $numIndices - 1;
1632 } elsif ($test_index < 0) {
1633 $found_index = 0;
1634 } else {
1635 $found_index = $test_index;
1636 }
1637 }
1638 }
1639  
1640 my $found_offset = @{$self->YYData->{'group_index_offsets'}}[$found_index];
1641  
1642 # Seek the parser, to the specified offset.
1643 $self->_reset($found_offset);
1644
1645 if($self->YYData->{'search_is_linenum'}) {
1646 my $found_linenum = @{$self->YYData->{'group_index_linenums'}}[$found_index];
1647 $LOG->debug("Seeking parser to nearest earlier group line number (" . $found_linenum . ").");
1648 return $found_linenum;
1649 } else {
1650 $LOG->debug("Seeking parser to nearest earlier group offset (" . $found_offset . ").");
1651 return $found_offset;
1652 }
1653 }
1654  
1655 #######################################################################
1656 # Additional Module Documentation #
1657 #######################################################################
1658  
1659 =head1 BUGS & ASSUMPTIONS
1660  
1661 The Parser B<$object> expects to scan the specified file as an input stream.
1662 Subsequent calls to $object->nextGroup() will advance the parser through
1663 the input stream.
1664  
1665 =head1 SEE ALSO
1666  
1667 L<http://www.honeyclient.org/trac>
1668  
1669 =head1 REPORTING BUGS
1670  
1671 L<http://www.honeyclient.org/trac/newticket>
1672  
1673 =head1 ACKNOWLEDGEMENTS
1674  
1675 Francois Desarmenien E<lt>francois@fdesar.netE<gt> for his
1676 work in developing the Parse::Yapp module.
1677  
1678 =head1 AUTHORS
1679  
1680 Darien Kindlund, E<lt>kindlund@mitre.orgE<gt>
1681  
1682 =head1 COPYRIGHT & LICENSE
1683  
1684 Copyright (C) 2007 The MITRE Corporation. All rights reserved.
1685  
1686 This program is free software; you can redistribute it and/or
1687 modify it under the terms of the GNU General Public License
1688 as published by the Free Software Foundation, using version 2
1689 of the License.
1690  
1691 This program is distributed in the hope that it will be useful,
1692 but WITHOUT ANY WARRANTY; without even the implied warranty of
1693 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1694 GNU General Public License for more details.
1695  
1696 You should have received a copy of the GNU General Public License
1697 along with this program; if not, write to the Free Software
1698 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
1699 02110-1301, USA.
1700  
1701  
1702 =cut
1703  
1704 1;