source: trunk/plugins/nikto_core.plugin @ 438

Revision 438, 87.0 KB checked in by sullo, 3 years ago (diff)

Random updates

  • Property svn:keywords set to Id
Line 
1#VERSION,2.1.1
2# $Id$
3###############################################################################
4#  Copyright (C) 2006 CIRT, Inc.
5#
6#  This program is free software; you can redistribute it and/or
7#  modify it under the terms of the GNU General Public License
8#  as published by the Free Software Foundation; version 2
9#  of the License only.
10#
11#  This program is distributed in the hope that it will be useful,
12#  but WITHOUT ANY WARRANTY; without even the implied warranty of
13#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14#  GNU General Public License for more details.
15#
16#  You should have received a copy of the GNU General Public License
17#  along with this program; if not, write to the Free Software
18#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19###############################################################################
20# PURPOSE:
21# Nikto core functionality
22###############################################################################
23
24sub change_variables {
25
26    # $line is the unfiltered variable
27    my $line = $_[0];
28    my @subtests;    # @subtests is the returned array of expanded variables
29    my $cooked;
30
31    my $shname = $mark->{'hostname'} || $mark->{'ip'};
32    $line =~ s/\@IP/$mark->{'ip'}/g;
33    $line =~ s/\@HOSTNAME/$shname/g;
34    $line =~ s/JUNK\(([0-9]+)\)/LW2::utils_randstr($1)/e;
35
36    if ($line !~ "\@") {
37        push(@subtests, $line);
38    }
39    else {
40        foreach my $varname (keys %VARIABLES) {
41            if ($line =~ /$varname/) {
42
43                # We've found the variable; now to expand it!
44                foreach my $value (split(/ /, $VARIABLES{$varname})) {
45                    $cooked = $line;
46                    $cooked =~ s/$varname/$value/g;
47                    push(@subtests, change_variables($cooked));
48                }
49            }
50        }
51    }
52
53    return @subtests;
54}
55
56###############################################################################
57sub is_404 {
58    my ($uri, $content, $rescode, $loc_header) = @_;
59    $ext = get_ext($uri);
60
61    if (($FoF{$ext}{'mode'} eq "STD") && ($rescode =~ /4[0-9][0-9]/)) {
62        return 1;
63    }
64    elsif ($FoF{$ext}{'mode'} eq "REDIR") {
65        if (get_base_host($loc_header) eq $FoF{$ext}{'location'}) {
66            return 1;
67        }
68    }
69    elsif (($FoF{$ext}{'type'} eq "BLANK") && ($content eq "")) {
70        return 1;
71    }
72    elsif ($FoF{$ext}{'type'} eq "HASH") {
73        my $content = rm_active_content($content, $uri);
74        if (LW2::md4($content) eq $FoF{$ext}{'match'}) {
75            return 1;
76        }
77    }
78    else {
79        foreach my $string (keys %ERRSTRINGS) {
80            if ($content =~ /$string/i) {
81                return 1;
82            }
83        }
84    }
85
86    return 0;
87}
88
89###############################################################################
90sub nprint {
91    my $line   = shift;
92    my $mode   = shift;
93    my ($mark) = @_;
94    chomp($line);
95
96    # scrub values
97    if ($OUTPUT{'scrub'}) {
98
99        # name
100        $line =~ s/$mark->{'hostname'}/example.com/ig unless $mark->{'hostname'} eq '';
101
102        # ip
103        $line =~ s/$mark->{'ip'}/0.0.0.0/ig unless $mark->{'ip'} eq '';
104
105        # vhost
106        $line =~ s/$CLI{'vhost'}/example.com/ig unless $CLI{'vhost'} eq '';
107
108        # and in case we got here from set_target
109        $line =~ s/$mark->{'ident'}/example.com/ig unless $mark->{'ident'} eq '';
110    }
111
112    # don't print debug & verbose to output file...
113    if ($mode ne '') {
114        if ($mode eq "d" && $OUTPUT{'debug'}) {
115            print "D:" . localtime() . " $line\n";
116        }
117        if ($mode eq "v" && $OUTPUT{'verbose'}) {
118            print "V:" . localtime() . " $line\n";
119        }
120        if ($mode eq "e" && $OUTPUT{'errors'}) {
121            print "E:" . localtime() . " $line\n";
122        }
123        return;
124    }
125
126    # print errors to STDERR
127    if ($line =~ /^\+ ERROR\:/) { print STDERR "$line\n"; return; }
128
129    # don't print to STDOUT if output file is "-"
130    if ((defined $CLI{'file'}) && ($CLI{'file'} eq "-")) { return; }
131
132    # print to scan details to standard output if the users wants another format and is saving results to a file
133    $line =~ s/(CVE\-[12][0-9]{4}-[0-9]{4})/http:\/\/cve.mitre.org\/cgi-bin\/cvename.cgi?name\=$1/g;
134    $line =~ s/(CA\-[12][0-9]{3}-[0-9]{2})/http:\/\/www.cert.org\/advisories\/$1.html/g;
135    $line =~ s/BID\-([0-9]{4})/http:\/\/www.securityfocus.com\/bid\/$1/g;
136    $line =~ s/(MS[0-9]{2}\-[0-9]{3})/http:\/\/www.microsoft.com\/technet\/security\/bulletin\/$1.asp/gi;
137    print "$line\n";
138
139    return;
140}
141
142###############################################################################
143sub get_ext {
144    my $uri = $_[0] || return;
145    if ($uri =~ /\/$/) { return "DIRECTORY"; }
146    $uri =~ s/^.*\///;
147    $uri =~ s/(\?|\&|\%).*$//;
148    if ($uri =~ /^\.[^.%]/) { return "DOTFILE"; }
149    if ($uri !~ /\./) { return "NONE"; }
150    $uri =~ s/\".*$//;
151    $uri =~ s/^.*\.//;
152    return $uri;
153}
154
155###############################################################################
156sub date_disp {
157    my @time   = localtime($_[0]);
158    my $result = sprintf("%d-%02d-%02d %02d:%02d:%02d",
159                         $time[5] + 1900,
160                         $time[4] + 1,
161                         $time[3] + 1,
162                         $time[2], $time[1], $time[0]);
163    return $result;
164}
165
166###############################################################################
167sub get_base_host {
168    my $uri = $_[0] || return;
169
170    # uri, protocol, host, port, params, frag, user, password.
171    my @hd   = LW2::uri_split($uri);
172    my $base = $hd[1] . "://" . $hd[2];
173    if (($hd[3] != 80) && ($hd[3] != 443)) { $base .= ":" . $hd[3]; }
174    $base .= "/";
175    return $base;
176}
177
178###############################################################################
179sub map_codes {
180    my ($mark) = @_;
181    my %REQS;
182    my $rs = LW2::utils_randstr(8);
183    my ($res, $content, $error, %headers);
184
185    # / for OK response
186    ($res, $content, $error) = nfetch($mark, "/", "GET", "", \%headers, "", "map_codes");
187
188    if (defined $headers{'location'}) {
189        nprint("- Root page / redirects to: $result{'location'}");
190        if ($headers{'location'} =~ /^$mark->{'hostname'}/i)    # same host
191        {
192            my $uri = $headers{'location'};
193            %headers = ();
194            ($res, $content, $error) = nfetch($mark, "/", "GET", "", \%headers, "", "map_codes");
195        }
196        else                                                    # different host... ugh... guess
197        {
198            $FoF{'okay'}{'response'} = 200;
199            $FoF{'okay'}{'type'}     = "STD";
200        }
201    }
202    else {
203        $FoF{'okay'}{'response'} = $res;
204        my $cooked = rm_active_content($content);
205        $FoF{'okay'}{'type'}  = "HASH";
206        $FoF{'okay'}{'match'} = LW2::md4($cooked);
207    }
208
209    # these are some used in mutate that may not be in the db_tests
210    $db_extensions{'bak'}  = 1;
211    $db_extensions{'data'} = 1;
212    $db_extensions{'dbc'}  = 1;
213    $db_extensions{'dbf'}  = 1;
214    $db_extensions{'lst'}  = 1;
215    $db_extensions{'htx'}  = 1;
216
217    foreach my $ext (keys %db_extensions) {
218        if (   $ext ne "DIRECTORY"
219            && $ext ne "NONE"
220            && $ext ne "DOTFILE") {
221            $REQS{"/$rs.$ext"} = $ext;
222        }
223    }
224
225    # add those generic type holders back as real files
226    $REQS{"/$rs/"} = "DIRECTORY";
227    $REQS{"/$rs"}  = "NONE";
228    $REQS{"/.$rs"} = "DOTFILE";
229
230    foreach my $file (keys %REQS) {
231        nprint("- Testing error for file: $file\n", "v");
232        %headers = ();
233        ($res, $content, $error) = nfetch($mark, $file, "GET", "", \%headers, "", "map_codes");
234
235        $ext = $REQS{$file};
236        $FoF{$ext}{'response'} = $res;
237
238        # handle .com to .org redirs or whatnot
239        if (defined $headers{'location'}) {
240            $FoF{$ext}{'location'} = get_base_host($headers{'location'});
241        }
242
243        # if it is not specific type, figure out Content or HASH method...
244        if ($FoF{$ext}{'response'} eq 404) { $FoF{$ext}{'mode'} = "STD"; next; }
245        elsif ($FoF{$ext}{'response'} eq 200) { $FoF{$ext}{'mode'} = "OK"; }
246        elsif ($FoF{$ext}{'response'} eq 410) { $FoF{$ext}{'mode'} = "STD"; next; }
247        elsif ($FoF{$ext}{'response'} eq 401) { $FoF{$ext}{'mode'} = "STD"; next; }
248        elsif ($FoF{$ext}{'response'} eq 403) { $FoF{$ext}{'mode'} = "STD"; next; }
249        elsif ($FoF{$ext}{'response'} eq 300) { $FoF{$ext}{'mode'} = "REDIR"; next; }
250        elsif ($FoF{$ext}{'response'} eq 301) { $FoF{$ext}{'mode'} = "REDIR"; next; }
251        elsif ($FoF{$ext}{'response'} eq 302) { $FoF{$ext}{'mode'} = "REDIR"; next; }
252        elsif ($FoF{$ext}{'response'} eq 303) { $FoF{$ext}{'mode'} = "REDIR"; next; }
253        elsif ($FoF{$ext}{'response'} eq 307) { $FoF{$ext}{'mode'} = "REDIR"; next; }
254        else                                  { $FoF{$ext}{'mode'} = "OTHER"; }
255
256        # if we've got an OK/OTHER response, look at content first
257        # blank content, or hash...
258        if (length($content) == 0) {
259            $FoF{$ext}{'type'}  = "BLANK";
260            $FoF{$ext}{'match'} = "";
261        }
262        else {
263            my $cooked = rm_active_content($content);
264            $FoF{$ext}{'type'}  = "HASH";
265            $FoF{$ext}{'match'} = LW2::md4($cooked);
266        }
267    }
268
269    # lastly, get a hash of index.php so we can cut down on some false positives...
270    %headers = ();
271    ($res, $content, $error) = nfetch($mark, "/index.php?", "GET", "", \%headers, "", "map_codes");
272
273    my $cooked = rm_active_content($content);
274    $FoF{"index.php"}{'match'} = LW2::md4($cooked);
275    $FoF{"index.php"}{'type'}  = "HASH";
276
277    return;
278}
279
280###############################################################################
281sub rm_active_content {
282
283    # Try to remove active content which could mess up the file's signature
284    my $cont = $_[0];
285    my $file = $_[1];
286
287    # filename
288    if ($file ne '') {
289        $file =~ s/([^a-zA-Z0-9\s])/\\$1/g;
290        $cont =~ s/$file//g;
291    }
292
293    # Dates
294    $cont =~ s/([0-9]{4}|[0-9]{1,2})(\-|\.|\/)[0-9]{1,2}(\-|\.|\/)([0-9]{4}|[0-9]{1,2})//g;
295    $cont =~ s/(([0-9]{2}:[0-9]{2}(:)?([0-9]{2})?)|([0-9]{8,14}|[0-9]{6}))//g;
296    $cont =~
297      s/(mon|tue|wed|thu|fri|sat|sun)(,)? [0-9]{1,2} (jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec) [0-9]{4} ([0-9]{2}:[0-9]{2}(:)?([0-9]{2})?)?//ig;
298    $cont =~
299      s/([0-9]{2,4})? ?(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)([0-9]{2,4})?(\/)?([0-9]{2})?([0-9]{2})?//gi;
300
301    $cont =~ s/[0-9\.]+ second//gi;    # page load time
302    $cont =~ s/[0-9]+ queries//gi;     # wordpress
303
304    # URI, if provided, plus encoded versions of it
305    # $_[1] has unescaped file name, and $file has escaped. use appropriate one!
306    if (defined $file) {
307
308        # match pages which link to themselves w/diff args
309        my $e = $file;
310        $e    =~ s/^\/$file\??//;
311        $cont =~ s/$e//gs;
312
313        # again but with the index in place
314        $e = $file;
315        $cont =~ s/$e//gs;
316
317        # base 64
318        $e = LW2::encode_base64($_[1]);
319        $cont =~ s/$e//gs;
320
321        # hex encoded
322        $e = LW2::encode_uri_hex($_[1]);
323        $cont =~ s/$e//gs;
324
325        # unicode encoded
326        $e = LW2::encode_unicode($_[1]);
327        $cont =~ s/$e//gs;
328
329        # url encoding, full url
330        $e = $_[1];
331        $e    =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
332        $cont =~ s/$e//gs;
333
334        # url encoding, query portion
335        if ($file =~ /\?/) {
336            $e = $file;
337            $e =~ s/\?(.*$)//;
338            my $qs = $1;
339            $qs =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
340            $e .= "?$qs";
341            $cont =~ s/$e//gs;
342        }
343    }
344
345    return $cont;
346}
347
348###############################################################################
349sub dump_target_info {
350    my ($mark) = @_;
351    my $sslprint = "";
352
353    if ($mark->{ssl}) {
354        $sslprint = "$NIKTO{'DIV'}\n";
355        $sslprint .=
356            "+ SSL Info:        Ciphers: $mark->{'ssl_cipher'}\n" .
357            "                   Info:    $mark->{'ssl_cert_issuer'}\n" .
358            "                   Subject: $mark->{'ssl_cert_subject'}";
359    }
360
361    if ($mark->{ip} =~ /[a-z]/i) {
362        nprint("+ Target IP:       (proxied)", "", $mark);
363    }
364    else {
365        nprint("+ Target IP:          $mark->{ip}", "", $mark);
366    }
367
368    nprint("+ Target Hostname:    $mark->{hostname}", "", $mark);
369    nprint("+ Target Port:        $mark->{port}");
370    if ((defined $CLI{'vhost'}) && ($CLI{'vhost'} ne $mark->{hostname})) {
371        nprint("+ Virtual Host:   $CLI{'vhost'}", "", $mark);
372    }
373    if (defined $request{'whisker'}->{'proxy_host'}) {
374        nprint(
375            "- Proxy:              $request{'whisker'}->{'proxy_host'}:$request{'whisker'}->{'proxy_port'}"
376            );
377    }
378    if (defined $NIKTO{'hostid'}) {
379        nprint(
380            "- Host Auth:       ID: $NIKTO{'hostid'}, PW: $NIKTO{'hostpw'}, Realm: $NIKTO{'hostdomain'}",
381            "v"
382            );
383    }
384    if ($mark->{ssl}) {
385        nprint($sslprint);
386    }
387
388    if (defined $NIKTO{'anti_ids'} && defined $CLI{'evasion'}) {
389        for (my $i = 1 ; $i <= (keys %{ $NIKTO{'anti_ids'} }) ; $i++) {
390            if ($CLI{'evasion'} =~ /$i/) {
391                nprint("+ Using IDS Evasion:  $NIKTO{'anti_ids'}{$i}");
392            }
393        }
394    }
395    if (defined $NIKTO{'mutate_opts'} && defined $CLI{'mutate'}) {
396        for (my $i = 1 ; $i <= (keys %{ $NIKTO{'mutate_opts'} }) ; $i++) {
397            if ($CLI{'mutate'} =~ /$i/) {
398                nprint("+ Using Mutation:     $NIKTO{'mutate_opts'}{$i}");
399            }
400        }
401    }
402    my $time = date_disp($mark->{start_time});
403    nprint("+ Start Time:         $time");
404    nprint($NIKTO{'DIV'});
405
406    if ($mark->{banner} ne "") {
407        nprint("+ Server: $mark->{banner}");
408    }
409    else {
410        nprint("+ Server: No banner retrieved");
411    }
412
413    return;
414}
415
416###############################################################################
417sub general_config {
418    ## gotta set these first
419    $| = 1;
420
421    # This is used in dump_target_info(), not just help output
422    $NIKTO{'anti_ids'}{'1'} = "Random URI encoding (non-UTF8)";
423    $NIKTO{'anti_ids'}{'2'} = "Directory self-reference (/./)";
424    $NIKTO{'anti_ids'}{'3'} = "Premature URL ending";
425    $NIKTO{'anti_ids'}{'4'} = "Prepend long random string";
426    $NIKTO{'anti_ids'}{'5'} = "Fake parameter";
427    $NIKTO{'anti_ids'}{'6'} = "TAB as request spacer";
428    $NIKTO{'anti_ids'}{'7'} = "Change the case of the URL";
429    $NIKTO{'anti_ids'}{'8'} = "Use Windows directory separator (\\)";
430    $NIKTO{'anti_ids'}{'A'} = "Use a carriage return (0x0d) as a request spacer";
431    $NIKTO{'anti_ids'}{'B'} = "Use binary value 0x0b as a request spacer";
432
433    # This is used in dump_target_info(), not just help output
434    $NIKTO{'mutate_opts'}{'1'} = "Test all files with all root directories";
435    $NIKTO{'mutate_opts'}{'2'} = "Guess for password file names";
436    $NIKTO{'mutate_opts'}{'3'} = "Enumerate user names via Apache (/~user type requests)";
437    $NIKTO{'mutate_opts'}{'4'} =
438      "Enumerate user names via cgiwrap (/cgi-bin/cgiwrap/~user type requests)";
439    $NIKTO{'mutate_opts'}{'5'} =
440      "Attempt to brute force sub-domain names, assume that the host name is the parent domain";
441    $NIKTO{'mutate_opts'}{'6'} = "Attempt to guess directory names from the supplied dictionary file";
442
443    ### CLI STUFF
444    $CLI{'pause'} = $CLI{'html'} = $OUTPUT{'verbose'} = $CLI{'skiplookup'} =
445      $NIKTO{'totalrequests'} = $OUTPUT{'debug'} = $OUTPUT{'scrub'} = $OUTPUT{'errors'} = 0;
446    $CLI{'all_options'} = join(" ", @ARGV);
447
448    # preprocess CLI options which cannot be abbreviated
449    for (my $i = 0 ; $i <= $#ARGV ; $i++) {
450        if    ($ARGV[$i] eq '-dbcheck') { dbcheck(); }
451        elsif ($ARGV[$i] eq '-update')  { check_updates(); }
452    }
453
454    GetOptions("nolookup"         => \$CLI{'skiplookup'},
455               "config=s"         => \$CLI{'config'},
456               "Cgidirs=s"        => \$CLI{'forcecgi'},
457               "mutate=s"         => \$CLI{'mutate'},
458               "mutate-options=s" => \$CLI{'mutate-options'},
459               "id=s"             => \$CLI{'hostauth'},
460               "evasion=s"        => \$CLI{'evasion'},
461               "port=s"           => \$CLI{'ports'},
462               "findonly"         => \$CLI{'findonly'},
463               "root=s"           => \$CLI{'root'},
464               "timeout=s"        => \$CLI{'timeout'},
465               "Pause=s"          => \$CLI{'pause'},
466               "ssl"              => \$CLI{'ssl'},
467               "nocache"          => \$CLI{'nocache'},
468               "nossl"            => \$CLI{'nossl'},
469               "no404"            => \$CLI{'nofof'},
470               "useproxy"         => \$CLI{'useproxy'},
471               "Help"             => \$CLI{'help'},
472               "vhost=s"          => \$CLI{'vhost'},
473               "host=s"           => \$CLI{'host'},
474               "output=s"         => \$CLI{'file'},
475               "Format=s"         => \$CLI{'format'},
476               "Display=s"        => \$CLI{'display'},
477               "Single"           => \$CLI{'Single'},
478               "Tuning=s"         => \$CLI{'tuning'},
479               "Version"          => \$CLI{'version'},
480               "Plugins=s"        => \$CLI{'plugins'},
481               "list-plugins"     => \$CLI{'list-plugins'},
482               "ask=s"            => \$CLI{'ask'}
483               ) or usage(0);
484
485    if    ($CLI{'help'})         { usage(2); }
486    elsif ($CLI{'version'})      { version(); }
487    elsif ($CLI{'Single'})       { single(); }
488    elsif ($CLI{'list-plugins'}) { list_plugins(); }
489
490    # output file
491    if (!defined $CLI{'format'}) {
492
493        # Check what output has
494        $CLI{'format'} = "none";
495        if (defined $CLI{'file'}) {
496            $CLI{'format'} = lc($CLI{'file'});
497            $CLI{'format'} =~ s/(^.*\.)([^.]*$)/$2/g;
498        }
499    }
500
501    if    ($CLI{'format'} =~ /te?xt/i) { $CLI{'format'} = "txt"; }
502    elsif ($CLI{'format'} =~ /html?/i) { $CLI{'format'} = "htm"; }
503    elsif ($CLI{'format'} =~ /csv/i)   { $CLI{'format'} = "csv"; }
504    elsif ($CLI{'format'} =~ /nbe/i)   { $CLI{'format'} = "nbe"; }
505    elsif ($CLI{'format'} =~ /xml/i)   { $CLI{'format'} = "xml"; }
506    elsif ($CLI{'format'} eq 'none') { }
507    else                             { nprint("+ ERROR: Invalid output format"); exit; }
508
509    if ((defined $CLI{'file'}) && ($CLI{'format'} eq "")) {
510        nprint("+ERROR: Output file specified without a format");
511        exit;
512    }
513
514    # verify readable dtd
515    if ($CLI{'format'} eq 'xml' && !-r $NIKTOCONFIG{'NIKTODTD'}) {
516        nprint("+ ERROR: reading DTD");
517        exit;
518    }
519
520    # screen output
521    if (defined $CLI{'display'}) {
522        if ($CLI{'display'} =~ /d/i) { $OUTPUT{'debug'}   = 1; }
523        if ($CLI{'display'} =~ /v/i) { $OUTPUT{'verbose'} = 1; }
524        if ($CLI{'display'} =~ /s/i) { $OUTPUT{'scrub'}   = 1; }
525        if ($CLI{'display'} =~ /e/i) { $OUTPUT{'errors'}  = 1; }
526                if ($CLI{'display'} =~ /p/i) { $OUTPUT{'percent'} = 1; }
527    }
528
529    # port(s)
530    if (defined $CLI{'ports'}) {
531        $CLI{'ports'} =~ s/^\s+//;
532        $CLI{'ports'} =~ s/\s+$//;
533        if ($CLI{'ports'} =~ /[^0-9\-\, ]/) {
534            nprint("+ ERROR: Invalid port option '$CLI{'ports'}'");
535            exit;
536        }
537    }
538
539    # Fixup
540    if (defined $CLI{'root'}) {
541        $CLI{'root'} =~ s/\/$//;
542        if (($CLI{'root'} !~ /^\//) && ($CLI{'root'} ne "")) { $CLI{'root'} = "/$CLI{'root'}"; }
543    }
544
545    if (defined $CLI{'hostauth'}) {
546        my @x = split(/:/, $CLI{'hostauth'});
547        if (($#x > 2) || ($x[0] eq "")) {
548            nprint(
549                "+ ERROR: \'$CLI{'hostauth'}\' (-i option) syntax is 'user:password' or 'user:password:domain' for host authentication."
550                );
551            exit;
552        }
553    }
554
555    if (defined $CLI{'evasion'}) {
556        $CLI{'evasion'} =~ s/[^1-8AB]//g;
557    }
558
559    if (!defined $CLI{'plugins'} || $CLI{'plugins'} eq "") {
560        $CLI{'plugins'} = '@@DEFAULT';
561    }
562
563    # Mapping for mutate for plugins
564    if (defined $CLI{'mutate'}) {
565        nprint("- Mutate is deprecated, use -Plugins instead");
566        if ($CLI{'mutate'} =~ /1/ || $CLI{'mutate'} =~ /2/) {
567            my $parameters;
568            $parameters = "passfiles" if ($CLI{'mutate'} =~ /2/);
569            $parameters .= ",all" if ($CLI{'mutate'} =~ /1/);
570            $CLI{'plugins'} .= ';tests(' . $parameters . ')';
571        }
572        if ($CLI{'mutate'} =~ /3/ || $CLI{'mutate'} =~ /4/) {
573            my $parameters;
574            $parameters = "enumerate";
575            $parameters .= ",home"    if ($CLI{'mutate'} =~ /3/);
576            $parameters .= ",cgiwrap" if ($CLI{'mutate'} =~ /4/);
577            $parameters .= ",dictionary:" . $CLI{'mutate-opts'} if (defined $CLI{'mutate-opts'});
578            $CLI{'plugins'} .= ';apacheusers(' . $parameters . ')';
579        }
580        if ($CLI{'mutate'} =~ /5/) {
581            $CLI{'plugins'} .= ";subdomain";
582        }
583        if ($CLI{'mutate'} =~ /6/) {
584            $CLI{'plugins'} .= ';dictionary(dictionary:' . $CLI{'mutate-opts'} . ')';
585        }
586    }
587
588    # Asking questions?
589    if ($CLI{'ask'} =~ /^(auto|yes|no)$/) {
590        $NIKTOCONFIG{'UPDATES'} = $CLI{'ask'};    # override nikto.conf setting
591        undef($CLI{'ask'});
592    }
593
594    $NIKTO{'timeout'} = $CLI{'timeout'} || 10;
595
596    # Set up User-Agent
597    $NIKTO{'useragent'} = $NIKTOCONFIG{'USERAGENT'};
598    $NIKTO{'useragent'} =~ s/\@VERSION/$NIKTO{'version'}/g;
599    my $ev = $CLI{'evasion'} || "None";
600    $NIKTO{'useragent'} =~ s/\@EVASIONS/$ev/g;
601
602    # RFI URL -- push it to VARIABLES
603    if (defined $NIKTOCONFIG{'RFIURL'}) {
604        $VARIABLES{'@RFIURL'} = $NIKTOCONFIG{'RFIURL'};
605    }
606    else {
607        nprint(
608            "- ***** RFIURL is not defined in nikto.conf, which means no RFI tests will run *****");
609    }
610
611    # SSL Test
612    if (!LW2::ssl_is_available()) {
613        nprint("- ***** SSL support not available (see docs for SSL install instructions) *****");
614    }
615
616    # Notices
617    my $notice = "";
618    if (defined $CLI{'root'}) { $notice .= "Prepending \'$CLI{'root'}\' to requests"; }
619    if ($CLI{'pause'} > 0)    { $notice .= ", Pausing $CLI{'pause'} seconds per request"; }
620    $notice =~ s/^, //;
621    if ($notice ne '') { nprint("-***** $notice *****"); }
622
623    # get core version
624    open(FI, "<$NIKTOCONFIG{PLUGINDIR}/nikto_core.plugin");
625    my @F = <FI>;
626    close(FI);
627    my @VERS = grep(/^#VERSION/, @F);
628    $NIKTO{'core_version'} = $VERS[0];
629    $NIKTO{'core_version'} =~ s/\#VERSION,//;
630    chomp($NIKTO{'core_version'});
631    $NIKTO{'TMPL_HCTR'}    = 0;
632    $NIKTO{'TMPL_SUMMARY'} = 0;
633
634    return;
635}
636
637###############################################################################
638sub resolve {
639    my $ident = $_[0] || return;
640    my ($name, $ip, $dn) = "";
641
642    # ident is name, lookup IP
643    if ($ident =~ /[^0-9\.]/)    # not an IP, assume name
644    {
645        if ($CLI{'skiplookup'}) {
646            print("+ ERROR: -skiplookup set, but given name\n");
647            exit;
648        }
649        $ip = gethostbyname($ident);
650        if (   ($ip eq "")
651            && ($request{'whisker'}->{'proxy_host'} ne "")
652            )                    # can't resolve name to IP, but using proxy
653        {
654            $name = $ident;
655            $ip   = $name;
656        }
657        elsif (($ip eq "")
658            && ($request{'whisker'}->{'proxy_host'} eq "")) # can't resolve name to IP, no proxy set
659        {
660            nprint("+ ERROR: Cannot resolve hostname '$ident'\n");
661            return;
662        }
663        else {
664            use IO::Socket;
665            $ip = inet_ntoa($ip);
666            if (   ($ip !~ /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/)
667                && ($ip ne ""))                             # trap for proxy...
668            {
669                nprint("+ ERROR: Invalid IP '$ip'\n\n");
670                return;
671            }
672            $name = $ident;
673        }
674    }
675    else                                                    # ident is IP, lookup name
676    {
677        if (   ($ident !~ /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/)
678            && ($ident ne ""))                              # trap for proxy...
679        {
680            nprint("+ ERROR: Invalid IP '$ident'\n\n");
681            return;
682        }
683
684        $ip = $ident;
685        if (!$CLI{'skiplookup'}) {
686            use IO::Socket;
687            my $temp_ip = inet_aton($ip);
688            $name = gethostbyaddr($temp_ip, AF_INET);
689
690            # check reverse dns to avoid an inet_aton error
691            my $rdnsip = gethostbyname($name);
692            if ($rdnsip ne "") {
693                $rdnsip = inet_ntoa($rdnsip);
694                if ($ip ne $rdnsip) { $name = $ip; }    # Reverse DNS does not match
695            }
696            else { $name = $ip; }                       # Reverse DNS does not exist
697        }
698        if ($name eq "") { $name = $ip; }
699    }
700
701    # set displayname -- name takes precedence
702    if   ($name ne "") { $dn = $name; }
703    else               { $dn = $ip; }
704
705    return $name, $ip, $dn;
706}
707
708###############################################################################
709sub set_targets {
710    my ($hostlist, $portlist, $ssl, $root) = @_;
711    my $host_ctr = 1;
712    my @hosts    = split(/,/, $hostlist);
713    my @ports    = split(/,/, $portlist) if defined $portlist;
714    my (@checkhosts, @results, @marks);
715    my $defaultport = ($ssl) ? 443 : 80;
716
717    # Check for old style portlist and expand
718    my @newports;
719    foreach my $port (@ports) {
720        if ($port =~ /-/) {
721            my ($start, $end);
722            my @temp = split(/-/, $port);
723            $start = $temp[0];
724            $end   = $temp[1];
725            if ($start eq "") { $start = 0; }
726            if ($end   eq "") { $end   = 65535; }
727            if ($start > $end) {
728                nprint("+ ERROR port range $port doesn't make sense - assuming 80/tcp");
729                next;
730            }
731            for (my $i = $start ; $i <= $end ; $i++) {
732                push(@newports, $i);
733            }
734        }
735        else {
736            push(@newports, $port);
737        }
738    }
739    @ports = @newports;
740
741    nprint("- Getting targets", "v");
742    if (scalar(@ports) == 1) {
743
744        # Only one port is set, assume that is the default port
745        $defaultport = $ports[0];
746    }
747
748    # check whether it's a file or an entry
749    foreach my $host (@hosts) {
750        if (-e $host || $host eq "-") {
751            @results = parse_hostfile($host);
752            push(@checkhosts, @results);
753        }
754        else {
755            push(@checkhosts, $host);
756        }
757    }
758
759    # Now parse the list of checkhosts
760    foreach my $host (@checkhosts) {
761        my $defhost;
762        my $defport;
763        $host =~ s/\s+//g;
764        if (!defined $host) { next; }
765
766        # is it a URL?
767        if ($host =~ /^https?:\/\//) {
768            my @hostdata = LW2::uri_split($host);
769
770            $defhost = $hostdata[2];
771            $defport = $hostdata[3];
772
773            if ((!defined $root) && (defined $hostdata[0])) {
774                $root = $hostdata[0];
775                nprint("- Added -root value of '$root'", "d");
776            }
777        }
778        else {
779            my @h = split(/\:|\,/, $host);
780
781            $defhost = $h[0];
782            $defport = $h[1];
783        }
784
785        # Now skip through all ports if port hasn't been added
786        if ($defport eq "" && scalar(@ports) > 0) {
787
788            foreach $port (@ports) {
789                my $markhash = {};
790                $markhash->{ident} = $defhost;
791                $markhash->{port}  = $port;
792                nprint("- Target:$markhash->{ident} port:$markhash->{port}", "v", $markhash);
793                push(@marks, $markhash);
794            }
795        }
796        else {
797            if ($defport eq "") {
798                $defport = $defaultport;
799            }
800            my $markhash = {};
801            $markhash->{ident} = $defhost;
802            $markhash->{port}  = $defport;
803
804            nprint("- Target:$markhash->{ident} port:$markhash->{port}", "v", $markhash);
805            push(@marks, $markhash);
806        }
807    }
808
809    return @marks;
810}
811
812###############################################################################
813sub parse_hostfile {
814    my ($file) = @_;
815    my $nmap = 0;
816    my (@results, $hostdesc);
817
818    open(IN, $file) || die print STDERR "+ ERROR: Cannot open '$file':$@\n";
819    while (<IN>) {
820        my $found = 0;
821
822        # Check whether this is an nmap oG file
823        chomp;
824        if (/^# Nmap [0-9.]* scan initiated/) {
825            $nmap = 1;
826        }
827        s/\#.*$//;
828        if ($_ eq "") { next; }
829
830        # Parse for nmap files
831        if ($nmap == 1) {
832
833            # First get the host name
834            my @line = split(/ /);
835            my @name = split(/\(|\)/, $line[2]);
836            $hostdesc = ($name[1] ne "") ? $name[1] : $line[1];
837
838            # now parse the ports list
839            for (my $i = 3 ; $i <= $#line ; $i++) {
840                my @ports = split(/\//, $line[$i]);
841                if ($ports[1] eq "open" && $ports[4] eq "http") {
842                    $found = 1;
843                    $hostdesc .= ":" . $ports[0];
844                }
845            }
846        }
847        else {
848
849            # just add it to the list
850            $hostdesc = $_;
851            $found    = 1;
852        }
853        push(@results, $hostdesc) if ($found);
854    }
855    close(IN);
856    return (@results);
857}
858
859###############################################################################
860sub load_databases {
861    my @dbs = qw/db_404_strings  db_outdated  db_realms  db_tests  db_variables db_content_search/;
862    my $prefix = $_[0];
863
864    unless (defined $prefix) {
865        $prefix = "";
866    }
867
868    # verify required files
869    for my $file (@dbs) {
870        if (!-r "$NIKTOCONFIG{PLUGINDIR}/$file") {
871            die nprint("+ ERROR: Can't find/read required file \"$NIKTOCONFIG{PLUGINDIR}/$file\"");
872        }
873    }
874
875    for my $file (@dbs) {
876        my $filename = $NIKTOCONFIG{PLUGINDIR} . "/" . $prefix . $file;
877        if (!-r $filename) { next; }
878        open(IN, "<$filename") || die nprint("+ ERROR: Can't open \"$filename\":$!\n");
879
880        # db_tests
881        if ($file eq 'db_tests') { push(@DBFILE, <IN>); next; }
882
883        # all the other files require per-line processing
884        else {
885            my @file;
886
887            # Cleanup
888            while (<IN>) {
889                chomp;
890                $_ =~ s/#.*$//;
891                $_ =~ s/\s+$//;
892                $_ =~ s/^\s+//;
893                if ($_ ne "") { push(@file, $_); }
894            }
895
896            # db_variables
897            if ($file eq 'db_variables') {
898                foreach my $l (@file) {
899                    if ($l =~ /^@/) {
900                        my @temp = split(/=/, $l);
901                        $VARIABLES{ $temp[0] } .= "$temp[1]";
902                    }
903                }
904            }
905
906            # db_404_strings
907            elsif ($file eq 'db_404_strings') {
908                foreach my $l (@file) {
909                    $ERRSTRINGS{$l} = 1;
910                }
911            }
912
913            # db_content_search
914            elsif ($file eq 'db_content_search') {
915                foreach my $l (@file) {
916                    my @T = parse_csv($l);
917                    $CONTENTSEARCH{ $T[0] }{'osvdb'}   = $T[1];
918                    $CONTENTSEARCH{ $T[0] }{'string'}  = $T[2];
919                    $CONTENTSEARCH{ $T[0] }{'message'} = $T[3];
920                }
921            }
922
923            # db_outdated
924            elsif ($file eq 'db_outdated') {
925                foreach my $l (@file) {
926                    my @T = parse_csv($l);
927                    $OVERS{ $T[1] }{ $T[2] } = $T[3];
928                    $OVERS{ $T[1] }{'tid'} = $T[0];
929                }
930            }
931
932            # db_realms
933            elsif ($file eq 'db_realms') {
934                my $db_realms_ctr = keys %REALMS;
935                foreach my $l (@file) {
936                    my @t = parse_csv($l);
937                    $REALMS{$db_realms_ctr}{'tid'}   = $t[0];
938                    $REALMS{$db_realms_ctr}{'realm'} = $t[1];
939                    $REALMS{$db_realms_ctr}{'id'}    = $t[2];
940                    $REALMS{$db_realms_ctr}{'pw'}    = $t[3];
941                    $REALMS{$db_realms_ctr}{'msg'}   = $t[4];
942                    $db_realms_ctr++;
943                }
944
945                # Cheat and add CLI directly to REALMS
946                if (defined $CLI{'hostauth'}) {
947                    my @x = split(/:/, $CLI{'hostauth'});
948
949                    $REALMS{$db_realms_ctr}{'tid'}   = "700500";
950                    $REALMS{$db_realms_ctr}{'realm'} = (defined $x[2]) ? $x[2] : '@ANY';
951                    $REALMS{$db_realms_ctr}{'pw'}    = $x[1];
952                    $REALMS{$db_realms_ctr}{'id'}    = $x[0];
953                    $REALMS{$db_realms_ctr}{'msg'}   = "Credentials provided by CLI.";
954                }
955            }
956
957            close(IN);
958        }
959    }
960
961    return;
962}
963
964###############################################################################
965sub dbcheck {
966    my @dbs =
967      qw/db_headers db_httpoptions db_multiple_index db_server_msgs db_subdomains db_favicon db_embedded db_404_strings  db_outdated  db_realms  db_tests  db_variables db_content_search/;
968    my $prefix = $_[0];
969    if ($prefix eq "")  { nprint "\n-->\tNikto Databases\n"; }
970    if ($prefix eq "u") { nprint "\n-->\tUser Databases\n"; }
971
972    for my $file (@dbs) {
973        my $filename = $NIKTOCONFIG{PLUGINDIR} . "/" . $prefix . $file;
974        if (!-r $filename) { next; }
975        open(IN, "<$filename") || die nprint("+ ERROR: Can't open \"$filename\":$!\n");
976        nprint "Syntax Check: $filename\n";
977
978        if ($file eq 'db_outdated') {
979            foreach $line (<IN>) {
980                $line =~ s/^\s+//;
981                if ($line =~ /^\#/) { next; }
982                chomp($line);
983                if ($line eq "") { next; }
984                my @L = parse_csv($line);
985                if ($#L ne 3) { print STDERR "\t+ ERROR: Invalid syntax ($#L): $line\n"; next; }
986                $ENTRIES{"$L[0]"}++;
987            }
988            foreach $entry (keys %ENTRIES) {
989                if ($ENTRIES{$entry} > 1) {
990                    print STDERR "\t+ ERROR: Duplicate ($ENTRIES{$entry}): $entry\n";
991                }
992            }
993            nprint "\t" . keys(%ENTRIES) . " entries\n";
994        }
995        elsif ($file eq 'db_tests') {
996            my %ENTRIES;
997            foreach my $line (<IN>) {
998                if ($line !~ /^\"/) { next; }
999                my @L = parse_csv($line);
1000                if ($L[4] !~ /(GET|POST|TRACE|TRACK|OPTIONS|SEARCH|INDEX)/i) {
1001                    print STDERR "\t+ ERROR: Possibly invalid method: $L[4] on ($line)\n";
1002                }
1003                if ($L[5] eq "") { print STDERR "\t+ ERROR: blank conditional: $line"; next; }
1004                if ($line !~ /^\".*\",\".*\",\".*\",\".*\",\".*\"/) {
1005                    print STDERR "\t+ ERROR: Invalid syntax ($#L): $line\n";
1006                    next;
1007                }
1008                if ($line !~ /^(\".*\",){11}\".*\"/) {
1009                    print STDERR "\t+ ERROR: Invalid syntax ($#L): $line\n";
1010                    next;
1011                }
1012                if (($L[3] =~ /^\@CG/) && ($L[3] !~ /^\@CGIDIRS/)) {
1013                    print STDERR "\t+ ERROR: Possible \@CGIDIRS misspelling: $line";
1014                }
1015                if ($L[1] =~ /[^0-9]/) { print STDERR "\t+ ERROR: Invalid OSVDB ID: $line"; }
1016                $ENTRIES{"$L[3],$L[4],$L[5],$L[6],$L[7],$L[8],$L[9],$L[11],$L[12]"}++;
1017                if ((count_fields($line, 1) ne 12) && (count_fields($line) ne '')) {
1018                    print STDERR "\t+ ERROR: Invalid syntax: $line\n";
1019                }
1020            }
1021            foreach $entry (keys %ENTRIES) {
1022                if ($ENTRIES{$entry} > 1) {
1023                    print STDERR "\t+ ERROR: Duplicate ($ENTRIES{$entry}): $entry\n";
1024                }
1025            }
1026            nprint "\t" . keys(%ENTRIES) . " entries\n";
1027        }
1028        elsif ($file eq 'db_variables') {
1029            my $ctr = 0;
1030            foreach $line (<IN>) {
1031                if ($line !~ /^\@/)         { next; }
1032                if ($line !~ /^\@.+\=.+$/i) { print STDERR "\t+ ERROR: Invalid syntax: $line\n"; }
1033                $ctr++;
1034            }
1035            nprint "\t$ctr entries\n";
1036        }
1037        elsif ($file eq 'db_realms') {
1038            my $ctr = 0;
1039            foreach $line (<IN>) {
1040                if ((count_fields($line, 1) ne 4) && (count_fields($line) ne '')) {
1041                    print STDERR "\t+ ERROR: Invalid syntax: $line";
1042                }
1043                $ctr++;
1044            }
1045            nprint "\t$ctr entries\n";
1046        }
1047        elsif ($file eq 'db_404_strings') {
1048            my $ctr = 0;
1049            foreach $line (<IN>) {
1050
1051                # not really any syntax to check
1052                $ctr++;
1053            }
1054            nprint "\t$ctr entries\n";
1055        }
1056        elsif ($file eq 'db_headers') {
1057            my $ctr = 0;
1058            foreach $line (<IN>) {
1059                if ((count_fields($line) ne 0) && (count_fields($line) ne '')) {
1060                    print STDERR "\t+ ERROR: Invalid syntax: $line";
1061                }
1062                $ctr++;
1063            }
1064            nprint "\t$ctr entries\n";
1065        }
1066        elsif ($file eq 'db_multiple_index') {
1067            my $ctr = 0;
1068            foreach $line (<IN>) {
1069                if ((count_fields($line) ne 0) && (count_fields($line) ne '')) {
1070                    print STDERR "\t+ ERROR: Invalid syntax: $line";
1071                }
1072                $ctr++;
1073            }
1074            nprint "\t$ctr entries\n";
1075        }
1076        else {
1077
1078            # It's a file of standard DB type, we can do this intelligently
1079            my @headers;
1080            my $ctr = 0, $fields = 0;
1081            foreach $line (<IN>) {
1082
1083                # first, grab the headers
1084                if ($fields == 0) {
1085                    $line =~ s/\#.*//;
1086                    next if ($line eq "");
1087                    @headers = parse_csv($line);
1088                    $fields  = $#headers;
1089                    next;
1090                }
1091                if (   (count_fields($line, 1) != $fields - 1)
1092                    && (count_fields($line) ne '')) {
1093                    print STDERR "\t+ ERROR: Invalid syntax: $line";
1094                }
1095                $ctr++;
1096            }
1097            nprint "\t$ctr entries\n";
1098        }
1099
1100        close(IN);
1101    }
1102
1103    if ($_[0] eq "") { dbcheck('u'); }    # do this once
1104
1105    nprint "\n";
1106    exit;
1107}
1108
1109###############################################################################
1110sub count_fields {
1111    my $line    = $_[0] || return;
1112    my $checkid = $_[1] || 0;
1113    if ($line !~ /^\"/) { return; }
1114    chomp($line);
1115    $line =~ s/\s+$//;
1116    if ($line eq '') { return; }
1117    my @L = parse_csv($line);
1118    if ($checkid && ($L[0] ne 'nikto_id') && (($L[0] =~ /[^0-9]/) || ($L[0] eq ''))) { return -1; }
1119    return $#L;
1120}
1121
1122###############################################################################
1123sub port_check {
1124    my ($hostname, $ip, $port) = @_;
1125    my (%headers);
1126    my $m = {};
1127
1128    # Check SKIPPORTS
1129    if ($NIKTOCONFIG{'SKIPPORTS'} =~ /\b$port\b/) {
1130        nprint("+ ERROR: SKIPPORTS (nikto.conf) contains $port -- not checking");
1131        return 0;
1132    }
1133
1134    $m->{hostname} = $hostname;
1135    $m->{ip}       = $ip;
1136    $m->{port}     = $port;
1137    $m->{ssl}      = 0;
1138
1139    my @checktypes = ('HTTP', 'HTTPS');
1140    if ($CLI{'ssl'})   { shift(@checktypes); }
1141    if ($CLI{'nossl'}) { pop(@checktypes); }
1142
1143    foreach my $method (split(/ /, $NIKTOCONFIG{'CHECKMETHODS'})) {
1144        $request{'whisker'}->{'method'} = $method;
1145        foreach my $checkssl (@checktypes) {
1146            nprint("- Checking for $checkssl on port $ip:$port, using $method", "v", $m);
1147            $m->{ssl} = ($checkssl eq "HTTP") ? 0 : 1;
1148            proxy_check($m);
1149            my ($res, $content) = nfetch($m, "/", $method, "", \%headers, { noerror => 1 }, "Port Check");
1150
1151            if ($res) {
1152
1153      # this will fix for some Apaches that are smart enough to answer non ssl reqs on an ssl server
1154                if (defined $content
1155                    && $content =~ /speaking plain HTTP to an SSL/) {
1156                    dump_var("Result Hash", \%result);
1157                    next;
1158                }
1159                nprint("- $checkssl Server found: $ip:$port \t$headers{server}", "d", $m);
1160                return $m->{ssl} + 1;
1161            }
1162        }
1163    }
1164
1165    nprint("+ No web server found on $ip:$port");
1166    nprint("---------------------------------------------------------------------------");
1167
1168    return 0;
1169}
1170
1171###############################################################################
1172sub load_plugins {
1173    my @pluginlist = dirlist("$NIKTOCONFIG{PLUGINDIR}", '\.plugin$');
1174    my @all_names;
1175
1176    # populate plugin macros
1177    $NIKTOCONFIG{'@@NONE'} = "";
1178
1179    # Check if running plugins is NONE - if so, don't bother initalising
1180    # plugins
1181    if ($CLI{'plugins'} eq '@@NONE') {
1182        return;
1183    }
1184
1185    foreach my $plugin (@pluginlist) {
1186        my $plugin_name = $plugin;
1187        $plugin_name =~ s/\.plugin$//;
1188        my $plugin_init = $plugin_name . "_init";
1189        eval { require "$NIKTOCONFIG{PLUGINDIR}/$plugin"; };
1190        if ($@) {
1191            nprint("- Could not load or parse plugin: $plugin_name\n Error: ");
1192            warn $@;
1193            nprint("- The plugin could not be run.");
1194        }
1195        else {
1196            nprint("- Initialising plugin $plugin_name", "v");
1197
1198            # Call initialisation method
1199            if (defined &$plugin_init) {
1200                my $pluginhash = &$plugin_init;
1201
1202                # Add default weights if not already assigned
1203                $pluginhash->{recon_weight}  = 50 unless (defined $pluginhash->{recon_weight});
1204                $pluginhash->{scan_weight}   = 50 unless (defined $pluginhash->{scan_weight});
1205                $pluginhash->{report_weight} = 50 unless (defined $pluginhash->{report_weight});
1206                $pluginhash->{postfetch_weight} = 50
1207                  unless (defined $pluginhash->{postfetch_weight});
1208                $pluginhash->{postfetch_weight} = 50
1209                  unless (defined $pluginhash->{postfetch_weight});
1210                push(@all_names, $pluginhash->{name});
1211
1212                push(@PLUGINS, $pluginhash);
1213                nprint("- Loaded \"$pluginhash->{full_name}\" plugin.", "v");
1214            }
1215        }
1216    }
1217    $NIKTOCONFIG{'@@ALL'} = join(';', @all_names);
1218    my @torun = split(/;/, expand_pluginlist($CLI{'plugins'}, 0));
1219
1220    # Second pass to ensure that @@ALL is configured
1221    foreach my $plugin (@PLUGINS) {
1222
1223        # Check that the plugin is to be run
1224        # Perl doesn't allow us to use "in", pity
1225        foreach my $torun_plugin (@torun) {
1226
1227            # split up into parameters
1228            my $name = my $suffix = $torun_plugin;
1229            if ($torun_plugin =~ /\(/) {
1230                $name   =~ s/(.*)(\(.*\))/$1/;
1231                $suffix =~ s/(.*)(\(.*\))/$2/;
1232            }
1233            else {
1234                $name   = $torun_plugin;
1235                $suffix = "";
1236            }
1237            if ($plugin->{'name'} =~ /$name/i) {
1238                $plugin->{'run'} = 1;
1239
1240                # Create parameters
1241                if ($suffix ne "") {
1242                    my $parameters = {};
1243                    $suffix =~ s/(\()(.*[^\)])(\)?)/$2/;
1244                    foreach my $parameter (split(/,/, $suffix)) {
1245                        if ($parameter !~ /:/) {
1246                            $parameters->{$parameter} = 1;
1247                        }
1248                        else {
1249                            my $key = my $value = $parameter;
1250                            $key   =~ s/:.*//;
1251                            $value =~ s/.*://;
1252                            $parameters->{$key} = $value;
1253                        }
1254                    }
1255                    $plugin->{'parameters'} = $parameters;
1256                }
1257            }
1258        }
1259    }
1260
1261    # For speed in future, create a hash of active plugins ordered by plugin weight, for
1262    # each type of plugin
1263    my (@rplugins, @splugins, @repplugins, @pfplugins, @prefplugins);
1264    my (@rsorted,  @ssorted,  @repsorted,  @pfsorted,  @prefsorted);
1265    foreach my $plugin (@PLUGINS) {
1266        if ($plugin->{'run'} == 1) {
1267            if (defined $plugin->{recon_method}) {
1268                push(@rplugins, $plugin);
1269            }
1270            if (defined $plugin->{scan_method}) {
1271                push(@splugins, $plugin);
1272            }
1273            if (defined $plugin->{report_item}) {
1274                push(@repplugins, $plugin);
1275            }
1276            if (defined $plugin->{prefetch_method}) {
1277                push(@prefplugins, $plugin);
1278            }
1279            if (defined $plugin->{postfetch_method}) {
1280                push(@pfplugins, $plugin);
1281            }
1282        }
1283    }
1284
1285    # Now sort each array by weight
1286    @rsorted = sort { $a->{'weight'} <=> $b->{'weight'} } @rplugins;
1287    $PLUGINORDER{'recon'} = \@rsorted;
1288    @ssorted = sort { $a->{'weight'} <=> $b->{'weight'} } @splugins;
1289    $PLUGINORDER{'scan'} = \@ssorted;
1290    @repsorted = sort { $a->{'weight'} <=> $b->{'weight'} } @repplugins;
1291    $PLUGINORDER{'report'} = \@repsorted;
1292    @prefsorted = sort { $a->{'weight'} <=> $b->{'weight'} } @prefplugins;
1293    $PLUGINORDER{'prefetch'} = \@prefsorted;
1294    @pfsorted = sort { $a->{'weight'} <=> $b->{'weight'} } @pfplugins;
1295    $PLUGINORDER{'postfetch'} = \@pfsorted;
1296}
1297
1298###############################################################################
1299sub run_hooks {
1300    my ($mark, $type, $request, $result) = @_;
1301
1302    foreach my $plugin (@{ $PLUGINORDER{$type} }) {
1303        my ($run) = 1;
1304
1305        # first check for conditionals
1306        my $condition = $plugin->{ $type . '_cond' };
1307        if (defined $plugin->{ $type . '_cond' }) {
1308
1309            # Evaluate condition
1310            $run = eval($condition);
1311        }
1312
1313        if (!$run) { next; }
1314
1315        my $oldverbose = $OUTPUT{'verbose'};
1316        my $olddebug   = $OUTPUT{'debug'};
1317        my $olderrors  = $OUTPUT{'errors'};
1318        nprint("- Running $type for \"$plugin->{full_name}\" plugin", "v")
1319          unless ($type eq "prefetch" || $type eq "postfetch");
1320        if (defined $plugin->{'parameters'}->{'verbose'}
1321            && $plugin->{'parameters'}->{'verbose'} == 1) {
1322            $OUTPUT{'verbose'} = 1;
1323        }
1324        if (defined $plugin->{'parameters'}->{'debug'}
1325            && $plugin->{'parameters'}->{'debug'} == 1) {
1326            $OUTPUT{'debug'} = 1;
1327        }
1328        &{ $plugin->{ $type . '_method' } }($mark, $plugin->{'parameters'}, $request, $result);
1329        $OUTPUT{'verbose'} = $oldverbose;
1330        $OUTPUT{'debug'}   = $olddebug;
1331        $OUTPUT{'errors'}  = $olderrors;
1332    }
1333
1334    return $request, $result;
1335}
1336
1337###############################################################################
1338sub report_head {
1339    my ($format, $file) = @_;
1340    nprint("- Opening reports", "v");
1341
1342    # For tuning set up a list of report methods, formats and handles
1343
1344    # This is a frig until I can think of a better way of achieving it
1345    foreach my $i (1 .. 100) {
1346        foreach my $plugin (@PLUGINS) {
1347            if ($plugin->{run} && defined $plugin->{report_item} && $plugin->{report_weight} == $i)
1348            {
1349                my $run = 1;
1350
1351                # first check for conditionals
1352                if (defined $plugin->{report_format}) {
1353
1354                    # Evaluate condition
1355                    $run = ($format eq $plugin->{report_format});
1356                }
1357                if ($run) {
1358                    nprint("- Opening report for \"$plugin->{full_name}\" plugin", "v");
1359                    my $handle;
1360                    if (defined $plugin->{report_head}) {
1361                        $handle = &{ $plugin->{report_head} }($file);
1362                    }
1363
1364                    # Now store this
1365                    my $report_entry = { host_start => $plugin->{report_host_start},
1366                                         host_end   => $plugin->{report_host_end},
1367                                         item       => $plugin->{report_item},
1368                                         close      => $plugin->{report_close},
1369                                         handle     => $handle,
1370                                         };
1371                    push(@REPORTS, $report_entry);
1372                }
1373            }
1374        }
1375    }
1376    return;
1377}
1378
1379###############################################################################
1380sub report_host_start {
1381    my ($mark) = @_;
1382
1383    # Go through all reporting modules
1384    foreach my $reporter (@REPORTS) {
1385        if (defined $reporter->{host_start}) {
1386            &{ $reporter->{host_start} }($reporter->{handle}, $mark);
1387        }
1388    }
1389}
1390
1391###############################################################################
1392sub report_host_end {
1393    my ($mark) = @_;
1394
1395    # Go through all reporting modules
1396    foreach my $reporter (@REPORTS) {
1397        if (defined $reporter->{host_end}) {
1398            &{ $reporter->{host_end} }($reporter->{handle}, $mark);
1399        }
1400    }
1401}
1402
1403###############################################################################
1404sub report_item {
1405    my ($mark, $item) = @_;
1406
1407    # Go through all reporting modules
1408    foreach my $reporter (@REPORTS) {
1409        if (defined $reporter->{item}) {
1410            &{ $reporter->{item} }($reporter->{handle}, $mark, $item);
1411        }
1412    }
1413}
1414
1415###############################################################################
1416sub report_close {
1417
1418    # Go through all reporting modules
1419    foreach my $reporter (@REPORTS) {
1420        if (defined $reporter->{close}) {
1421            &{ $reporter->{close} }($reporter->{handle});
1422        }
1423    }
1424}
1425
1426###############################################################################
1427sub check_updates {
1428    LW2::http_init_request(\%request);
1429    my (%REMOTE, %LOCAL, @DBTOGET) = ();
1430    my ($pluginmsg, $remotemsg) = "";
1431    my $code_updates = 0;
1432    my $serverdir    = "/nikto/UPDATES/$NIKTO{'version'}";
1433
1434    # set up our mark
1435    my %mark = ('ident' => 'www.cirt.net',
1436                'ssl'   => 0,
1437                'port'  => 80
1438                );
1439    ($mark{'hostname'}, $mark{'ip'}, $mark{'display_name'}) = resolve('www.cirt.net');
1440
1441    for (my $i = 0 ; $i <= $#ARGV ; $i++) {
1442        if (($ARGV[$i] eq "-u") || ($ARGV[$i] eq "-useproxy")) {
1443            $CLI{'useproxy'} = 1;
1444            last;
1445        }
1446    }
1447
1448    # retrieve versions file
1449    (my $RES, $CONTENT) = nfetch(\%mark, "$serverdir/versions.txt", "GET");
1450    if ($RES eq 407) {
1451        if ($NIKTOCONFIG{'PROXYUSER'} eq "") {
1452            $NIKTOCONFIG{'PROXYUSER'} = read_data("Proxy ID: ",   "");
1453            $NIKTOCONFIG{'PROXYPASS'} = read_data("Proxy Pass: ", "noecho");
1454        }
1455
1456        # and try again
1457        ($RES, $CONTENT) = nfetch(\%mark, "$serverdir/versions.txt", "GET");
1458    }
1459
1460    if ($RES eq "") {
1461        ($RES, $CONTENT) = nfetch(\%mark, "$serverdir/versions.txt", "GET");
1462    }
1463
1464    if ($RES ne 200) {
1465        print STDERR
1466          "+ ERROR ($RES): Unable to get $request{'whisker'}->{'host'}$serverdir/versions.txt\n";
1467        exit;
1468    }
1469
1470    # make hash
1471    for (split(/\n/, $CONTENT)) {
1472        my @l = parse_csv($_);
1473        if ($_ =~ /^msg/) {
1474            $remotemsg = "$l[1]";
1475            next;
1476        }
1477        $REMOTE{ $l[0] } = $l[1];
1478    }
1479
1480    # get local versions of plugins/dbs
1481    my @NIKTOFILES = dirlist($NIKTOCONFIG{PLUGINDIR}, "");
1482
1483    foreach my $file (@NIKTOFILES) {
1484        my $v = "";
1485        open(LOCAL, "<$NIKTOCONFIG{PLUGINDIR}/$file")
1486          || print STDERR "+ ERROR: Unable to open '$NIKTOCONFIG{PLUGINDIR}/$file' for read: $@\n";
1487        my @l = <LOCAL>;
1488        close(LOCAL);
1489
1490        my @VERS = grep(/^#VERSION/, @l);
1491        chomp($VERS[0]);
1492        $LOCAL{$file} = (parse_csv($VERS[0]))[1];
1493    }
1494
1495    # check main nikto versions
1496    foreach my $remotefile (keys %REMOTE) {
1497        my @l = split(/\./, $LOCAL{$remotefile});
1498        my @r = split(/\./, $REMOTE{$remotefile});
1499        my $update=0;
1500        if ($LOCAL{$remotefile} eq '') { $update=1; }
1501        elsif ($r[0] > $l[0]) { $update=1; }
1502        elsif ($r[1] > $l[1]) { $update=1; }
1503        elsif ($r[2] > $l[2]) { $update=1; }
1504
1505        if ($update) {
1506                if ($remotefile eq "nikto") {
1507                                nprint "+ Nikto has been updated to $REMOTE{$remotefile}, local copy is $NIKTO{'version'}\n";
1508                                nprint "+ No update has taken place. Please upgrade Nikto by visiting http://$server/\n";
1509                                if ($remotemsg ne "") { nprint "+ $server message: $remotemsg\n"; }
1510                                exit;
1511                        }
1512                push(@DBTOGET, $remotefile);
1513                if ($remotefile !~ /^db_/) { $code_updates = 1; }
1514                }
1515        }
1516
1517    # replace local files if updated
1518    foreach my $toget (@DBTOGET) {
1519        nprint "+ Retrieving '$toget'\n";
1520        (my $RES, $CONTENT) = nfetch(\%mark, "$serverdir/$toget", "GET");
1521        if ($RES ne 200) {
1522            print STDERR "+ ERROR: Unable to get $server$serverdir/$toget\n";
1523            exit;
1524        }
1525        if ($CONTENT ne "") {
1526            open(OUT, ">$NIKTOCONFIG{PLUGINDIR}/$toget")
1527              || die print STDERR
1528              "+ ERROR: Unable to open '$NIKTOCONFIG{PLUGINDIR}/$toget' for write: $@\n";
1529            print OUT $CONTENT;
1530            close(OUT);
1531        }
1532    }
1533
1534    # CHANGES file
1535    if ($code_updates) {
1536        nprint "+ Retrieving 'CHANGES.txt'\n";
1537        (my $RES, $CONTENT) = nfetch(\%mark, "$serverdir/CHANGES.txt", "GET");
1538        if (($CONTENT ne "") && ($RES eq 200)) {
1539            open(OUT, ">$NIKTOCONFIG{DOCUMENTDIR}/CHANGES.txt")
1540              || die print STDERR
1541              "+ ERROR: Unable to open '$NIKTOCONFIG{DOCUMENTDIR}/CHANGES.txt' for write: $@\n";
1542            print OUT $CONTENT;
1543            close(OUT);
1544        }
1545    }
1546
1547    if ($#DBTOGET < 0) { nprint "+ No updates required.\n"; }
1548    if ($remotemsg ne "") { nprint "+ $server message: $remotemsg\n"; }
1549    exit;
1550}
1551
1552###############################################################################
1553# read_data ( prompt, mode )
1554# read STDIN data from the user
1555# portions of this (POSIX code) were taken from the
1556# Term::ReadPassword module by Tom Phoenix <rootbeer@redcat.com> (many thanks).
1557# it has been modified to not require Term::ReadLine, but still requires
1558# POSIX::Termios of it's a POSIX machine
1559###############################################################################
1560sub read_data {
1561    if ($NIKTOCONFIG{PROMPTS} =~ /no/i) { return; }
1562    my ($prompt, $mode, $POSIX) = @_;
1563    my $input = "";
1564
1565    if   ($^O =~ /Win32/) { $POSIX = 0; }
1566    else                  { $POSIX = 1; }
1567
1568    my %SPECIAL = ("\x03" => 'INT',    # Control-C, Interrupt
1569                   "\x08" => 'DEL',    # Backspace
1570                   "\x7f" => 'DEL',    # Delete
1571                   "\x0d" => 'ENT',    # CR, Enter
1572                   "\x0a" => 'ENT',    # LF, Enter
1573                   );
1574
1575    # if we're on a non-POSIX machine we can't not-echo the
1576    # characters, so just use getc to avoid the dependency on
1577    # POSIX::Termios. We would be best to get rid of this
1578    # entirely and use another way...
1579
1580    if ($POSIX) {
1581        local (*TTY, *TTYOUT);
1582        open TTY,    "<&STDIN"   or return;
1583        open TTYOUT, ">>&STDOUT" or return;
1584
1585        # Don't buffer it!
1586        select((select(TTYOUT), $| = 1)[0]);
1587        print TTYOUT $prompt;
1588
1589        # Remember where everything was
1590        my $fd_tty = fileno(TTY);
1591        my $term   = POSIX::Termios->new();
1592        $term->getattr($fd_tty);
1593        my $original_flags = $term->getlflag();
1594
1595        if ($mode eq "noecho") {
1596            my $new_flags = $original_flags & ~(ISIG | ECHO | ICANON);
1597            $term->setlflag($new_flags);
1598        }
1599        $term->setattr($fd_tty, TCSAFLUSH);
1600      KEYSTROKE:
1601        while (1) {
1602            my $new_keys = '';
1603            my $count = sysread(TTY, $new_keys, 99);
1604            if ($count) {
1605                for my $new_key (split //, $new_keys) {
1606                    if (my $meaning = $SPECIAL{$new_key}) {
1607                        if    ($meaning eq 'ENT') { last KEYSTROKE; }
1608                        elsif ($meaning eq 'DEL') { chop $input; }
1609                        elsif ($meaning eq 'INT') { last KEYSTROKE; }
1610                        else                      { $input .= $new_key; }
1611                    }
1612                    else { $input .= $new_key; }
1613                }
1614            }
1615            else { last KEYSTROKE; }
1616        }
1617
1618        # Done with waiting for input. Let's not leave the cursor sitting
1619        # there, after the prompt.
1620        print TTY "\n";
1621        nprint "\n";
1622
1623        # Let's put everything back where we found it.
1624        $term->setlflag($original_flags);
1625        $term->setattr($fd_tty, TCSAFLUSH);
1626        close(TTY);
1627        close(TTYOUT);
1628    }
1629    else    # non-POSIX
1630    {
1631        print $prompt;
1632        $input = <STDIN>;
1633        chomp($input);
1634    }
1635
1636    return $input;
1637}
1638
1639###############################################################################
1640sub proxy_setup {
1641    if (!$CLI{'useproxy'}) { return; }
1642
1643    # HTTP proxy
1644    $request{'whisker'}->{'proxy_host'} = $NIKTOCONFIG{PROXYHOST};
1645    $request{'whisker'}->{'proxy_port'} = $NIKTOCONFIG{PROXYPORT};
1646
1647    return;
1648}
1649
1650###############################################################################
1651sub proxy_check {
1652    my ($mark) = @_;
1653
1654    if (defined $request{'whisker'}->{'proxy_host'} && $CLI{'useproxy'})    # proxy is set up
1655    {
1656        LW2::http_close(\%request);    # force-close any old connections
1657        setup_hash(\%request, $mark, "Proxy Check");
1658        $request{'whisker'}->{'method'} = "GET";
1659        $request{'whisker'}->{'uri'}    = "/";
1660
1661        LW2::http_fixup_request(\%request);
1662
1663        if ($CLI{'pause'} > 0) { sleep $CLI{'pause'}; }
1664        LW2::http_do_request_timeout(\%request, \%result);
1665        $NIKTO{'totalrequests'}++;
1666        dump_var("Request Hash", \%request);
1667        dump_var("Result Hash",  \%result);
1668
1669        # First check that we can connect to the proxy
1670        if (exists $result{'whisker'}{'error'}) {
1671            if ($result{'whisker'}{'error'} =~ /Transport endpoint is not connected/) {
1672                nprint("+ ERROR: Could not connect to the defined proxy $NIKTOCONFIG{PROXYHOST}");
1673                exit 1;
1674            }
1675            nprint("+ ERROR: Proxy error: $result{'whisker'}{'error'}", "v");
1676        }
1677        if ($result{'whisker'}{'code'} eq "407")    # proxy requires auth
1678        {
1679
1680            # have id/pw?
1681            if ($NIKTOCONFIG{PROXYUSER} eq "") {
1682                $NIKTOCONFIG{PROXYUSER} = read_data("Proxy ID: ",   "");
1683                $NIKTOCONFIG{PROXYPASS} = read_data("Proxy Pass: ", "noecho");
1684            }
1685            if ($result{'proxy-authenticate'} !~ /Basic/i) {
1686                my @x = split(/ /, $result{'proxy-authenticate'});
1687                nprint(
1688                    "+ Proxy server uses '$x[0]' rather than 'Basic' authentication. $NIKTO{'name'} $NIKTO{'version'} can't do that."
1689                    );
1690                exit;
1691            }
1692
1693            # test it...
1694            LW2::http_close(\%request);    # force-close any old connections
1695            LW2::auth_set("proxy-basic", \%request, $NIKTOCONFIG{PROXYUSER},
1696                          $NIKTOCONFIG{PROXYPASS});    # set auth
1697            LW2::http_fixup_request(\%request);
1698            if ($CLI{'pause'} > 0) { sleep $CLI{'pause'}; }
1699            LW2::http_do_request_timeout(\%request, \%result);
1700            $NIKTO{'totalrequests'}++;
1701            dump_var("Request Hash", \%request);
1702            dump_var("Result Hash",  \%result);
1703
1704            if ($result{'proxy-authenticate'} ne "") {
1705                my @pauthinfo  = split(/ /, $result{'proxy-authenticate'});
1706                my @pauthinfo2 = split(/=/, $result{'proxy-authenticate'});
1707                $pauthinfo2[1] =~ s/^\"//;
1708                $pauthinfo2[1] =~ s/\"$//;
1709                nprint(
1710                    "+ Proxy requires authentication for '$pauthinfo[0]' realm '$pauthinfo2[1]', unable to authenticate."
1711                    );
1712                exit;
1713            }
1714            else { nprint("- Successfully authenticated to proxy.", "v"); }
1715        }
1716    }
1717
1718    return;
1719}
1720
1721###############################################################################
1722sub dirlist {
1723    my $DIR     = $_[0] || return;
1724    my $PATTERN = $_[1] || "";
1725    my @FILES_TMP = ();
1726
1727    opendir(DIRECTORY, $DIR) || die print STDERR "+ ERROR: Can't open directory '$DIR': $@";
1728    foreach my $file (readdir(DIRECTORY)) {
1729        if ($file =~ /^\./) { next; }    # skip hidden files, '.' and '..'
1730        if ($PATTERN ne "") {
1731            if ($file =~ /$PATTERN/) { push(@FILES_TMP, $file); }
1732        }
1733        else { push(@FILES_TMP, $file); }
1734    }
1735    closedir(DIRECTORY);
1736
1737    return @FILES_TMP;
1738}
1739
1740#######################################################################
1741sub dump_var {
1742    return if !$OUTPUT{'debug'};
1743    my $msg     = $_[0];
1744    my %hash_in = %{ $_[1] };
1745
1746    my $display = LW2::dump('', \%hash_in);
1747    $display =~ s/^\$/'$msg'/;
1748    if ($OUTPUT{'scrub'}) {
1749        $display =~ s/'host' => '.*',/'host' => 'example.com',/g;
1750        $display =~ s/'Host' => '.*'/'host' => 'example.com'/g;
1751    }
1752    nprint($display, "d");
1753    return;
1754}
1755
1756######################################################################
1757sub content_present {
1758    my $result = FALSE;
1759    my $res    = $_[0];
1760
1761    # perform an extra check just in case the web server lies about finds
1762    # basically assume that the value for a non-extension is the true
1763    # code for "File not Found".
1764    if ($res ne $FoF{'NONE'}{'response'}) {
1765        foreach $found (split(' ', $VARIABLES{"\@HTTPFOUND"})) {
1766            if ($res eq $found) {
1767                $result = TRUE;
1768            }
1769        }
1770    }
1771
1772    return $result;
1773}
1774
1775#######################################################################
1776sub setup_hash {
1777    my ($reqhash, $mark, $testid) = @_;
1778
1779    # Do the standard set up for the hash
1780    LW2::http_init_request($reqhash);
1781    $reqhash->{'whisker'}->{'ssl_save_info'}              = 1;
1782    $reqhash->{'whisker'}->{'lowercase_incoming_headers'} = 1;
1783    $reqhash->{'whisker'}->{'timeout'}                    = $NIKTO{'timeout'};
1784    if (defined $CLI{'evasion'}) {
1785        $reqhash->{'whisker'}->{'encode_anti_ids'} = $CLI{'evasion'};
1786    }
1787    $reqhash->{'User-Agent'} = $NIKTO{'useragent'};
1788    $reqhash->{'User-Agent'} =~ s/\@TESTID/$testid/;
1789    $reqhash->{'whisker'}->{'retry'} = 0;
1790    $reqhash->{'whisker'}->{'host'} = $mark->{'hostname'} || $mark->{'ip'};
1791
1792    if ($mark->{'vhost'}) {
1793        $request{'Host'} = $mark->{'vhost'};
1794    }
1795    $reqhash->{'whisker'}->{'port'} = $mark->{'port'};
1796    $reqhash->{'whisker'}->{'ssl'}  = $mark->{'ssl'};
1797
1798    # Proxy stuff
1799    if (defined $NIKTOCONFIG{PROXYHOST} && defined $CLI{'useproxy'}) {
1800        $reqhash->{'whisker'}->{'proxy_host'} = $NIKTOCONFIG{'PROXYHOST'};
1801        $reqhash->{'whisker'}->{'proxy_port'} = $NIKTOCONFIG{'PROXYPORT'};
1802        LW2::auth_set("proxy-basic", $reqhash, $NIKTOCONFIG{'PROXYUSER'},
1803                      $NIKTOCONFIG{'PROXYPASS'});
1804    }
1805
1806    return $reqhash;
1807}
1808
1809#######################################################################
1810sub cache_add {
1811    my $method        = shift;
1812    my $code          = shift;
1813    my $content       = shift;
1814    my $uri           = shift;
1815    my $postdata      = shift;
1816    my $flags_nocache = shift;
1817    my ($mark)        = @_;
1818
1819    if ((!defined $CLI{'nocache'}) && (!$flags_nocache)) {
1820        my $key =
1821          LW2::md5(  $mark->{'ip'}
1822                   . $mark->{'hostname'}
1823                   . $mark->{'port'}
1824                   . $mark->{'ssl'}
1825                   . $method
1826                   . $uri
1827                   . $postdata);
1828
1829        $CACHE{$key}{'method'}  = $method;
1830        $CACHE{$key}{'code'}    = $code;
1831        $CACHE{$key}{'content'} = $content;
1832    }
1833}
1834
1835#######################################################################
1836sub cache_fetch {
1837    my $method        = shift;
1838    my $uri           = shift;
1839    my $postdata      = shift;
1840    my $flags_nocache = shift;
1841    my ($mark)        = @_;
1842
1843    if ((!defined $CLI{'nocache'}) && (!$flags_nocache)) {
1844        my $key =
1845          LW2::md5(  $mark->{'ip'}
1846                   . $mark->{'hostname'}
1847                   . $mark->{'port'}
1848                   . $mark->{'ssl'}
1849                   . $method
1850                   . $uri
1851                   . $postdata);
1852
1853        if ($CACHE{$key}{'code'} ne '') {
1854            return (1, $CACHE{$key}{'code'}, $CACHE{$key}{'content'});
1855        }
1856        else {
1857            return 0;
1858        }
1859    }
1860    return 0;
1861}
1862
1863#######################################################################
1864sub nfetch {
1865    my ($mark, $uri, $method, $data, $headers, $flags, $testid) = @_;
1866    if ($CLI{'pause'} > 0) { sleep $CLI{'pause'}; }
1867    my (%request, %result);
1868    setup_hash(\%request, $mark, $testid);
1869
1870    if (defined $CLI{'root'}) {
1871        $request{'whisker'}->{'uri'} = $CLI{'root'} . $uri;    # prepend -root option value
1872        }
1873    else {
1874        $request{'whisker'}->{'uri'} = $uri;
1875        }
1876    $request{'whisker'}->{'method'} = $method;
1877
1878    if ($data ne "") {
1879        $data =~ s/\\\"/\"/g;
1880        $request{'whisker'}->{'data'} = $data;
1881    }
1882
1883    # check for extra HTTP headers
1884    if (defined $headers) {
1885        # loop through the hash ref passed and add each header to request
1886        while (my ($key, $value) = each(%$headers)) {
1887            $request{$key} = $value;
1888        }
1889    }
1890    LW2::http_fixup_request(\%request) unless ($flags->{'noclean'});
1891
1892    # Run pre hooks
1893    (%$request, %$result) = run_hooks($mark, "prefetch", \%request, \%result);
1894
1895    # Check cache
1896    my $incache = 0;
1897    nprint("- Checking $uri in cache.", "d");
1898    ($incache, my $code, my $content) =
1899      cache_fetch($request{'whisker'}->{'method'}, $uri, $data, $flags->{'nocache'}, $mark);
1900    if ($incache) {
1901        $result{'whisker'}->{'code'} = $code;
1902        $result{'whisker'}->{'data'} = $content;
1903    }
1904
1905    if (!$incache) {
1906        LW2::http_do_request_timeout(\%request, \%result);
1907        $NIKTO{'totalrequests'}++;
1908        cache_add($request{'whisker'}->{'method'},
1909                  $result{'whisker'}->{'code'},
1910                  $result{'whisker'}->{'data'},
1911                  $uri, $data, $flags->{'nocache'}, $mark);
1912
1913        if ($OUTPUT{'debug'}) {
1914            dump_var("Request Hash", \%request);
1915            dump_var("Result Hash",  \%result);
1916        }
1917
1918        # Snarf what we can from the whisker hash and put in mark
1919                if (!exists $result{'whisker'}->{'error'}) {           
1920                        if (!exists $mark->{'banner'}) {
1921                                $mark->{'banner'} = $result{'server'};
1922                        }
1923                        else {
1924                                # Check banner hasn't changed
1925                                if (exists $result{'server'} && $mark->{'banner'} ne $result{'server'}) {
1926                                        nprint("+ Server banner has changed from $mark->{banner} to $result{server}, this may suggest a WAF is in place");
1927                                }
1928                        }
1929                       
1930                        if (!exists $mark->{'ssl_cipher'} && $mark->{'ssl'}) {
1931                                # Grab ssl details
1932                                $mark->{'ssl_cipher'} = $result{'whisker'}->{'ssl_cipher'};
1933                                $mark->{'ssl_cert_issuer'} = $result{'whisker'}->{'ssl_cert_issuer'};
1934                                $mark->{'ssl_cert_subject'} = $result{'whisker'}->{'ssl_cert_subject'};
1935                        }
1936                }
1937    }
1938    nprint("- $result{'whisker'}{'code'} for $method:\t$uri", "v");
1939
1940    # Check for errors to reduce false positives
1941    if (defined $result{'whisker'}->{'error'} && !exists $flags->{'noerror'}) {
1942        $mark->{'total_errors'}++;
1943        nprint("+ ERROR: $uri returned an error: $result{'whisker'}{'error'}\n", "e");
1944    }
1945
1946    if (   defined $CLI{'display'}
1947        && ($CLI{'display'} =~ /2/)
1948        && (defined($result{'whisker'}->{'cookies'}))) {
1949        foreach my $c (@{ $result{'whisker'}->{'cookies'} }) {
1950            nprint("+ $uri sent cookie: $c");
1951        }
1952    }
1953
1954    # If headers is defined, copy the whisker headers to the hash
1955    if (defined $headers) {
1956
1957        # First clear the hash
1958        foreach my $header (keys %$headers) {
1959            delete($headers->{$header});
1960        }
1961        while (my ($key, $value) = each(%result)) {
1962            if ($key ne "whisker" && $key ne "connection") {
1963                $headers->{$key} = $value;
1964            }
1965        }
1966    }
1967
1968    # Run post hooks
1969    (%$request, %$result) = run_hooks($mark, "postfetch", \%request, \%result);
1970
1971    return $result{'whisker'}->{'code'}, $result{'whisker'}->{'data'},
1972      $result{'whisker'}->{'error'};
1973}
1974
1975#######################################################################
1976sub set_scan_items {
1977
1978    # load the tests
1979    %TESTS = ();
1980    my @SKIPLIST = ();
1981    if (defined $NIKTOCONFIG{SKIPIDS}) {
1982        @SKIPLIST = split(/ /, $NIKTOCONFIG{SKIPIDS});
1983    }
1984
1985    # now load checks
1986    foreach my $line (@DBFILE) {
1987        if ($line =~ /^\"/)    # check
1988        {
1989            chomp($line);
1990            my @item = parse_csv($line);
1991            my $add  = 1;
1992
1993            # check tuning options
1994            if ((defined $CLI{'tuning'}) && (defined $item[2])) {
1995
1996                # Work out the required tuning from the CLI string
1997                my $exclude = 0;
1998                foreach my $tune (split(//, $CLI{'tuning'})) {
1999                    if ($tune eq "x") {
2000                        $exclude = 1;
2001                        next;
2002                    }
2003                    if ($exclude == 0) {
2004                        if ($item[2] !~ /$tune/) { $add = 0; }
2005                        next;
2006                    }
2007                    if ($exclude == 1) {
2008                        if ($item[2] =~ /$tune/) { $add = 0; }
2009                    }
2010                }
2011            }
2012
2013            # Skip list
2014            foreach my $id (@SKIPLIST) {
2015                if ($id eq $item[0]) { $add = 0; }
2016            }
2017
2018            # RFI URL Defined?
2019            if (($item[2] =~ /c/) && ($VARIABLES{'@RFIURL'} eq '')) {
2020                $add = 0;
2021            }
2022
2023            if ($add) {
2024                my $ext = get_ext($item[3]);
2025                $db_extensions{$ext} = 1;
2026
2027                # This escapes regex characters in the conditionals.
2028                # This will have to change if regex is ever allowed in the db
2029                for (my $y = 5 ; $y <= 9 ; $y++) { $item[$y] =~ s/([^a-zA-Z0-9\s])/\\$1/g; }
2030
2031                $NIKTO{total_checks}++;
2032                $TESTS{ $item[0] }{'uri'}         = $item[3];
2033                $TESTS{ $item[0] }{'osvdb'}       = $item[1];
2034                $TESTS{ $item[0] }{'method'}      = $item[4];
2035                $TESTS{ $item[0] }{'match_1'}     = $item[5];
2036                $TESTS{ $item[0] }{'match_1_or'}  = $item[6];
2037                $TESTS{ $item[0] }{'match_1_and'} = $item[7];
2038                $TESTS{ $item[0] }{'fail_1'}      = $item[8];
2039                $TESTS{ $item[0] }{'fail_2'}      = $item[9];
2040                $TESTS{ $item[0] }{'message'}     = $item[10];
2041                $TESTS{ $item[0] }{'data'}        = $item[11];
2042                $TESTS{ $item[0] }{'headers'}     = $item[12];
2043            }
2044        }
2045    }
2046
2047    undef @DBFILE;    # this memory hog is no longer needed!
2048    nprint("- $NIKTO{'total_checks'} server checks loaded", "v");
2049    if ($NIKTO{'total_checks'} eq 0 && !defined $CLI{'tuning'}) {
2050        nprint("+ Unable to load valid checks!");
2051        exit;
2052    }
2053    return;
2054}
2055
2056#######################################################################
2057sub max_test_id {
2058    return (sort { $a <=> $b } keys %TESTS)[-1];
2059}
2060
2061#######################################################################
2062sub char_escape {
2063    $_[0] =~ s/([^a-zA-Z0-9 ])/\\$1/g;
2064    return $_[0];
2065}
2066
2067#######################################################################
2068sub parse_csv {
2069    my $text = $_[0] || return;
2070    my @new = ();
2071    push(@new, $+) while $text =~ m{
2072      "([^\"\\]*(?:\\.[^\"\\]*)*)",?
2073       |  ([^,]+),?
2074       | ,
2075   }gx;
2076    push(@new, undef) if substr($text, -1, 1) eq ',';
2077    return @new;
2078}
2079
2080#######################################################################
2081sub version {
2082    my @NIKTOFILES = dirlist($NIKTOCONFIG{PLUGINDIR}, "(^nikto|^db_)");
2083    nprint "$NIKTO{'DIV'}\n";
2084    nprint "$NIKTO{'name'} Versions\n";
2085    nprint "$NIKTO{'DIV'}\n";
2086    nprint "File                               Version      Last Mod\n";
2087    nprint "-----------------------------      --------     ----------\n";
2088    nprint "Nikto main                         $NIKTO{'version'}\n";
2089    nprint "LibWhisker                         $LW2::VERSION\n";
2090
2091    foreach my $FILE (sort @NIKTOFILES) {
2092        open(FI, "<$NIKTOCONFIG{PLUGINDIR}/$FILE")
2093          || die print STDERR "+ ERROR: Unable to open '$NIKTOCONFIG{PLUGINDIR}/$FILE': $!\n";
2094        my @F = <FI>;
2095        close(FI);
2096        my @VERS = grep(/^#VERSION/, @F);
2097        my @MODS = grep(/^# \$Id:/,  @F);
2098        chomp($VERS[0]);
2099        chomp($MODS[0]);
2100        my @modification = split(/ /, $MODS[0]);
2101        $VERS[0] =~ s/^#VERSION,//;
2102        my $ws1 = (35 - length($FILE));
2103        my $ws2 = (13 - length($VERS[0]));
2104        nprint "$FILE" . " " x $ws1 . "$VERS[0]" . " " x $ws2 . "$modification[4]\n";
2105    }
2106    nprint "$NIKTO{'DIV'}\n";
2107
2108    exit;
2109}
2110
2111#######################################################################
2112sub send_updates {
2113    return if ($NIKTOCONFIG{'UPDATES'} !~ /yes|auto/i);
2114
2115    my $have_updates = 0;
2116    my ($updated_version, $answer, $RES);
2117    foreach my $ver (keys %UPDATES) {
2118
2119        # ignore useless ones...
2120        if ($ver !~ /[0-9]/) { next; }
2121        elsif ($ver eq "Win32")          { next; }
2122        elsif ($ver eq "(Win32)")        { next; }
2123        elsif ($ver eq "Linux-Mandrake") { next; }
2124        $have_updates = 1;
2125        $updated_version .= "$ver ";
2126    }
2127
2128    if ((!$have_updates) || ($updated_version eq "")) { return; }
2129
2130    # make sure the db_outdatedb isn't *too* old
2131    open(OD, "<$NIKTOCONFIG{PLUGINDIR}/db_outdated")
2132      || die print STDERR "+ ERROR: Unable to open '$NIKTOCONFIG{PLUGINDIR}/db_outdated': $!\n";
2133    @F = <OD>;
2134    close(OD);
2135
2136    my @LASTUPDATED = grep(/^\# \$Id: db_outdated/, @F);
2137    $LASTUPDATED[0] =~ /([0-9]{4}\-[0-9]{2})/;
2138    $lm = $1;
2139    $lm =~ s/\-//g;
2140
2141    my @NOW = localtime(time);
2142    $NOW[5] += 1900;
2143    $NOW[4]++;
2144    if ($NOW[4] < 10) { $NOW[4] = "0$NOW[4]"; }
2145    my $now = "$NOW[5]$NOW[4]";
2146    if (($now - $lm) > 120) { return; }    # DB is 4 months old... ignore the updates!
2147
2148    $updated_version =~ s/\s+$//;
2149    $updated_version =~ s/^\s+//;
2150
2151    if ($NIKTOCONFIG{'UPDATES'} eq "auto") {
2152        $answer = "y";
2153    }
2154    else {
2155        $answer = read_data(
2156            "\n
2157      *********************************************************************
2158      Portions of the server's ident string ($updated_version) are not in
2159      the Nikto database or is newer than the known string. Would you like
2160      to submit this information (*no server specific data*) to CIRT.net
2161      for a Nikto update (or you may email to sullo\@cirt.net) (y/n)? ", ""
2162        );
2163    }
2164
2165    if ($answer !~ /y/i) { return; }
2166
2167    # set up our mark
2168    my %mark = ('ident' => 'www.cirt.net',
2169                'ssl'   => 0,
2170                'port'  => 80
2171                );
2172    ($mark{'hostname'}, $mark{'ip'}, $mark{'display_name'}) = resolve('www.cirt.net');
2173
2174    for (my $i = 0 ; $i <= $#ARGV ; $i++) {
2175        if (($ARGV[$i] eq "-u") || ($ARGV[$i] eq "-useproxy")) {
2176            $CLI{'useproxy'} = 1;
2177            last;
2178        }
2179    }
2180
2181    ($RES, $CONTENT) = nfetch(\%mark, "/cgi-bin/versions?DATA=$updated_version", "GET");
2182
2183    if ($RES eq 407) {
2184        if ($NIKTOCONFIG{PROXYUSER} eq "") {
2185            $NIKTOCONFIG{PROXYUSER} = read_data("Proxy ID: ",   "");
2186            $NIKTOCONFIG{PROXYPASS} = read_data("Proxy Pass: ", "noecho");
2187        }
2188        ($RES, $CONTENT) = nfetch(\%mark, "/cgi-bin/versions?DATA=$updated_version", "GET");
2189    }
2190
2191    if ($RES eq "") {
2192        LW2::http_close(\%request);    # force-close any old connections
2193        $mark{'ip'} = $NIKTOCONFIG{CIRT};
2194        ($RES, $CONTENT) = nfetch(\%mark, "/cgi-bin/versions?DATA=$updated_version", "GET");
2195    }
2196
2197    if ($CONTENT !~ /SUCCESS/) {
2198        print STDERR "+ ERROR: ($RES, $CONTENT): Unable to send update info to CIRT.net\n";
2199    }
2200    else {
2201        nprint "- Sent updated info to CIRT.net -- Thank you!\n";
2202    }
2203
2204    return;
2205}
2206
2207#######################################################################
2208sub usage {
2209    if ($_[0] eq 2) {
2210        print "
2211   Options:
2212       -ask+               Whether to ask about submitting updates
2213                               yes   Ask about each (default)
2214                               no    Don't ask, don't send
2215                               auto  Don't ask, just send
2216       -config+            Use this config file
2217       -Cgidirs+           Scan these CGI dirs: \"none\", \"all\", or values like \"/cgi/ /cgi-a/\"
2218       -Display+           Turn on/off display outputs:
2219                               1     Show redirects
2220                               2     Show cookies received
2221                               3     Show all 200/OK responses
2222                               4     Show URLs which require authentication
2223                               V     Verbose output
2224                               D     Debug output
2225                               E     Display all HTTP errors
2226       -dbcheck           Check database and other key files for syntax errors (cannot be abbreviated)
2227       -evasion+          IDS evasion technique:\n";
2228
2229        foreach my $k (sort keys %{ $NIKTO{'anti_ids'} }) {
2230            print "                               $k     $NIKTO{'anti_ids'}{$k}\n";
2231        }
2232
2233        print "       -findonly          Find http(s) ports only, don't perform a full scan
2234       -Format+           Save file (-o) format:
2235                               csv   Comma-separated-value
2236                               htm   HTML Format
2237                               nbe   Nessus NBE format
2238                               txt   Plain text (default if not specified)
2239                               xml   XML Format
2240       -host+             Target host
2241       -Help              Extended help information
2242       -id+               Host authentication to use, format is userid:password
2243       -list-plugins      List all available plugins, perform no testing
2244       -mutate+           Guess additional file names:\n";
2245
2246        foreach my $k (sort keys %{ $NIKTO{'mutate_opts'} }) {
2247            print "                               $k     $NIKTO{'mutate_opts'}{$k}\n";
2248        }
2249
2250        print "       -mutate-options    Provide information for mutates
2251       -nocache           Disables the URI cache
2252       -nossl             Disables using SSL
2253       -no404             Disables nikto attempting to guess a 404 page
2254       -output+           Write output to this file
2255       -Plugins           List of plugins to run (default ALL)
2256       -port+             Port to use (default 80)
2257       -Pause+            Pause between tests (seconds)
2258       -root+             Prepend root value to all requests, format is /directory
2259       -ssl               Force ssl mode on port
2260       -Single            Single request mode
2261       -timeout+          Timeout (default 2 seconds)
2262       -Tuning+           Scan tuning:
2263                               1     Interesting File / Seen in logs
2264                               2     Misconfiguration / Default File
2265                               3     Information Disclosure
2266                               4     Injection (XSS/Script/HTML)
2267                               5     Remote File Retrieval - Inside Web Root
2268                               6     Denial of Service
2269                               7     Remote File Retrieval - Server Wide
2270                               8     Command Execution / Remote Shell
2271                               9     SQL Injection
2272                               0     File Upload
2273                               a     Authentication Bypass
2274                               b     Software Identification
2275                               c     Remote Source Inclusion
2276                               x     Reverse Tuning Options (i.e., include all except specified)
2277       -useproxy          Use the proxy defined in nikto.conf
2278       -update            Update databases and plugins from cirt.net (cannot be abbreviated)
2279       -Version           Print plugin and database versions
2280       -vhost+            Virtual host (for Host header)
2281   + requires a value
2282   ";
2283    }
2284    else {
2285        print "
2286       -config+            Use this config file
2287       -Cgidirs+           scan these CGI dirs: 'none', 'all', or values like \"/cgi/ /cgi-a/\"
2288       -dbcheck            check database and other key files for syntax errors (cannot be abbreviated)
2289       -evasion+           ids evasion technique
2290       -Format+            save file (-o) format
2291       -host+              target host
2292       -Help               Extended help information
2293       -id+                host authentication to use, format is userid:password
2294       -list-plugins       List all available plugins
2295       -mutate+            Guess additional file names
2296       -mutate-options+    Provide extra information for mutations
2297       -output+            Write output to this file
2298       -nocache            Disables the URI cache
2299       -nossl              Disables using SSL
2300       -no404              Disables 404 checks
2301       -Plugins                List of plugins to run (default ALL)
2302       -port+              Port to use (default 80)
2303           -root+                          Prepend root value to all requests, format is /directory
2304       -Display+           Turn on/off display outputs
2305       -ssl                Force ssl mode on port
2306       -Single             Single request mode
2307       -timeout+           Timeout (default 2 seconds)
2308       -Tuning+            Scan tuning
2309       -update             Update databases and plugins from cirt.net (cannot be abbreviated)
2310       -Version            Print plugin and database versions
2311       -vhost+             Virtual host (for Host header)
2312   + requires a value
2313   ";
2314    }
2315    exit;
2316}
2317
2318#######################################################################
2319sub init_db {
2320    my $dbname   = $_[0];
2321    my $filename = "$NIKTOCONFIG{PLUGINDIR}/" . $dbname;
2322    my (@dbarray, @headers);
2323    my $hashref = {};
2324
2325    # Check that the database exists
2326    unless (open(IN, "<$filename")) {
2327        nprint("+ ERROR: Unable to open database file $dbname: $!.");
2328        return $dbarray;
2329    }
2330
2331    # Now read the header values
2332    while (<IN>) {
2333        chomp;
2334        s/\#.*$//;
2335        if ($_ eq "") { next }
2336        unless (@headers) {
2337            @headers = parse_csv($_);
2338        }
2339        else {
2340
2341            # contents; so split them up and apply to hash
2342            my @contents = parse_csv($_);
2343            my $hashref  = {};
2344            for (my $i = 0 ; $i <= $#contents ; $i++) {
2345                $hashref->{ $headers[$i] } = $contents[$i];
2346            }
2347            push(@dbarray, $hashref);
2348        }
2349    }
2350    return \@dbarray;
2351}
2352
2353#######################################################################
2354sub add_vulnerability {
2355    my ($mark, $message, $nikto_id, $osvdb, $method, $uri) = @_;
2356    $uri    = "/"   unless (defined $uri);
2357    $method = "GET" unless (defined $method);
2358    $osvdb  = "0"   unless (defined $osvdb);
2359
2360    my $result = "";
2361    if (defined $_[7]) {
2362        $result = $_[7]->{'whisker'}->{'data'};
2363    }
2364    my $outmessage = $message;
2365    my $resulthash = {};
2366
2367    unless ($osvdb eq "0") {
2368        $outmessage = "OSVDB-$osvdb: $message";
2369    }
2370    nprint("+ $outmessage");
2371    %$resulthash = (mark     => $mark,
2372                    message  => $message,
2373                    nikto_id => $nikto_id,
2374                    osvdb    => $osvdb,
2375                    method   => $method,
2376                    uri      => $uri,
2377                    result   => $result,
2378                    );
2379    $mark->{total_vulns}++;
2380    push(@RESULTS, $resulthash);
2381
2382    # Now report it
2383    report_item($mark, $resulthash);
2384}
2385
2386###############################################################################
2387sub list_plugins {
2388
2389    # Just do a load_plugins, then loop through the array and print out name,
2390    # description and copyright
2391
2392    load_plugins();
2393
2394    foreach my $plugin (@PLUGINS) {
2395        nprint("Plugin: $plugin->{'name'}");
2396        push(@all_names, $plugin->{'name'});
2397        nprint(" $plugin->{'full_name'} - $plugin->{'description'}");
2398        nprint(" Written by $plugin->{'author'}, Copyright (C) $plugin->{'copyright'}");
2399        if (defined $plugin->{'options'}) {
2400            nprint(" Options:");
2401            while (my ($option, $description) = each(%{ $plugin->{'options'} })) {
2402                nprint("  $option: $description");
2403            }
2404        }
2405        nprint("\n");
2406    }
2407
2408    # Plugin macros
2409    nprint("Defined plugin macros:");
2410
2411    foreach my $macro (keys %NIKTOCONFIG) {
2412        if ($macro =~ /^@@/) {
2413            nprint(" $macro = \"" . $NIKTOCONFIG{$macro} . "\"");
2414            if ($NIKTOCONFIG{$macro} =~ /@@/) {
2415                nprint("  (expanded) = \"" . expand_pluginlist($NIKTOCONFIG{$macro}, 0) . "\"");
2416            }
2417        }
2418    }
2419
2420    exit(0);
2421}
2422
2423###############################################################################
2424# This is overly complicated and jumps a lot between scalars and arrays. The REs are
2425# probably dodgy, but it works! W00!
2426sub expand_pluginlist {
2427    my ($pluginlist, $parent) = @_;
2428
2429    my @macros;
2430    foreach my $config (keys %NIKTOCONFIG) {
2431        if ($config =~ /^@@/) {
2432            push(@macros, $config);
2433        }
2434    }
2435
2436    # Now loop through each member of the list and expand it
2437    my $count       = 0;
2438    my $npluginlist = $pluginlist;
2439    do {
2440        $count++;
2441        my @raw = split(/;/, $npluginlist);
2442
2443        # cooked contains the processed list
2444        my @cooked;
2445        foreach my $entry (@raw) {
2446
2447            # Is it +; if so remap to @@DEFAULT
2448            if ($entry eq "+") {
2449                $entry = '@@DEFAULT';
2450            }
2451
2452            # result contains the processed entry
2453            my $result = $original = $entry;
2454
2455            # Is it a macro
2456            if ($entry =~ /^-?@@/) {
2457
2458                # break up into components
2459                $prefix = ($entry =~ /^-/) ? "-" : "";
2460                $name = $suffix = $entry;
2461                $name   =~ s/(^-?)(@@[[:alpha:]]+)(\(?.*\)?$)/$2/;
2462                $suffix =~ s/(.*)(\(.*\))/$2/;
2463                if ($suffix eq $entry) {
2464                    $suffix = "";
2465                }
2466                foreach my $macro (@macros) {
2467                    if ($entry =~ /-?$macro/) {
2468
2469                        # It's a macro, so replace the contents with the macro
2470                        # Add prefix and suffix to each member of the macro
2471                        my @temp;
2472                        foreach my $child (split(/;/, $NIKTOCONFIG{$macro})) {
2473                            push(@temp, "$prefix$child$suffix");
2474                        }
2475                        $result = join(';', @temp);
2476
2477                        # stop an infinite loop
2478                        last;
2479                    }
2480                }
2481            }
2482            if ($result =~ /^-?@@/ && $result eq $original) {
2483
2484                # macro not found or is itself - ignore
2485                $result = "";
2486            }
2487            if ($count > 100) {
2488
2489                # check for recurstion
2490                nprint("ERROR: Recursion found whilst expanding macros");
2491                $result = "";
2492                last;
2493            }
2494            push(@cooked, $result);
2495        }
2496        $npluginlist = join(';', @cooked);
2497    } while ($npluginlist =~ /@@/ && $count <= 100);
2498
2499    #use re 'debug';
2500    # Now we've expanded out macros, deal with duplicates and -
2501    my @raw = split(/;/, $npluginlist);
2502
2503    # hash so we don't have to mess with duplicates
2504    my %cooked;
2505    foreach my $plugin (@raw) {
2506
2507        # break out components
2508        my $minus;
2509        my $name = my $suffix = $plugin;
2510        $minus = (substr($plugin, 0, 1) eq '-');
2511        $name   =~ s/(^-?)([^\(]+)(\(?.*\)?$)/$2/;
2512        $suffix =~ s/(.*)(\(.*\))/$2/;
2513        if ($suffix eq $plugin) {
2514            $suffix = "";
2515        }
2516
2517        #nprint("P:$plugin M:$minus N:$name S:$suffix");
2518        if ($minus) {
2519
2520            # it's a minus - remove any previous entry
2521            if (exists $cooked{$name}) {
2522                delete $cooked{$name};
2523            }
2524        }
2525        else {
2526
2527            # else add it with the parameters as the value of the hash
2528            $cooked{$name} = $suffix;
2529        }
2530    }
2531
2532    # Now rejoin into one happy whole
2533    my $output;
2534    foreach my $plugin (keys %cooked) {
2535        $output .= "$plugin" . $cooked{$plugin} . ";";
2536    }
2537
2538    # remove the last ;
2539    $output =~ s/;$//g;
2540
2541    return $output;
2542}
2543#######################################################################
2544sub nikto_core { return; }    # trap for this plugin being called to run. lame.
2545#######################################################################
2546
25471;
Note: See TracBrowser for help on using the repository browser.