Agent/Driver/Browser/FF.pm untested

filter: Statementstmt 0.0% 0 / 76 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 15 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 128 CC 9 SCAR 37.8
CC
9
Cov
0%
drive
90.0
BEGIN
2.0
BEGIN
2.0
CRAP 43.7
1 #######################################################################
2 # Created on: May 11, 2006
3 # Package: HoneyClient::Agent::Driver::FF
4 # File: FF.pm
5 # Description: A specific driver for automating an instance of
6 # the Firefox browser, running inside a
7 # HoneyClient VM.
8 #
9 # CVS: $Id: FF.pm 773 2007-07-26 19:04:55Z kindlund $
10 #
11 # @author knwang, ttruong, kindlund, stephenson
12 #
13 # Copyright (C) 2007 The MITRE Corporation. All rights reserved.
14 #
15 # This program is free software; you can redistribute it and/or
16 # modify it under the terms of the GNU General Public License
17 # as published by the Free Software Foundation, using version 2
18 # of the License.
19 #
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 # GNU General Public License for more details.
24 #
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
28 # 02110-1301, USA.
29 #
30 #
31 #######################################################################
32  
33 =pod
34  
35 =head1 NAME
36  
37 HoneyClient::Agent::Driver::Browser::FF - Perl extension to drive Mozilla
38 Firefox to a given web page. This package extends the
39 HoneyClient::Agent::Driver::Browser package, by overridding the drive() method.
40  
41 =head1 VERSION
42  
43 This documentation refers to HoneyClient::Agent::Driver::Browser::FF version 0.98.
44  
45 =head1 SYNOPSIS
46  
47 use HoneyClient::Agent::Driver::Browser::FF;
48  
49 # Library used exclusively for debugging complex objects.
50 use Data::Dumper;
51  
52 # Create a new FF object, initialized with a collection
53 # of URLs to visit.
54 my $browser = HoneyClient::Agent::Driver::Browser::FF->new(
55 links_to_visit => {
56 'http://www.google.com' => 1,
57 'http://www.cnn.com' => 1,
58 },
59 );
60  
61 # If you want to see what type of "state information" is physically
62 # inside $browser, try this command at any time.
63 print Dumper($browser);
64  
65 # Continue to "drive" the driver, until it is finished.
66 while (!$browser->isFinished()) {
67  
68 # Before we drive the application to a new set of resources,
69 # find out where we will be going within the application, first.
70 print "About to contact the following resources:\n";
71 print Dumper($browser->next());
72  
73 # Now, drive browser for one iteration.
74 $browser->drive();
75  
76 # Get the driver's progress.
77 print "Status:\n";
78 print Dumper($browser->status());
79  
80 }
81  
82 # At this stage, the driver has exhausted its collection of links
83 # to visit. Let's say we want to add the URL "http://www.mitre.org"
84 # to the driver's list.
85 $browser->{links_to_visit}->{'http://www.mitre.org'} = 1;
86  
87 # Now, drive the browser for one iteration.
88 $browser->drive();
89
90 # Or, we can specify the URL as an argument.
91 $browser->drive(url => "http://www.mitre.org");
92  
93 =head1 DESCRIPTION
94  
95 This library allows the Agent module to drive an instance of Mozilla
96 Firefox inside the HoneyClient VM. The purpose of this module is to
97 programmatically navigate this browser to different websites, in order to
98 become purposefully infected with new malware.
99  
100 This module is object-oriented in design, retaining all state information
101 within itself for easy access. This specific browser implementation inherits
102 all code from the HoneyClient::Agent::Driver::Browser package.
103  
104 Fundamentally, the FF driver is initialized with a set of absolute URLs
105 for the browser to drive to. Upon visiting each URL, the driver collects
106 any B<new> links found and will attempt to drive the browser to each
107 valid URL upon subsequent iterations of work.
108  
109 For each top-level URL given, the driver will attempt to process all
110 corresponding links that are hosted on the same server, in order to
111 simulate a complete 'spider' of each server.
112  
113 URLs are added and removed from hashtables, as keys. For each URL, a
114 calculated "priority" (a positive integer) of the URL is assigned the
115 value. When the FF driver is ready to go to a new link, it will always go
116 to the next link that has the highest priority. If two URLs have the same
117 priority, then the FF driver will chose among those two at random.
118  
119 Furthermore, the FF driver will try to visit all links shared by a
120 common server in order before moving on to drive to other,
121 external links in an ordered fashion. B<However>, the FF driver may end
122 up re-visiting old sites, if new links were found that the
123 FF driver has not visited yet.
124  
125 As the FF driver navigates the browser to each link, it
126 maintains a set of hashtables that record when valid links were
127 visited (see L<links_visited>); when invalid links were found
128 (see L<links_ignored>); and when the browser attempted to visit
129 a link but the operation timed out (see L<links_timed_out>).
130 By maintaining this internal history, the driver will B<never>
131 navigate the browser to the same link twice.
132  
133 Lastly, it is highly recommended that for each driver B<$object>,
134 one should call $object->isFinished() prior to making a subsequent
135 call to $object->drive(), in order to verify that the driver has
136 not exhausted its set of links to visit. Otherwise, if
137 $object->drive() is called with an empty set of links to visit,
138 the corresponding operation will B<croak>.
139  
140 =cut
141  
142 package HoneyClient::Agent::Driver::Browser::FF;
143  
144 use strict;
145 use warnings;
146 use Carp ();
147  
148 # Traps signals, allowing END: blocks to perform cleanup.
149 use sigtrap qw(die untrapped normal-signals error-signals);
150  
151 #######################################################################
152 # Module Initialization #
153 #######################################################################
154  
155 BEGIN {
156  
157 # Defines which functions can be called externally.
158 require Exporter;
159 our ( @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS, $VERSION );
160  
161 # Set our package version.
162 $VERSION = 0.98;
163  
164 # Define inherited modules.
165 use HoneyClient::Agent::Driver::Browser;
166  
167 @ISA = qw(Exporter HoneyClient::Agent::Driver::Browser);
168  
169 # Symbols to export automatically
170 # Note: Since this module is object-oriented, we do *NOT* export
171 # any functions other than "new" to call statically. Each function
172 # for this module *must* be called as a method from a unique
173 # object instance.
174 @EXPORT = qw();
175  
176 # Items to export into callers namespace by default. Note: do not export
177 # names by default without a very good reason. Use EXPORT_OK instead.
178 # Do not simply export all your public functions/methods/constants.
179  
180 # This allows declaration use HoneyClient::Agent::Driver::Browser::FF ':all';
181 # If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
182 # will save memory.
183  
184 # Note: Since this module is object-oriented, we do *NOT* export
185 # any functions other than "new" to call statically. Each function
186 # for this module *must* be called as a method from a unique
187 # object instance.
188 %EXPORT_TAGS = ( 'all' => [qw()], );
189  
190 # Symbols to autoexport (when qw(:all) tag is used)
191 @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
192  
193 $SIG{PIPE} = 'IGNORE'; # Do not exit on broken pipes.
194 }
195 our ( @EXPORT_OK, $VERSION );
196  
197 =pod
198  
199 =begin testing
200  
201 # Make sure Log::Log4perl loads
202 BEGIN { use_ok('Log::Log4perl', qw(:nowarn))
203 or diag("Can't load Log::Log4perl package. Check to make sure the package library is correctly listed within the path.");
204
205 # Suppress all logging messages, since we need clean output for unit testing.
206 Log::Log4perl->init({
207 "log4perl.rootLogger" => "DEBUG, Buffer",
208 "log4perl.appender.Buffer" => "Log::Log4perl::Appender::TestBuffer",
209 "log4perl.appender.Buffer.min_level" => "fatal",
210 "log4perl.appender.Buffer.layout" => "Log::Log4perl::Layout::PatternLayout",
211 "log4perl.appender.Buffer.layout.ConversionPattern" => "%d{yyyy-MM-dd HH:mm:ss} %5p [%M] (%F:%L) - %m%n",
212 });
213 }
214 require_ok('Log::Log4perl');
215 use Log::Log4perl qw(:easy);
216  
217 # Make sure HoneyClient::Util::Config loads.
218 BEGIN { use_ok('HoneyClient::Util::Config', qw(getVar))
219 or diag("Can't load HoneyClient::Util::Config package. Check to make sure the package library is correctly listed within the path.");
220  
221 # Suppress all logging messages, since we need clean output for unit testing.
222 Log::Log4perl->init({
223 "log4perl.rootLogger" => "DEBUG, Buffer",
224 "log4perl.appender.Buffer" => "Log::Log4perl::Appender::TestBuffer",
225 "log4perl.appender.Buffer.min_level" => "fatal",
226 "log4perl.appender.Buffer.layout" => "Log::Log4perl::Layout::PatternLayout",
227 "log4perl.appender.Buffer.layout.ConversionPattern" => "%d{yyyy-MM-dd HH:mm:ss} %5p [%M] (%F:%L) - %m%n",
228 });
229
230 }
231 require_ok('HoneyClient::Util::Config');
232 can_ok('HoneyClient::Util::Config', 'getVar');
233 use HoneyClient::Util::Config qw(getVar);
234  
235 # Make sure the module loads properly, with the exportable
236 # functions shared.
237 BEGIN { use_ok('HoneyClient::Agent::Driver::Browser::FF') or diag("Can't load HoneyClient::Agent::Driver::Browser::FF package. Check to make sure the package library is correctly listed within the path."); }
238 require_ok('HoneyClient::Agent::Driver::Browser::FF');
239 can_ok('HoneyClient::Agent::Driver::Browser::FF', 'new');
240 can_ok('HoneyClient::Agent::Driver::Browser::FF', 'drive');
241 can_ok('HoneyClient::Agent::Driver::Browser::FF', 'isFinished');
242 can_ok('HoneyClient::Agent::Driver::Browser::FF', 'next');
243 can_ok('HoneyClient::Agent::Driver::Browser::FF', 'status');
244 can_ok('HoneyClient::Agent::Driver::Browser::FF', 'getNextLink');
245 use HoneyClient::Agent::Driver::Browser::FF;
246  
247 # Suppress all logging messages, since we need clean output for unit testing.
248 Log::Log4perl->init({
249 "log4perl.rootLogger" => "DEBUG, Buffer",
250 "log4perl.appender.Buffer" => "Log::Log4perl::Appender::TestBuffer",
251 "log4perl.appender.Buffer.min_level" => "fatal",
252 "log4perl.appender.Buffer.layout" => "Log::Log4perl::Layout::PatternLayout",
253 "log4perl.appender.Buffer.layout.ConversionPattern" => "%d{yyyy-MM-dd HH:mm:ss} %5p [%M] (%F:%L) - %m%n",
254 });
255  
256 # Make sure Win32::Job loads.
257 BEGIN { use_ok('Win32::Job') or diag("Can't load Win32::Job package. Check to make sure the package library is correctly listed within the path."); }
258 require_ok('Win32::Job');
259 use Win32::Job;
260  
261 # Make sure ExtUtils::MakeMaker loads.
262 BEGIN { use_ok('ExtUtils::MakeMaker', qw(prompt)) or diag("Can't load ExtUtils::MakeMaker package. Check to make sure the package library is correctly listed within the path."); }
263 require_ok('ExtUtils::MakeMaker');
264 can_ok('ExtUtils::MakeMaker', 'prompt');
265 use ExtUtils::MakeMaker qw(prompt);
266  
267 =end testing
268  
269 =cut
270  
271 #######################################################################
272  
273 # Include the Global Configuration Processing Library
274 use HoneyClient::Util::Config qw(getVar);
275  
276 # Include Win32 Job Library
277 use Win32::Job;
278  
279 # Include Logging Library
280 use Log::Log4perl qw(:easy);
281  
282 # The global logging object.
283 our $LOG = get_logger();
284  
285 #######################################################################
286 # Public Methods Implemented #
287 #######################################################################
288  
289 =pod
290  
291 =head1 METHODS OVERRIDDEN
292  
293 The following functions have been overridden by the FF driver. All other
294 methods were implemented by the generic Browser driver. For further
295 information about the Browser driver, see the L<HoneyClient::Agent::Driver::Browser>
296 documentation.
297  
298 =head2 $object->drive(url => $url)
299  
300 =over 4
301  
302 Drives an instance of Mozilla Firefox for one iteration,
303 navigating either to the specified URL or to the next URL computed within
304 the Browser driver's internal hashtables.
305  
306 For a description of which hashtable is consulted upon each iteration of
307 drive(), see the B<next_link_to_visit> description of the
308 L<HoneyClient::Agent::Driver::Browser> documentation, in the
309 "DEFAULT PARAMETER LIST" section.
310  
311 Once a drive() iternation has completed, the corresponding browser process
312 is terminated. Thus, each call to drive() invokes a new instance of the
313 browser.
314  
315 I<Inputs>:
316 B<$url> is an optional argument, specifying the next immediate URL the browser
317 must drive to.
318  
319 I<Output>: The updated FF driver B<$object>, containing state information from driving the
320 browser for one iteration.
321  
322 B<Warning>: This method will B<croak>, if the FF driver object is B<unable>
323 to navigate to a new link, because its list of links to vist is empty and no new
324 URL was supplied.
325  
326 =back
327  
328 =begin testing
329  
330 # Generate a notice, to clarify our assumptions.
331 diag("");
332 diag("About to run basic FF-specific browser tests.");
333 diag("Note: These tests *require* network connectivity and");
334 diag("*expect* FF to be installed at the following location.");
335 diag("");
336  
337 my $processExec = getVar(name => "process_exec",
338 namespace => "HoneyClient::Agent::Driver::Browser::FF");
339 my $processName = getVar(name => "process_name",
340 namespace => "HoneyClient::Agent::Driver::Browser::FF");
341  
342 diag("Process Name:\t\t'" . $processName . "'");
343 diag("Process Location:\t'" . $processExec . "'");
344 diag("");
345 diag("If FF is installed in a different location or has a different executable name,");
346 diag("then please answer *NO* to the next question and update your etc/honeyclient.xml");
347 diag("file, changing the 'process_name' and 'process_exec' elements in the");
348 diag("<HoneyClient/><Agent/><Driver/><Browser/><FF/> section.");
349 diag("");
350 diag("Then, once updated, re-run these tests.");
351 diag("");
352  
353 my $question;
354 $question = prompt("# Do you want to run these tests?", "yes");
355 if ($question !~ /^y.*/i) {
356 exit;
357 }
358  
359 my $ie = HoneyClient::Agent::Driver::Browser::FF->new(test => 1);
360 is($ie->{test}, 1, "new(test => 1)") or diag("The new() call failed.");
361 isa_ok($ie, 'HoneyClient::Agent::Driver::Browser::FF', "new(test => 1)") or diag("The new() call failed.");
362  
363 diag("");
364 diag("About to drive FF to a specific website for *exactly* " . $ie->{timeout} . " seconds.");
365 diag("Note: Please do *NOT* close the browser manually; the test code should close it automatically.");
366 diag("");
367  
368 $question = prompt("# Which website should FF browse to?", "http://www.google.com");
369 $ie->drive(url => $question);
370  
371 diag("");
372 $question = prompt("# Did FF properly render the page and automatically exit?", "yes");
373 diag("");
374 if ($question !~ /^y.*/i) {
375 diag("Check your network connectivity and verify that you can manually browse this page in FF.");
376 diag("Then, re-run these tests.");
377 diag("");
378 diag("If the tests still do not work, please submit a ticket to:");
379 diag("http://www.honeyclient.org/trac/newticket");
380 diag("");
381 fail("The drive() call failed.");
382 }
383  
384 diag("About to restart FF. Please check if the \"Restore Previous Session\" dialog box appears.");
385 diag("");
386 $question = prompt("# Pick another website for FF to browse to:", "http://www.mitre.org");
387 $ie->drive(url => $question);
388  
389 diag("");
390 $question = prompt("# Did the \"Restore Previous Session\" dialog box appear?", "yes");
391 diag("");
392 if ($question !~ /^n.*/i) {
393 diag("You will need to disable the \"Restore Previous Session\" dialog box manually in Firefox.");
394 diag("Here's how:");
395 diag("1) Start up Firefox manually.");
396 diag("2) Go to 'about:config'.");
397 diag("3) Change the 'browser.sessionstore.resume_from_crash' value to 'false'.");
398 diag("");
399 diag("Then, re-run these tests.");
400 diag("");
401 diag("If the tests still do not work, please submit a ticket to:");
402 diag("http://www.honeyclient.org/trac/newticket");
403 diag("");
404 fail("The drive() call failed.");
405 }
406  
407 =end testing
408  
409 =cut
410  
411 sub drive {
412  
413 # Extract arguments.
414 my ($self, %args) = @_;
415  
416 # Sanity check: Make sure we've been fed an object.
417 unless (ref($self)) {
418 $LOG->error("Error: Function must be called in reference to a " .
419 __PACKAGE__ . "->new() object!");
420 Carp::croak "Error: Function must be called in reference to a " .
421 __PACKAGE__ . "->new() object!\n";
422 }
423  
424 # Sanity check, don't get the next link, if
425 # we've been fed a url.
426 my $argsExist = scalar(%args);
427 if (!$argsExist ||
428 !exists($args{'url'}) ||
429 !defined($args{'url'})) {
430 # Get the next URL from our hashtables.
431 $args{'url'} = $self->_getNextLink();
432 }
433  
434 # Drive the generic browser before opening with FF
435 $self = $self->SUPER::drive(%args);
436
437 # Sanity check: Make sure our next URL is defined.
438 unless (defined($args{'url'})) {
439 $LOG->error("Error: Unable to drive browser - no links left to browse!");
440 Carp::croak "Error: Unable to drive browser - no links left to browse!\n";
441 }
442  
443 # Indicates how long we wait for each drive operation to complete,
444 # before registering attempt as a failure.
445 my $timeout : shared = $self->timeout();
446  
447 # Create a new Job.
448 my $job = Win32::Job->new();
449  
450 # Sanity check.
451 if (!defined($job)) {
452 $LOG->error("Error: Unable to spawn a new process - " . $^E . ".");
453 Carp::croak "Error: Unable to spawn a new process - " . $^E . ".\n";
454 }
455  
456 # Spawn the job.
457 my $processExec = getVar(name => "process_exec");
458 my $processName = getVar(name => "process_name");
459 my $status = $job->spawn($processExec, $processName . " " . $args{'url'});
460  
461 # Sanity check.
462 if (!defined($status)) {
463 $LOG->error("Error: Unable to spawn a new browser - " . $^E . ".");
464 Carp::croak "Error: Unable to spawn a new browser - " . $^E . ".\n";
465 }
466  
467 # Run the job.
468 $job->run($timeout);
469  
470 # Check to see if run fails.
471 $status = $job->status();
472  
473 # Sanity check.
474 if (!defined($status) ||
475 !scalar(%{$status})) {
476 $LOG->error("Error: Unable to retrieve job status from spawned process.");
477 Carp::croak "Error: Unable to retrieve job status from spawned process.\n";
478 }
479  
480 # Figure out the correct Process ID.
481 my @keys = keys(%{$status});
482 my $processID = pop(@keys);
483  
484 # Sanity checks.
485 if (!defined($processID) ||
486 !exists($status->{$processID}->{'exitcode'}) ||
487 !defined($status->{$processID}->{'exitcode'})) {
488 $LOG->error("Error: Unable to retrieve job status from spawned process.");
489 Carp::croak "Error: Unable to retrieve job status from spawned process.\n";
490 }
491  
492 # TODO: We may want to report this suspicious activity back to the Agent;
493 # perhaps force the Agent to do an early integrity check, to make sure nothing
494 # sketchy is going on.
495  
496 # Check to make sure the exitcode is '293', meaning, that the
497 # application didn't unexpectedly die early.
498 if ($status->{$processID}->{'exitcode'} != 293) {
499 $LOG->warn("Unexpected: '" . $processName . "' process (ID = " . $processID . ") terminated early!");
500 }
501  
502 # Return the modified object state.
503 return $self;
504 }
505  
506 #######################################################################
507  
508 1;
509  
510 #######################################################################
511 # Additional Module Documentation #
512 #######################################################################
513  
514 __END__