source: trunk/plugins/nikto_core.plugin @ 621

Revision 621, 96.5 KB checked in by sullo, 2 years ago (diff)

Fix nmap file identification, match /ssl/ as well as /http/ for web server ports.

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