source: trunk/plugins/nikto_core.plugin @ 505

Revision 505, 90.1 KB checked in by deity, 3 years ago (diff)

Fix for broken -id parameter and clean up of unused %REALMS hash

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