Don't log password to syslog
[webmin.git] / miniserv.pl
1 #!/usr/local/bin/perl
2 # A very simple perl web server used by Webmin
3
4 # Require basic libraries
5 package miniserv;
6 use Socket;
7 use POSIX;
8 use Time::Local;
9
10 @itoa64 = split(//, "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
11
12 # Find and read config file
13 if (@ARGV != 1) {
14         die "Usage: miniserv.pl <config file>";
15         }
16 if ($ARGV[0] =~ /^([a-z]:)?\//i) {
17         $config_file = $ARGV[0];
18         }
19 else {
20         chop($pwd = `pwd`);
21         $config_file = "$pwd/$ARGV[0]";
22         }
23 %config = &read_config_file($config_file);
24
25 # Check is SSL is enabled and available
26 if ($config{'ssl'}) {
27         eval "use Net::SSLeay";
28         if (!$@) {
29                 $use_ssl = 1;
30                 # These functions only exist for SSLeay 1.0
31                 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
32                 eval "Net::SSLeay::load_error_strings()";
33                 if ($config{'no_ssl2'}) {
34                         eval "Net::SSLeay::CTX_set_options($ctx,&Net::SSLeay::OP_NO_SSLv2)";
35                         }
36                 if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
37                     defined(&Net::SSLeay::CTX_load_verify_locations) &&
38                     defined(&Net::SSLeay::CTX_set_verify)) {
39                         $client_certs = 1;
40                         }
41                 }
42         }
43
44 # Check if the syslog module is available to log hacking attempts
45 if ($config{'syslog'} && !$config{'inetd'}) {
46         eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
47         if (!$@) {
48                 $use_syslog = 1;
49                 }
50         }
51
52 # check if the TCP-wrappers module is available
53 if ($config{'libwrap'}) {
54         eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
55         if (!$@) {
56                 $use_libwrap = 1;
57                 }
58         }
59
60 # Check if the MD5 perl module is available
61 eval "use MD5";
62 if (!$@) {
63         $use_md5 = "MD5";
64         }
65 else {
66         eval "use Digest::MD5";
67         if (!$@) {
68                 $use_md5 = "Digest::MD5";
69                 }
70         }
71
72 # Get miniserv's perl path and location
73 $miniserv_path = $0;
74 open(SOURCE, $miniserv_path);
75 <SOURCE> =~ /^#!(\S+)/;
76 $perl_path = $1;
77 close(SOURCE);
78 if (!-x $perl_path) {
79         $perl_path = $^X;
80         }
81 if (-l $perl_path) {
82         $linked_perl_path = readlink($perl_path);
83         }
84 @miniserv_argv = @ARGV;
85
86 # Check vital config options
87 &update_vital_config();
88
89 $sidname = $config{'sidname'};
90 die "Session authentication cannot be used in inetd mode"
91         if ($config{'inetd'} && $config{'session'});
92
93 # check if the PAM module is available to authenticate
94 if (!$config{'no_pam'}) {
95         eval "use Authen::PAM;";
96         if (!$@) {
97                 # check if the PAM authentication can be used by opening a
98                 # PAM handle
99                 local $pamh;
100                 if (ref($pamh = new Authen::PAM($config{'pam'}, "root",
101                                                   \&pam_conv_func))) {
102                         # Now test a login to see if /etc/pam.d/XXX is set
103                         # up properly.
104                         $pam_conv_func_called = 0;
105                         $pam_username = "test";
106                         $pam_password = "test";
107                         $pamh->pam_authenticate();
108                         if ($pam_conv_func_called) {
109                                 $pam_msg = "PAM authentication enabled";
110                                 $use_pam = 1;
111                                 }
112                         else {
113                                 $pam_msg = "PAM test failed - maybe /etc/pam.d/$config{'pam'} does not exist";
114                                 }
115                         }
116                 else {
117                         $pam_msg = "PAM initialization of Authen::PAM failed";
118                         }
119                 }
120         else {
121                 $pam_msg = "Perl module Authen::PAM needed for PAM is not installed : $@";
122                 }
123         }
124 if ($config{'pam_only'} && !$use_pam) {
125         $pam_msg2 = "PAM use is mandatory, but could not be enabled!";
126         }
127 elsif ($pam_msg && !$use_pam) {
128         $pam_msg2 = "Continuing without the Authen::PAM perl module";
129         }
130
131 # Check if the User::Utmp perl module is installed
132 if ($config{'utmp'}) {
133         eval "use User::Utmp;";
134         if (!$@) {
135                 $write_utmp = 1;
136                 $utmp_msg = "UTMP logging enabled";
137                 }
138         else {
139                 $utmp_msg = "Perl module User::Utmp needed for Utmp logging is not installed : $@";
140                 }
141         }
142
143 # See if the crypt function fails
144 eval "crypt('foo', 'xx')";
145 if ($@) {
146         eval "use Crypt::UnixCrypt";
147         if (!$@) {
148                 $use_perl_crypt = 1;
149                 $crypt_msg = "Using Crypt::UnixCrypt for password encryption\n";
150                 }
151         else {
152                 $crypt_msg = "crypt() function un-implemented, and Crypt::UnixCrypt not installed - password authentication will probably fail\n";
153                 }
154         }
155
156 # Check if /dev/urandom really generates random IDs, by calling it twice
157 local $rand1 = &generate_random_id("foo", 1);
158 local $rand2 = &generate_random_id("foo", 2);
159 local $rand_msg;
160 if ($rand1 eq $rand2) {
161         $bad_urandom = 1;
162         $rand_msg = "Random number generator file /dev/urandom is not reliable";
163         }
164
165 # Check if we can call sudo
166 if ($config{'sudo'} && &has_command("sudo")) {
167         eval "use IO::Pty";
168         if (!$@) {
169                 $use_sudo = 1;
170                 }
171         else {
172                 $sudo_msg = "Perl module IO::Pty needed for calling sudo is not installed : $@";
173                 }
174         }
175
176 # init days and months for http_date
177 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
178 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
179            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
180
181 # Change dir to the server root
182 @roots = ( $config{'root'} );
183 for($i=0; defined($config{"extraroot_$i"}); $i++) {
184         push(@roots, $config{"extraroot_$i"});
185         }
186 chdir($roots[0]);
187 eval { $user_homedir = (getpwuid($<))[7]; };
188 if ($@) {
189         # getpwuid doesn't work on windows
190         $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
191         $on_windows = 1;
192         }
193
194 # Read users file
195 &read_users_file();
196
197 # Setup SSL if possible and if requested
198 if (!-r $config{'keyfile'} ||
199     $config{'certfile'} && !-r $config{'certfile'}) {
200         # Key file doesn't exist!
201         $use_ssl = 0;
202         }
203 @ipkeys = &get_ipkeys(\%config);
204 if ($use_ssl) {
205         if ($config{'ssl_version'}) {
206                 # Force an SSL version
207                 $Net::SSLeay::version = $config{'ssl_version'};
208                 $Net::SSLeay::ssl_version = $config{'ssl_version'};
209                 }
210         $client_certs = 0 if (!-r $config{'ca'} || !%certs);
211         $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
212                                                  $config{'certfile'});
213         foreach $ipkey (@ipkeys) {
214                 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'});
215                 foreach $ip (@{$ipkey->{'ips'}}) {
216                         $ssl_contexts{$ip} = $ctx;
217                         }
218                 }
219         }
220
221 # Setup syslog support if possible and if requested
222 if ($use_syslog) {
223         open(ERRDUP, ">&STDERR");
224         open(STDERR, ">/dev/null");
225         $log_socket = $config{"logsock"} || "unix";
226         eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
227         if ($@) {
228                 $use_syslog = 0;
229                 }
230         else {
231                 local $msg = ucfirst($config{'pam'})." starting";
232                 eval { syslog("info", "%s", $msg); };
233                 if ($@) {
234                         eval {
235                                 setlogsock("inet");
236                                 syslog("info", "%s", $msg);
237                                 };
238                         if ($@) {
239                                 # All attempts to use syslog have failed..
240                                 $use_syslog = 0;
241                                 }
242                         }
243                 }
244         open(STDERR, ">&ERRDUP");
245         close(ERRDUP);
246         }
247
248 # Read MIME types file and add extra types
249 &read_mime_types();
250
251 # get the time zone
252 if ($config{'log'}) {
253         local(@gmt, @lct, $days, $hours, $mins);
254         @gmt = gmtime(time());
255         @lct = localtime(time());
256         $days = $lct[3] - $gmt[3];
257         $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
258                  $lct[2] - $gmt[2];
259         $mins = $hours * 60 + $lct[1] - $gmt[1];
260         $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
261         $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
262         }
263
264 # Build various maps from the config files
265 &build_config_mappings();
266
267 # start up external authentication program, if needed
268 if ($config{'extauth'}) {
269         socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
270         if (!($extauth = fork())) {
271                 close(EXTAUTH);
272                 close(STDIN);
273                 close(STDOUT);
274                 open(STDIN, "<&EXTAUTH2");
275                 open(STDOUT, ">&EXTAUTH2");
276                 exec($config{'extauth'}) or die "exec failed : $!\n";
277                 }
278         close(EXTAUTH2);
279         local $os = select(EXTAUTH);
280         $| = 1; select($os);
281         }
282
283 # Pre-load any libraries
284 foreach $pl (split(/\s+/, $config{'preload'})) {
285         ($pkg, $lib) = split(/=/, $pl);
286         $pkg =~ s/[^A-Za-z0-9]/_/g;
287         eval "package $pkg; do '$config{'root'}/$lib'";
288         if ($@) {
289                 print STDERR "Failed to pre-load $lib in $pkg : $@\n";
290                 }
291         else {
292                 print STDERR "Pre-loaded $lib in $pkg\n";
293                 }
294         }
295 foreach $pl (split(/\s+/, $config{'premodules'})) {
296         if ($pl =~ /\//) {
297                 ($dir, $mod) = split(/\//, $pl);
298                 }
299         else {
300                 ($dir, $mod) = (undef, $pl);
301                 }
302         push(@INC, "$config{'root'}/$dir");
303         eval "package $mod; use $mod ()";
304         if ($@) {
305                 print STDERR "Failed to pre-load $mod : $@\n";
306                 }
307         else {
308                 print STDERR "Pre-loaded $mod\n";
309                 }
310         }
311
312 # Open debug log if set
313 if ($config{'debuglog'}) {
314         open(DEBUG, ">>$config{'debuglog'}");
315         chmod(0700, $config{'debuglog'});
316         select(DEBUG); $| = 1; select(STDOUT);
317         print DEBUG "miniserv.pl starting ..\n";
318         }
319
320 # Write out (empty) blocked hosts file
321 &write_blocked_file();
322
323 # Re-direct STDERR to a log file
324 if ($config{'errorlog'} ne '-') {
325         open(STDERR, ">>$config{'errorlog'}") || die "failed to open $config{'errorlog'} : $!";
326         if ($config{'logperms'}) {
327                 chmod(oct($config{'logperms'}), $config{'errorlog'});
328                 }
329         }
330 select(STDERR); $| = 1; select(STDOUT);
331
332 if ($config{'inetd'}) {
333         # We are being run from inetd - go direct to handling the request
334         $SIG{'HUP'} = 'IGNORE';
335         $SIG{'TERM'} = 'DEFAULT';
336         $SIG{'PIPE'} = 'DEFAULT';
337         open(SOCK, "+>&STDIN");
338
339         # Check if it is time for the logfile to be cleared
340         if ($config{'logclear'}) {
341                 local $write_logtime = 0;
342                 local @st = stat("$config{'logfile'}.time");
343                 if (@st) {
344                         if ($st[9]+$config{'logtime'}*60*60 < time()){
345                                 # need to clear log
346                                 $write_logtime = 1;
347                                 unlink($config{'logfile'});
348                                 }
349                         }
350                 else { $write_logtime = 1; }
351                 if ($write_logtime) {
352                         open(LOGTIME, ">$config{'logfile'}.time");
353                         print LOGTIME time(),"\n";
354                         close(LOGTIME);
355                         }
356                 }
357
358         # Initialize SSL for this connection
359         if ($use_ssl) {
360                 $ssl_con = &ssl_connection_for_ip(SOCK);
361                 $ssl_con || exit;
362                 }
363
364         # Work out the hostname for this web server
365         $host = &get_socket_name(SOCK);
366         $host || exit;
367         $port = $config{'port'};
368         $acptaddr = getpeername(SOCK);
369         $acptaddr || exit;
370
371         print DEBUG "main: Starting handle_request loop pid=$$\n";
372         while(&handle_request($acptaddr, getsockname(SOCK))) { }
373         print DEBUG "main: Done handle_request loop pid=$$\n";
374         close(SOCK);
375         exit;
376         }
377
378 # Build list of sockets to listen on
379 if ($config{"bind"} && $config{"bind"} ne "*") {
380         push(@sockets, [ inet_aton($config{'bind'}), $config{'port'} ]);
381         }
382 else {
383         push(@sockets, [ INADDR_ANY, $config{'port'} ]);
384         }
385 foreach $s (split(/\s+/, $config{'sockets'})) {
386         if ($s =~ /^(\d+)$/) {
387                 # Just listen on another port on the main IP
388                 push(@sockets, [ $sockets[0]->[0], $s ]);
389                 }
390         elsif ($s =~ /^(\S+):(\d+)$/) {
391                 # Listen on a specific port and IP
392                 push(@sockets, [ $1 eq "*" ? INADDR_ANY : inet_aton($1), $2 ]);
393                 }
394         elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
395                 # Listen on the main port on another IP
396                 push(@sockets, [ inet_aton($1), $sockets[0]->[1] ]);
397                 }
398         }
399
400 # Open all the sockets
401 $proto = getprotobyname('tcp');
402 @sockerrs = ( );
403 $tried_inaddr_any = 0;
404 for($i=0; $i<@sockets; $i++) {
405         $fh = "MAIN$i";
406         socket($fh, PF_INET, SOCK_STREAM, $proto) ||
407                 die "Failed to open socket : $!";
408         setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
409         for($j=0; $j<5; $j++) {
410                 last if (bind($fh, pack_sockaddr_in($sockets[$i]->[1],
411                                                     $sockets[$i]->[0])));
412                 sleep(1);
413                 }
414         if ($j == 5) {
415                 # All attempts failed .. give up
416                 if ($sockets[$i]->[0] eq INADDR_ANY) {
417                         push(@sockerrs, "Failed to bind to port $sockets[$i]->[1] : $!");
418                         $tried_inaddr_any = 1;
419                         }
420                 else {
421                         $ip = inet_ntoa($sockets[$i]->[0]);
422                         push(@sockerrs, "Failed to bind to IP $ip port $sockets[$i]->[1] : $!");
423                         }
424                 }
425         else {
426                 listen($fh, SOMAXCONN);
427                 push(@socketfhs, $fh);
428                 }
429         }
430 foreach $se (@sockerrs) {
431         print STDERR $se,"\n";
432         }
433
434 # If all binds failed, try binding to any address
435 if (!@socketfhs && !$tried_inaddr_any) {
436         print STDERR "Falling back to listening on any address\n";
437         $fh = "MAIN";
438         socket($fh, PF_INET, SOCK_STREAM, $proto) ||
439                 die "Failed to open socket : $!";
440         setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
441         bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY)) ||
442                 die "Failed to bind to port $sockets[0]->[1] : $!";
443         listen($fh, SOMAXCONN);
444         push(@socketfhs, $fh);
445         }
446 elsif (!@socketfhs && $tried_inaddr_any) {
447         die "Could not listen on any ports";
448         }
449
450 if ($config{'listen'}) {
451         # Open the socket that allows other webmin servers to find this one
452         $proto = getprotobyname('udp');
453         if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
454                 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
455                 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
456                 listen(LISTEN, SOMAXCONN);
457                 }
458         else {
459                 $config{'listen'} = 0;
460                 }
461         }
462
463 # Split from the controlling terminal, unless configured not to
464 if (!$config{'nofork'}) {
465         if (fork()) { exit; }
466         }
467 eval { setsid(); };     # may not work on Windows
468
469 # Close standard file handles
470 open(STDIN, "</dev/null");
471 open(STDOUT, ">/dev/null");
472 &log_error("miniserv.pl started");
473 &log_error($pam_msg) if ($pam_msg);
474 &log_error($pam_msg2) if ($pam_msg2);
475 &log_error($utmp_msg) if ($utmp_msg);
476 &log_error($crypt_msg) if ($crypt_msg);
477 &log_error($sudo_msg) if ($sudo_msg);
478 &log_error($rand_msg) if ($rand_msg);
479
480 # write out the PID file
481 &write_pid_file();
482
483 # Start the log-clearing process, if needed. This checks every minute
484 # to see if the log has passed its reset time, and if so clears it
485 if ($config{'logclear'}) {
486         if (!($logclearer = fork())) {
487                 &close_all_sockets();
488                 close(LISTEN);
489                 while(1) {
490                         local $write_logtime = 0;
491                         local @st = stat("$config{'logfile'}.time");
492                         if (@st) {
493                                 if ($st[9]+$config{'logtime'}*60*60 < time()){
494                                         # need to clear log
495                                         $write_logtime = 1;
496                                         unlink($config{'logfile'});
497                                         }
498                                 }
499                         else { $write_logtime = 1; }
500                         if ($write_logtime) {
501                                 open(LOGTIME, ">$config{'logfile'}.time");
502                                 print LOGTIME time(),"\n";
503                                 close(LOGTIME);
504                                 }
505                         sleep(5*60);
506                         }
507                 exit;
508                 }
509         push(@childpids, $logclearer);
510         }
511
512 # Setup the logout time dbm if needed
513 if ($config{'session'}) {
514         eval "use SDBM_File";
515         dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
516         eval "\$sessiondb{'1111111111'} = 'foo bar';";
517         if ($@) {
518                 dbmclose(%sessiondb);
519                 eval "use NDBM_File";
520                 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
521                 }
522         else {
523                 delete($sessiondb{'1111111111'});
524                 }
525         }
526
527 # Run the main loop
528 $SIG{'HUP'} = 'miniserv::trigger_restart';
529 $SIG{'TERM'} = 'miniserv::term_handler';
530 $SIG{'USR1'} = 'miniserv::trigger_reload';
531 $SIG{'PIPE'} = 'IGNORE';
532 local $remove_session_count = 0;
533 $need_pipes = $config{'passdelay'} || $config{'session'};
534 $last_pid_time = time();
535 while(1) {
536         # wait for a new connection, or a message from a child process
537         local ($i, $rmask);
538         if (@childpids <= $config{'maxconns'}) {
539                 # Only accept new main socket connects when ready
540                 local $s;
541                 foreach $s (@socketfhs) {
542                         vec($rmask, fileno($s), 1) = 1;
543                         }
544                 }
545         else {
546                 printf STDERR "too many children (%d > %d)\n",
547                         scalar(@childpids), $config{'maxconns'};
548                 }
549         if ($need_pipes) {
550                 for($i=0; $i<@passin; $i++) {
551                         vec($rmask, fileno($passin[$i]), 1) = 1;
552                         }
553                 }
554         vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
555
556         # Wait for a connection
557         local $sel = select($rmask, undef, undef, 10);
558
559         # Check the flag files
560         if ($config{'restartflag'} && -r $config{'restartflag'}) {
561                 print STDERR "restart flag file detected\n";
562                 unlink($config{'restartflag'});
563                 $need_restart = 1;
564                 }
565         if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
566                 unlink($config{'reloadflag'});
567                 $need_reload = 1;
568                 }
569
570         if ($need_restart) {
571                 # Got a HUP signal while in select() .. restart now
572                 &restart_miniserv();
573                 }
574         if ($need_reload) {
575                 # Got a USR1 signal while in select() .. re-read config
576                 $need_reload = 0;
577                 &reload_config_file();
578                 }
579         local $time_now = time();
580
581         # Write the PID every 10 seconds
582         if ($time_now - $last_pid_time > 10) {
583                 &write_pid_file();
584                 $last_pid_time = $time_now;
585                 }
586
587         # Clean up finished processes
588         local $pid;
589         do {    $pid = waitpid(-1, WNOHANG);
590                 @childpids = grep { $_ != $pid } @childpids;
591                 } while($pid != 0 && $pid != -1);
592
593         # run the unblocking procedure to check if enough time has passed to
594         # unblock hosts that heve been blocked because of password failures
595         $unblocked = 0;
596         if ($config{'blockhost_failures'}) {
597                 $i = 0;
598                 while ($i <= $#deny) {
599                         if ($blockhosttime{$deny[$i]} &&
600                             $config{'blockhost_time'} != 0 &&
601                             ($time_now - $blockhosttime{$deny[$i]}) >=
602                              $config{'blockhost_time'}) {
603                                 # the host can be unblocked now
604                                 $hostfail{$deny[$i]} = 0;
605                                 splice(@deny, $i, 1);
606                                 $unblocked = 1;
607                                 }
608                         $i++;
609                         }
610                 }
611
612         # Do the same for blocked users
613         if ($config{'blockuser_failures'}) {
614                 $i = 0;
615                 while ($i <= $#deny) {
616                         if ($blockusertime{$deny[$i]} &&
617                             $config{'blockuser_time'} != 0 &&
618                             ($time_now - $blockusertime{$deny[$i]}) >=
619                              $config{'blockuser_time'}) {
620                                 # the user can be unblocked now
621                                 $userfail{$deny[$i]} = 0;
622                                 splice(@denyusers, $i, 1);
623                                 $unblocked = 1;
624                                 }
625                         $i++;
626                         }
627                 }
628         if ($unblocked) {
629                 &write_blocked_file();
630                 }
631
632         if ($config{'session'} && (++$remove_session_count%50) == 0) {
633                 # Remove sessions with more than 7 days of inactivity,
634                 local $s;
635                 foreach $s (keys %sessiondb) {
636                         local ($user, $ltime, $lip) =
637                                 split(/\s+/, $sessiondb{$s});
638                         if ($time_now - $ltime > 7*24*60*60) {
639                                 &run_logout_script($s, $user);
640                                 &write_logout_utmp($user, $lip);
641                                 delete($sessiondb{$s});
642                                 if ($use_syslog) {
643                                         syslog("info", "%s",
644                                               "Timeout of session for $user");
645                                         }
646                                 }
647                         }
648                 }
649
650         if ($use_pam && $config{'pam_conv'}) {
651                 # Remove PAM sessions with more than 5 minutes of inactivity
652                 local $c;
653                 foreach $c (values %conversations) {
654                         if ($time_now - $c->{'time'} > 5*60) {
655                                 &end_pam_conversation($c);
656                                 if ($use_syslog) {
657                                         syslog("info", "%s", "Timeout of PAM ".
658                                                 "session for $c->{'user'}");
659                                         }
660                                 }
661                         }
662                 }
663
664         # Don't check any sockets if there is no activity
665         next if ($sel <= 0);
666
667         # Check if any of the main sockets have received a new connection
668         local $sn = 0;
669         foreach $s (@socketfhs) {
670                 if (vec($rmask, fileno($s), 1)) {
671                         # got new connection
672                         $acptaddr = accept(SOCK, $s);
673                         if (!$acptaddr) { next; }
674                         binmode(SOCK);  # turn off any Perl IO stuff
675
676                         # create pipes
677                         local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
678                         if ($need_pipes) {
679                                 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
680                                         &allocate_pipes();
681                                 }
682
683                         # Check username of connecting user
684                         local ($peerp, $peera) = unpack_sockaddr_in($acptaddr);
685                         $localauth_user = undef;
686                         if ($config{'localauth'} && inet_ntoa($peera) eq "127.0.0.1") {
687                                 if (open(TCP, "/proc/net/tcp")) {
688                                         # Get the info direct from the kernel
689                                         while(<TCP>) {
690                                                 s/^\s+//;
691                                                 local @t = split(/[\s:]+/, $_);
692                                                 if ($t[1] eq '0100007F' &&
693                                                     $t[2] eq sprintf("%4.4X", $peerp)) {
694                                                         $localauth_user = getpwuid($t[11]);
695                                                         last;
696                                                         }
697                                                 }
698                                         close(TCP);
699                                         }
700                                 if (!$localauth_user) {
701                                         # Call lsof for the info
702                                         local $lsofpid = open(LSOF,
703                                                 "$config{'localauth'} -i TCP\@127.0.0.1:$peerp |");
704                                         while(<LSOF>) {
705                                                 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
706                                                     $2 != $$ && $2 != $lsofpid) {
707                                                         $localauth_user = $3;
708                                                         }
709                                                 }
710                                         close(LSOF);
711                                         }
712                                 }
713
714                         # Work out the hostname for this web server
715                         $host = &get_socket_name(SOCK);
716                         if (!$host) {
717                                 print STDERR "Failed to get local socket name : $!\n";
718                                 close(SOCK);
719                                 next;
720                                 }
721                         $port = $sockets[$sn]->[1];
722
723                         # fork the subprocess
724                         local $handpid;
725                         if (!($handpid = fork())) {
726                                 # setup signal handlers
727                                 $SIG{'TERM'} = 'DEFAULT';
728                                 $SIG{'PIPE'} = 'DEFAULT';
729                                 #$SIG{'CHLD'} = 'IGNORE';
730                                 $SIG{'HUP'} = 'IGNORE';
731                                 $SIG{'USR1'} = 'IGNORE';
732
733                                 # Initialize SSL for this connection
734                                 if ($use_ssl) {
735                                         $ssl_con = &ssl_connection_for_ip(SOCK);
736                                         $ssl_con || exit;
737                                         }
738
739                                 # Close the file handle for the session DBM
740                                 dbmclose(%sessiondb);
741
742                                 # close useless pipes
743                                 if ($need_pipes) {
744                                         &close_all_pipes();
745                                         close($PASSINr); close($PASSOUTw);
746                                         }
747                                 &close_all_sockets();
748                                 close(LISTEN);
749
750                                 print DEBUG
751                                   "main: Starting handle_request loop pid=$$\n";
752                                 while(&handle_request($acptaddr,
753                                                       getsockname(SOCK))) { }
754                                 print DEBUG
755                                   "main: Done handle_request loop pid=$$\n";
756                                 shutdown(SOCK, 1);
757                                 close(SOCK);
758                                 close($PASSINw); close($PASSOUTw);
759                                 exit;
760                                 }
761                         push(@childpids, $handpid);
762                         if ($need_pipes) {
763                                 close($PASSINw); close($PASSOUTr);
764                                 push(@passin, $PASSINr);
765                                 push(@passout, $PASSOUTw);
766                                 }
767                         close(SOCK);
768                         }
769                 $sn++;
770                 }
771
772         if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
773                 # Got UDP packet from another webmin server
774                 local $rcvbuf;
775                 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
776                 next if (!$from);
777                 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
778                 local $toip = inet_ntoa((unpack_sockaddr_in(
779                                          getsockname(LISTEN)))[1]);
780                 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
781                     (!@allow || &ip_match($fromip, $toip, @allow))) {
782                         local $listenhost = &get_socket_name(LISTEN);
783                         send(LISTEN, "$listenhost:$config{'port'}:".
784                                   ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
785                                   ($config{'listenhost'} ?
786                                         &get_system_hostname() : ""),
787                                   0, $from)
788                                 if ($listenhost);
789                         }
790                 }
791
792         # check for session, password-timeout and PAM messages from subprocesses
793         for($i=0; $i<@passin; $i++) {
794                 if (vec($rmask, fileno($passin[$i]), 1)) {
795                         # this sub-process is asking about a password
796                         local $infd = $passin[$i];
797                         local $outfd = $passout[$i];
798                         #local $inline = <$infd>;
799                         local $inline = &sysread_line($infd);
800                         if ($inline) {
801                                 print DEBUG "main: inline $inline";
802                                 }
803                         else {
804                                 print DEBUG "main: inline EOF\n";
805                                 }
806                         if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
807                                 # Got a delay request from a subprocess.. for
808                                 # valid logins, there is no delay (to prevent
809                                 # denial of service attacks), but for invalid
810                                 # logins the delay increases with each failed
811                                 # attempt.
812                                 if ($3) {
813                                         # login OK.. no delay
814                                         print $outfd "0 0\n";
815                                         $wasblocked = $hostfail{$2} ||
816                                                       $userfail{$1};
817                                         $hostfail{$2} = 0;
818                                         $userfail{$1} = 0;
819                                         if ($wasblocked) {
820                                                 &write_blocked_file();
821                                                 }
822                                         }
823                                 else {
824                                         # login failed..
825                                         $hostfail{$2}++;
826                                         $userfail{$1}++;
827                                         $blocked = 0;
828
829                                         # add the host to the block list,
830                                         # if configured
831                                         if ($config{'blockhost_failures'} &&
832                                             $hostfail{$2} >=
833                                               $config{'blockhost_failures'}) {
834                                                 push(@deny, $2);
835                                                 $blockhosttime{$2} = $time_now;
836                                                 $blocked = 1;
837                                                 if ($use_syslog) {
838                                                         local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
839                                                         syslog("crit", "%s",
840                                                                 $logtext);
841                                                         }
842                                                 }
843
844                                         # add the user to the user block list,
845                                         # if configured
846                                         if ($config{'blockuser_failures'} &&
847                                             $userfail{$1} >=
848                                               $config{'blockuser_failures'}) {
849                                                 push(@denyusers, $1);
850                                                 $blockusertime{$1} = $time_now;
851                                                 $blocked = 2;
852                                                 if ($use_syslog) {
853                                                         local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
854                                                         syslog("crit", "%s",
855                                                                 $logtext);
856                                                         }
857                                                 }
858
859                                         # Lock out the user's password, if enabled
860                                         if ($config{'blocklock'} &&
861                                             $userfail{$1} >=
862                                               $config{'blockuser_failures'}) {
863                                                 my $lk = &lock_user_password($1);
864                                                 $blocked = 2;
865                                                 if ($use_syslog) {
866                                                         local $logtext = $lk == 1 ? "Security alert: User $1 locked after $config{'blockuser_failures'} failed logins" : $lk < 0 ? "Security alert: User could not be locked" : "Security alert: User is already locked";
867                                                         syslog("crit", "%s",
868                                                                 $logtext);
869                                                         }
870                                                 }
871
872                                         # Send back a delay
873                                         $dl = $userdlay{$1} -
874                                            int(($time_now - $userlast{$1})/50);
875                                         $dl = $dl < 0 ? 0 : $dl+1;
876                                         print $outfd "$dl $blocked\n";
877                                         $userdlay{$1} = $dl;
878
879                                         # Write out blocked status file
880                                         if ($blocked) {
881                                                 &write_blocked_file();
882                                                 }
883                                         }
884                                 $userlast{$1} = $time_now;
885                                 }
886                         elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
887                                 # Verifying a session ID
888                                 local $session_id = $1;
889                                 local $notimeout = $2;
890                                 local $skey = $sessiondb{$session_id} ?
891                                                 $session_id : 
892                                                 &hash_session_id($session_id);
893                                 if (!defined($sessiondb{$skey})) {
894                                         # Session doesn't exist
895                                         print $outfd "0 0\n";
896                                         }
897                                 else {
898                                         local ($user, $ltime) =
899                                           split(/\s+/, $sessiondb{$skey});
900                                         local $lot = &get_logout_time($user, $session_id);
901                                         if ($lot &&
902                                             $time_now - $ltime > $lot*60 &&
903                                             !$notimeout) {
904                                                 # Session has timed out
905                                                 print $outfd "1 ",$time_now - $ltime,"\n";
906                                                 #delete($sessiondb{$skey});
907                                                 }
908                                         else {
909                                                 # Session is OK
910                                                 print $outfd "2 $user\n";
911                                                 if ($lot &&
912                                                     $time_now - $ltime >
913                                                     ($lot*60)/2) {
914                                                         $sessiondb{$skey} = "$user $time_now";
915                                                         }
916                                                 }
917                                         }
918                                 }
919                         elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
920                                 # Creating a new session
921                                 local $session_id = $1;
922                                 local $user = $2;
923                                 local $ip = $3;
924                                 $sessiondb{&hash_session_id($session_id)} =
925                                         "$user $time_now $ip";
926                                 }
927                         elsif ($inline =~ /^delete\s+(\S+)/) {
928                                 # Logging out a session
929                                 local $session_id = $1;
930                                 local $skey = $sessiondb{$session_id} ?
931                                                 $session_id : 
932                                                 &hash_session_id($session_id);
933                                 local @sdb = split(/\s+/, $sessiondb{$skey});
934                                 print $outfd $sdb[0],"\n";
935                                 delete($sessiondb{$skey});
936                                 }
937                         elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
938                                 # Starting a new PAM conversation
939                                 local ($cid, $host, $user) = ($1, $2, $3);
940
941                                 # Does this user even need PAM?
942                                 local ($realuser, $canlogin) =
943                                         &can_user_login($user, undef, $host);
944                                 local $conv;
945                                 if ($canlogin == 0) {
946                                         # Cannot even login!
947                                         print $outfd "0 Invalid username\n";
948                                         }
949                                 elsif ($canlogin != 2) {
950                                         # Not using PAM .. so just ask for
951                                         # the password.
952                                         $conv = { 'user' => $realuser,
953                                                   'host' => $host,
954                                                   'step' => 0,
955                                                   'cid' => $cid,
956                                                   'time' => time() };
957                                         print $outfd "3 Password\n";
958                                         }
959                                 else {
960                                         # Start the PAM conversation
961                                         # sub-process, and get a question
962                                         $conv = { 'user' => $realuser,
963                                                   'host' => $host,
964                                                   'cid' => $cid,
965                                                   'time' => time() };
966                                         local ($PAMINr, $PAMINw, $PAMOUTr,
967                                                 $PAMOUTw) = &allocate_pipes();
968                                         local $pampid = fork();
969                                         if (!$pampid) {
970                                                 close($PAMOUTr); close($PAMINw);
971                                                 &pam_conversation_process(
972                                                         $realuser,
973                                                         $PAMOUTw, $PAMINr);
974                                                 }
975                                         close($PAMOUTw); close($PAMINr);
976                                         $conv->{'pid'} = $pampid;
977                                         $conv->{'PAMOUTr'} = $PAMOUTr;
978                                         $conv->{'PAMINw'} = $PAMINw;
979                                         push(@childpids, $pampid);
980
981                                         # Get the first PAM question
982                                         local $pok = &recv_pam_question(
983                                                 $conv, $outfd);
984                                         if (!$pok) {
985                                                 &end_pam_conversation($conv);
986                                                 }
987                                         }
988
989                                 $conversations{$cid} = $conv if ($conv);
990                                 }
991                         elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
992                                 # A response to a PAM question
993                                 local ($cid, $answer) = ($1, $2);
994                                 local $conv = $conversations{$cid};
995                                 if (!$conv) {
996                                         # No such conversation?
997                                         print $outfd "0 Bad login session\n";
998                                         }
999                                 elsif ($conv->{'pid'}) {
1000                                         # Send the PAM response and get
1001                                         # the next question
1002                                         &send_pam_answer($conv, $answer);
1003                                         local $pok = &recv_pam_question($conv, $outfd);
1004                                         if (!$pok) {
1005                                                 &end_pam_conversation($conv);
1006                                                 }
1007                                         }
1008                                 else {
1009                                         # This must be the password .. try it
1010                                         # and send back the results
1011                                         local ($vu, $expired, $nonexist) =
1012                                                 &validate_user($conv->{'user'},
1013                                                                $answer,
1014                                                                $conf->{'host'});
1015                                         local $ok = $vu ? 1 : 0;
1016                                         print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1017                                         &end_pam_conversation($conv);
1018                                         }
1019                                 }
1020                         elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1021                                 # Store the fact that some user can sudo to root
1022                                 local ($user, $ok) = ($1, $2);
1023                                 $sudocache{$user} = $ok." ".time();
1024                                 }
1025                         elsif ($inline =~ /^readsudo\s+(\S+)/) {
1026                                 # Query the user sudo cache (valid for 1 minute)
1027                                 local $user = $1;
1028                                 local ($ok, $last) =
1029                                         split(/\s+/, $sudocache{$user});
1030                                 if ($last < time()-60) {
1031                                         # Cache too old
1032                                         print $outfd "2\n";
1033                                         }
1034                                 else {
1035                                         # Tell client OK or not
1036                                         print $outfd "$ok\n";
1037                                         }
1038                                 }
1039                         elsif ($inline =~ /\S/) {
1040                                 # Unknown line from pipe?
1041                                 print DEBUG "main: Unknown line from pipe $inline\n";
1042                                 print STDERR "Unknown line from pipe $inline\n";
1043                                 }
1044                         else {
1045                                 # close pipe
1046                                 close($infd); close($outfd);
1047                                 $passin[$i] = $passout[$i] = undef;
1048                                 }
1049                         }
1050                 }
1051         @passin = grep { defined($_) } @passin;
1052         @passout = grep { defined($_) } @passout;
1053         }
1054
1055 # handle_request(remoteaddress, localaddress)
1056 # Where the real work is done
1057 sub handle_request
1058 {
1059 $acptip = inet_ntoa((unpack_sockaddr_in($_[0]))[1]);
1060 $localip = $_[1] ? inet_ntoa((unpack_sockaddr_in($_[1]))[1]) : undef;
1061 print DEBUG "handle_request: from $acptip to $localip\n";
1062 if ($config{'loghost'}) {
1063         $acpthost = gethostbyaddr(inet_aton($acptip), AF_INET);
1064         $acpthost = $acptip if (!$acpthost);
1065         }
1066 else {
1067         $acpthost = $acptip;
1068         }
1069 $datestr = &http_date(time());
1070 $ok_code = 200;
1071 $ok_message = "Document follows";
1072 $logged_code = undef;
1073 $reqline = $request_uri = $page = undef;
1074 $authuser = undef;
1075 $validated = undef;
1076
1077 # check address against access list
1078 if (@deny && &ip_match($acptip, $localip, @deny) ||
1079     @allow && !&ip_match($acptip, $localip, @allow)) {
1080         &http_error(403, "Access denied for $acptip");
1081         return 0;
1082         }
1083
1084 if ($use_libwrap) {
1085         # Check address with TCP-wrappers
1086         if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1087                        $acptip, STRING_UNKNOWN)) {
1088                 &http_error(403, "Access denied for $acptip by TCP wrappers");
1089                 return 0;
1090                 }
1091         }
1092 print DEBUG "handle_request: passed IP checks\n";
1093
1094 # Compute a timeout for the start of headers, based on the number of
1095 # child processes. As this increases, we use a shorter timeout to avoid
1096 # an attacker overloading the system.
1097 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1098
1099 # Wait at most 60 secs for start of headers for initial requests, or
1100 # 10 minutes for kept-alive connections
1101 local $rmask;
1102 vec($rmask, fileno(SOCK), 1) = 1;
1103 local $to = $checked_timeout ? 10*60 : $header_timeout;
1104 local $sel = select($rmask, undef, undef, $to);
1105 if (!$sel) {
1106         if ($checked_timeout) {
1107                 print DEBUG "handle_request: exiting due to timeout of $to\n";
1108                 exit;
1109                 }
1110         else {
1111                 &http_error(400, "Timeout",
1112                             "Waited for that $to seconds for start of headers");
1113                 }
1114         }
1115 $checked_timeout++;
1116 print DEBUG "handle_request: passed timeout check\n";
1117
1118 # Read the HTTP request and headers
1119 local $origreqline = &read_line();
1120 ($reqline = $origreqline) =~ s/\r|\n//g;
1121 $method = $page = $request_uri = undef;
1122 print DEBUG "handle_request reqline=$reqline\n";
1123 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1124         # An empty request .. just close the connection
1125         print DEBUG "handle_request: rejecting empty request\n";
1126         return 0;
1127         }
1128 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1129         print DEBUG "handle_request: invalid reqline=$reqline\n";
1130         if ($use_ssl) {
1131                 # This could be an http request when it should be https
1132                 $use_ssl = 0;
1133                 local $url = $config{'musthost'} ?
1134                                 "https://$config{'musthost'}:$port/" :
1135                                 "https://$host:$port/";
1136                 if ($config{'ssl_redirect'}) {
1137                         # Just re-direct to the correct URL
1138                         sleep(1);       # Give browser a change to finish
1139                                         # sending its request
1140                         &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1141                         &write_data("Date: $datestr\r\n");
1142                         &write_data("Server: $config{'server'}\r\n");
1143                         &write_data("Location: $url\r\n");
1144                         &write_keep_alive(0);
1145                         &write_data("\r\n");
1146                         return 0;
1147                         }
1148                 else {
1149                         # Tell user the correct URL
1150                         &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1151                         }
1152                 }
1153         elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1154                 # This could be an https request when it should be http ..
1155                 # need to fake a HTTP response
1156                 eval <<'EOF';
1157                         use Net::SSLeay;
1158                         eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1159                         eval "Net::SSLeay::load_error_strings()";
1160                         $ssl_ctx = Net::SSLeay::CTX_new();
1161                         Net::SSLeay::CTX_use_RSAPrivateKey_file(
1162                                 $ssl_ctx, $config{'keyfile'},
1163                                 &Net::SSLeay::FILETYPE_PEM);
1164                         Net::SSLeay::CTX_use_certificate_file(
1165                                 $ssl_ctx,
1166                                 $config{'certfile'} || $config{'keyfile'},
1167                                 &Net::SSLeay::FILETYPE_PEM);
1168                         $ssl_con = Net::SSLeay::new($ssl_ctx);
1169                         pipe(SSLr, SSLw);
1170                         if (!fork()) {
1171                                 close(SSLr);
1172                                 select(SSLw); $| = 1; select(STDOUT);
1173                                 print SSLw $origreqline;
1174                                 local $buf;
1175                                 while(sysread(SOCK, $buf, 1) > 0) {
1176                                         print SSLw $buf;
1177                                         }
1178                                 close(SOCK);
1179                                 exit;
1180                                 }
1181                         close(SSLw);
1182                         Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1183                         Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1184                         Net::SSLeay::accept($ssl_con) || die "accept() failed";
1185                         $use_ssl = 1;
1186                         local $url = $config{'musthost'} ?
1187                                         "https://$config{'musthost'}:$port/" :
1188                                         "https://$host:$port/";
1189                         if ($config{'ssl_redirect'}) {
1190                                 # Just re-direct to the correct URL
1191                                 sleep(1);       # Give browser a change to
1192                                                 # finish sending its request
1193                                 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1194                                 &write_data("Date: $datestr\r\n");
1195                                 &write_data("Server: $config{'server'}\r\n");
1196                                 &write_data("Location: $url\r\n");
1197                                 &write_keep_alive(0);
1198                                 &write_data("\r\n");
1199                                 return 0;
1200                                 }
1201                         else {
1202                                 # Tell user the correct URL
1203                                 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1204                                 }
1205 EOF
1206                 if ($@) {
1207                         &http_error(400, "Bad Request");
1208                         }
1209                 }
1210         else {
1211                 &http_error(400, "Bad Request");
1212                 }
1213         }
1214 $method = $1;
1215 $request_uri = $page = $2;
1216 %header = ();
1217 local $lastheader;
1218 while(1) {
1219         ($headline = &read_line()) =~ s/\r|\n//g;
1220         last if ($headline eq "");
1221         print DEBUG "handle_request: got headline $headline\n";
1222         if ($headline =~ /^(\S+):\s*(.*)$/) {
1223                 $header{$lastheader = lc($1)} = $2;
1224                 }
1225         elsif ($headline =~ /^\s+(.*)$/) {
1226                 $header{$lastheader} .= $headline;
1227                 }
1228         else {
1229                 &http_error(400, "Bad Header $headline");
1230                 }
1231         }
1232 if (defined($header{'host'})) {
1233         if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1234                 ($host, $port) = ($1, $2);
1235                 }
1236         else {
1237                 $host = $header{'host'};
1238                 }
1239         if ($config{'musthost'} && $host ne $config{'musthost'}) {
1240                 # Disallowed hostname used
1241                 &http_error(400, "Invalid HTTP hostname");
1242                 }
1243         }
1244 undef(%in);
1245 if ($page =~ /^([^\?]+)\?(.*)$/) {
1246         # There is some query string information
1247         $page = $1;
1248         $querystring = $2;
1249         print DEBUG "handle_request: querystring=$querystring\n";
1250         if ($querystring !~ /=/) {
1251                 $queryargs = $querystring;
1252                 $queryargs =~ s/\+/ /g;
1253                 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1254                 $querystring = "";
1255                 }
1256         else {
1257                 # Parse query-string parameters
1258                 local @in = split(/\&/, $querystring);
1259                 foreach $i (@in) {
1260                         local ($k, $v) = split(/=/, $i, 2);
1261                         $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1262                         $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1263                         $in{$k} = $v;
1264                         }
1265                 }
1266         }
1267 $posted_data = undef;
1268 if ($method eq 'POST' &&
1269     $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1270         # Read in posted query string information, up the configured maximum
1271         # post request length
1272         $clen = $header{"content-length"};
1273         $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1274         while(length($posted_data) < $clen_read) {
1275                 $buf = &read_data($clen_read - length($posted_data));
1276                 if (!length($buf)) {
1277                         &http_error(500, "Failed to read POST request");
1278                         }
1279                 chomp($posted_data);
1280                 $posted_data =~ s/\015$//mg;
1281                 $posted_data .= $buf;
1282                 }
1283         print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1284         if ($clen_read != $clen && length($posted_data) > $clen) {
1285                 # If the client sent more data than we asked for, chop the
1286                 # rest off
1287                 $posted_data = substr($posted_data, 0, $clen);
1288                 }
1289         if (length($posted_data) > $clen) {
1290                 # When the client sent too much, delay so that it gets headers
1291                 sleep(3);
1292                 }
1293         if ($header{'user-agent'} =~ /MSIE/ &&
1294             $header{'user-agent'} !~ /Opera/i) {
1295                 # MSIE includes an extra newline in the data
1296                 $posted_data =~ s/\r|\n//g;
1297                 }
1298         local @in = split(/\&/, $posted_data);
1299         foreach $i (@in) {
1300                 local ($k, $v) = split(/=/, $i, 2);
1301                 #$v =~ s/\r|\n//g;
1302                 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1303                 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1304                 $in{$k} = $v;
1305                 }
1306         print DEBUG "handle_request: posted_data=$posted_data\n";
1307         }
1308
1309 # replace %XX sequences in page
1310 $page =~ s/%(..)/pack("c",hex($1))/ge;
1311
1312 # Check if the browser's user agent indicates a mobile device
1313 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1314
1315 # Check if Host: header is for a mobile URL
1316 foreach my $m (@mobile_prefixes) {
1317         if ($header{'host'} =~ /^\Q$m\E/i) {
1318                 $mobile_device = 1;
1319                 }
1320         }
1321
1322 # check for the logout flag file, and if existant deny authentication
1323 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1324         print DEBUG "handle_request: logout flag set\n";
1325         $deny_authentication++;
1326         open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1327         chop($count = <LOGOUT>);
1328         close(LOGOUT);
1329         $count--;
1330         if ($count > 0) {
1331                 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1332                 print LOGOUT "$count\n";
1333                 close(LOGOUT);
1334                 }
1335         else {
1336                 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1337                 }
1338         }
1339
1340 # check for any redirect for the requested URL
1341 foreach my $pfx (@strip_prefix) {
1342         my $l = length($pfx);
1343         if(length($page) >= $l &&
1344            substr($page,0,$l) eq $pfx) {
1345                 $page=substr($page,$l);
1346                 last;
1347                 }
1348         }
1349 $simple = &simplify_path($page, $bogus);
1350 $rpath = $simple;
1351 $rpath .= "&".$querystring if (defined($querystring));
1352 $redir = $redirect{$rpath};
1353 if (defined($redir)) {
1354         print DEBUG "handle_request: redir=$redir\n";
1355         &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1356         &write_data("Date: $datestr\r\n");
1357         &write_data("Server: $config{'server'}\r\n");
1358         local $ssl = $use_ssl || $config{'inetd_ssl'};
1359         $portstr = $port == 80 && !$ssl ? "" :
1360                    $port == 443 && $ssl ? "" : ":$port";
1361         $prot = $ssl ? "https" : "http";
1362         &write_data("Location: $prot://$host$portstr$redir\r\n");
1363         &write_keep_alive(0);
1364         &write_data("\r\n");
1365         return 0;
1366         }
1367
1368 # Check for a DAV request
1369 $davpath = undef;
1370 foreach my $d (@davpaths) {
1371         if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1372                 $davpath = $d;
1373                 last;
1374                 }
1375         }
1376 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1377         &http_error(400, "Bad Request method $method");
1378         }
1379
1380 # Check for password if needed
1381 if (%users) {
1382         print DEBUG "handle_request: Need authentication\n";
1383         $validated = 0;
1384         $blocked = 0;
1385
1386         # Session authentication is never used for connections by
1387         # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1388         # or mobile browsers if requested.
1389         if ($header{'user-agent'} =~ /webmin/i ||
1390             $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1391             $sessiononly{$simple} || $davpath ||
1392             $simple eq "/xmlrpc.cgi" ||
1393             $acptip eq $config{'host_nosession'} ||
1394             $mobile_device && $config{'mobile_nosession'}) {
1395                 print DEBUG "handle_request: Forcing HTTP authentication\n";
1396                 $config{'session'} = 0;
1397                 }
1398
1399         # check for SSL authentication
1400         if ($use_ssl && $verified_client) {
1401                 $peername = Net::SSLeay::X509_NAME_oneline(
1402                                 Net::SSLeay::X509_get_subject_name(
1403                                         Net::SSLeay::get_peer_certificate(
1404                                                 $ssl_con)));
1405                 local $peername2 = $peername;
1406                 $peername2 =~ s/Email=/emailAddress=/ ||
1407                         $peername2 =~ s/emailAddress=/Email=/;
1408                 foreach $u (keys %certs) {
1409                         if ($certs{$u} eq $peername ||
1410                             $certs{$u} eq $peername2) {
1411                                 $authuser = $u;
1412                                 $validated = 2;
1413                                 #syslog("info", "%s", "SSL login as $authuser from $acpthost") if ($use_syslog);
1414                                 last;
1415                                 }
1416                         }
1417                 if ($use_syslog && !$validated) {
1418                         syslog("crit", "%s",
1419                                "Unknown SSL certificate $peername");
1420                         }
1421                 }
1422
1423         if (!$validated && !$deny_authentication) {
1424                 # check for IP-based authentication
1425                 local $a;
1426                 foreach $a (keys %ipaccess) {
1427                         if ($acptip eq $a) {
1428                                 # It does! Auth as the user
1429                                 $validated = 3;
1430                                 $baseauthuser = $authuser =
1431                                         $ipaccess{$a};
1432                                 }
1433                         }
1434                 }
1435
1436         # Check for normal HTTP authentication
1437         if (!$validated && !$deny_authentication && !$config{'session'} &&
1438             $header{authorization} =~ /^basic\s+(\S+)$/i) {
1439                 # authorization given..
1440                 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1441                 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1442                 local ($vu, $expired, $nonexist) =
1443                         &validate_user($authuser, $authpass, $host);
1444                 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1445                 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1446                         $authuser = $vu;
1447                         $validated = 1;
1448                         }
1449                 else {
1450                         $validated = 0;
1451                         }
1452                 if ($use_syslog && !$validated) {
1453                         syslog("crit", "%s",
1454                                ($nonexist ? "Non-existent" :
1455                                 $expired ? "Expired" : "Invalid").
1456                                " login as $authuser from $acpthost");
1457                         }
1458                 if ($authuser =~ /\r|\n|\s/) {
1459                         &http_error(500, "Invalid username",
1460                                     "Username contains invalid characters");
1461                         }
1462                 if ($authpass =~ /\r|\n/) {
1463                         &http_error(500, "Invalid password",
1464                                     "Password contains invalid characters");
1465                         }
1466
1467                 if ($config{'passdelay'} && !$config{'inetd'}) {
1468                         # check with main process for delay
1469                         print DEBUG "handle_request: about to ask for password delay\n";
1470                         print $PASSINw "delay $authuser $acptip $validated\n";
1471                         <$PASSOUTr> =~ /(\d+) (\d+)/;
1472                         $blocked = $2;
1473                         print DEBUG "handle_request: password delay $1 $2\n";
1474                         sleep($1);
1475                         }
1476                 }
1477
1478         # Check for a visit to the special session login page
1479         if ($config{'session'} && !$deny_authentication &&
1480             $page eq $config{'session_login'}) {
1481                 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1482                         # Logout clicked .. remove the session
1483                         local $sid = $2;
1484                         print $PASSINw "delete $sid\n";
1485                         local $louser = <$PASSOUTr>;
1486                         chop($louser);
1487                         $logout = 1;
1488                         $already_session_id = undef;
1489                         $authuser = $baseauthuser = undef;
1490                         if ($louser) {
1491                                 if ($use_syslog) {
1492                                         syslog("info", "%s", "Logout by $louser from $acpthost");
1493                                         }
1494                                 &run_logout_script($louser, $sid,
1495                                                    $acptip, $localip);
1496                                 &write_logout_utmp($louser, $actphost);
1497                                 }
1498                         }
1499                 else {
1500                         # Validate the user
1501                         if ($in{'user'} =~ /\r|\n|\s/) {
1502                                 &http_error(500, "Invalid username",
1503                                     "Username contains invalid characters");
1504                                 }
1505                         if ($in{'pass'} =~ /\r|\n/) {
1506                                 &http_error(500, "Invalid password",
1507                                     "Password contains invalid characters");
1508                                 }
1509
1510                         local ($vu, $expired, $nonexist) =
1511                                 &validate_user($in{'user'}, $in{'pass'}, $host);
1512                         local $hrv = &handle_login(
1513                                         $vu || $in{'user'}, $vu ? 1 : 0,
1514                                         $expired, $nonexist, $in{'pass'},
1515                                         $in{'notestingcookie'});
1516                         return $hrv if (defined($hrv));
1517                         }
1518                 }
1519
1520         # Check for a visit to the special PAM login page
1521         if ($config{'session'} && !$deny_authentication &&
1522             $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1523             !$in{'restart'}) {
1524                 # A question has been entered .. submit it to the main process
1525                 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1526                 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1527                 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1528                         &http_error(500, "Invalid response",
1529                             "Response contains invalid characters");
1530                         }
1531
1532                 if (!$in{'cid'}) {
1533                         # Start of a new conversation - answer must be username
1534                         $cid = &generate_random_id($in{'answer'});
1535                         print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1536                         }
1537                 else {
1538                         # A response to a previous question
1539                         $cid = $in{'cid'};
1540                         print $PASSINw "pamanswer $cid $in{'answer'}\n";
1541                         }
1542
1543                 # Read back the response, and the next question (if any)
1544                 local $line = <$PASSOUTr>;
1545                 $line =~ s/\r|\n//g;
1546                 local ($rv, $question) = split(/\s+/, $line, 2);
1547                 if ($rv == 0) {
1548                         # Cannot login!
1549                         local $hrv = &handle_login(
1550                                 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1551                                                              : "unknown",
1552                                 0, 0, 1, undef);
1553                         return $hrv if (defined($hrv));
1554                         }
1555                 elsif ($rv == 1 || $rv == 3) {
1556                         # Another question .. force use of PAM CGI
1557                         $validated = 1;
1558                         $method = "GET";
1559                         $querystring .= "&cid=$cid&question=".
1560                                         &urlize($question);
1561                         $querystring .= "&password=1" if ($rv == 3);
1562                         $queryargs = "";
1563                         $page = $config{'pam_login'};
1564                         $miniserv_internal = 1;
1565                         $logged_code = 401;
1566                         }
1567                 elsif ($rv == 2) {
1568                         # Got back a final ok or failure
1569                         local ($user, $ok, $expired, $nonexist) =
1570                                 split(/\s+/, $question);
1571                         local $hrv = &handle_login(
1572                                 $user, $ok, $expired, $nonexist, undef,
1573                                 $in{'notestingcookie'});
1574                         return $hrv if (defined($hrv));
1575                         }
1576                 elsif ($rv == 4) {
1577                         # A message from PAM .. tell the user
1578                         $validated = 1;
1579                         $method = "GET";
1580                         $querystring .= "&cid=$cid&message=".
1581                                         &urlize($question);
1582                         $queryargs = "";
1583                         $page = $config{'pam_login'};
1584                         $miniserv_internal = 1;
1585                         $logged_code = 401;
1586                         }
1587                 }
1588
1589         # Check for a visit to the special password change page
1590         if ($config{'session'} && !$deny_authentication &&
1591             $page eq $config{'password_change'} && !$validated) {
1592                 # Just let this slide ..
1593                 $validated = 1;
1594                 $miniserv_internal = 3;
1595                 }
1596
1597         # Check for an existing session
1598         if ($config{'session'} && !$validated) {
1599                 if ($already_session_id) {
1600                         $session_id = $already_session_id;
1601                         $authuser = $already_authuser;
1602                         $validated = 1;
1603                         }
1604                 elsif (!$deny_authentication &&
1605                        $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1606                         $session_id = $2;
1607                         local $notimeout = $in{'webmin_notimeout'} ? 1 : 0;
1608                         print $PASSINw "verify $session_id $notimeout\n";
1609                         <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1610                         if ($1 == 2) {
1611                                 # Valid session continuation
1612                                 $validated = 1;
1613                                 $authuser = $2;
1614                                 #$already_session_id = $session_id;
1615                                 $already_authuser = $authuser;
1616                                 }
1617                         elsif ($1 == 1) {
1618                                 # Session timed out
1619                                 $timed_out = $2;
1620                                 }
1621                         else {
1622                                 # Invalid session ID .. don't set verified
1623                                 }
1624                         }
1625                 }
1626
1627         # Check for local authentication
1628         if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1629                 if (defined($users{$localauth_user})) {
1630                         # Local user exists in webmin users file
1631                         $validated = 1;
1632                         $authuser = $localauth_user;
1633                         }
1634                 else {
1635                         # Check if local user is allowed by unixauth
1636                         local @can = &can_user_login($localauth_user,
1637                                                      undef, $host);
1638                         if ($can[0]) {
1639                                 $validated = 2;
1640                                 $authuser = $localauth_user;
1641                                 }
1642                         else {
1643                                 $localauth_user = undef;
1644                                 }
1645                         }
1646                 }
1647
1648         if (!$validated) {
1649                 # Check if this path allows anonymous access
1650                 local $a;
1651                 foreach $a (keys %anonymous) {
1652                         if (substr($simple, 0, length($a)) eq $a) {
1653                                 # It does! Auth as the user, if IP access
1654                                 # control allows him.
1655                                 if (&check_user_ip($anonymous{$a}) &&
1656                                     &check_user_time($anonymous{$a})) {
1657                                         $validated = 3;
1658                                         $baseauthuser = $authuser =
1659                                                 $anonymous{$a};
1660                                         }
1661                                 }
1662                         }
1663                 }
1664
1665         if (!$validated) {
1666                 # Check if this path allows unauthenticated access
1667                 local ($u, $unauth);
1668                 foreach $u (@unauth) {
1669                         $unauth++ if ($simple =~ /$u/);
1670                         }
1671                 if (!$bogus && $unauth) {
1672                         # Unauthenticated directory or file request - approve it
1673                         $validated = 4;
1674                         $baseauthuser = $authuser = undef;
1675                         }
1676                 }
1677
1678         if (!$validated) {
1679                 if ($blocked == 0) {
1680                         # No password given.. ask
1681                         if ($config{'pam_conv'} && $use_pam) {
1682                                 # Force CGI for PAM question, starting with
1683                                 # the username which is always needed
1684                                 $validated = 1;
1685                                 $method = "GET";
1686                                 $querystring .= "&initial=1&question=".
1687                                                 &urlize("Username");
1688                                 $querystring .= "&failed=$failed_user" if ($failed_user);
1689                                 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1690                                 $queryargs = "";
1691                                 $page = $config{'pam_login'};
1692                                 $miniserv_internal = 1;
1693                                 $logged_code = 401;
1694                                 }
1695                         elsif ($config{'session'}) {
1696                                 # Force CGI for session login
1697                                 $validated = 1;
1698                                 if ($logout) {
1699                                         $querystring .= "&logout=1&page=/";
1700                                         }
1701                                 else {
1702                                         # Re-direct to current module only
1703                                         local $rpage = $request_uri;
1704                                         if (!$config{'loginkeeppage'}) {
1705                                                 $rpage =~ s/\?.*$//;
1706                                                 $rpage =~ s/[^\/]+$//
1707                                                 }
1708                                         $querystring = "page=".&urlize($rpage);
1709                                         }
1710                                 $method = "GET";
1711                                 $querystring .= "&failed=$failed_user" if ($failed_user);
1712                                 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1713                                 $queryargs = "";
1714                                 $page = $config{'session_login'};
1715                                 $miniserv_internal = 1;
1716                                 $logged_code = 401;
1717                                 }
1718                         else {
1719                                 # Ask for login with HTTP authentication
1720                                 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1721                                 &write_data("Date: $datestr\r\n");
1722                                 &write_data("Server: $config{'server'}\r\n");
1723                                 &write_data("WWW-authenticate: Basic ".
1724                                            "realm=\"$config{'realm'}\"\r\n");
1725                                 &write_keep_alive(0);
1726                                 &write_data("Content-type: text/html\r\n");
1727                                 &write_data("\r\n");
1728                                 &reset_byte_count();
1729                                 &write_data("<html>\n");
1730                                 &write_data("<head><title>Unauthorized</title></head>\n");
1731                                 &write_data("<body><h1>Unauthorized</h1>\n");
1732                                 &write_data("A password is required to access this\n");
1733                                 &write_data("web server. Please try again. <p>\n");
1734                                 &write_data("</body></html>\n");
1735                                 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1736                                 return 0;
1737                                 }
1738                         }
1739                 elsif ($blocked == 1) {
1740                         # when the host has been blocked, give it an error
1741                         &http_error(403, "Access denied for $acptip. The host ".
1742                                          "has been blocked because of too ".
1743                                          "many authentication failures.");
1744                         }
1745                 elsif ($blocked == 2) {
1746                         # when the user has been blocked, give it an error
1747                         &http_error(403, "Access denied. The user ".
1748                                          "has been blocked because of too ".
1749                                          "many authentication failures.");
1750                         }
1751                 }
1752         else {
1753                 # Get the real Webmin username
1754                 local @can = &can_user_login($authuser, undef, $host);
1755                 $baseauthuser = $can[3] || $authuser;
1756
1757                 if ($config{'remoteuser'} && !$< && $validated) {
1758                         # Switch to the UID of the remote user (if he exists)
1759                         local @u = getpwnam($authuser);
1760                         if (@u && $< != $u[2]) {
1761                                 $( = $u[3]; $) = "$u[3] $u[3]";
1762                                 ($>, $<) = ($u[2], $u[2]);
1763                                 }
1764                         else {
1765                                 &http_error(500, "Unix user $authuser does not exist");
1766                                 return 0;
1767                                 }
1768                         }
1769                 }
1770
1771         # Check per-user IP access control
1772         if (!&check_user_ip($baseauthuser)) {
1773                 &http_error(403, "Access denied for $acptip for $baseauthuser");
1774                 return 0;
1775                 }
1776
1777         # Check per-user allowed times
1778         if (!&check_user_time($baseauthuser)) {
1779                 &http_error(403, "Access denied at the current time");
1780                 return 0;
1781                 }
1782         }
1783
1784 # Validate the path, and convert to canonical form
1785 rerun:
1786 $simple = &simplify_path($page, $bogus);
1787 print DEBUG "handle_request: page=$page simple=$simple\n";
1788 if ($bogus) {
1789         &http_error(400, "Invalid path");
1790         }
1791
1792 # Check for a DAV request
1793 if ($davpath) {
1794         return &handle_dav_request($davpath);
1795         }
1796
1797 # Work out the active theme(s)
1798 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1799                         $config{'mobile_preroot'} :
1800                  $authuser && defined($config{'preroot_'.$authuser}) ?
1801                         $config{'preroot_'.$authuser} :
1802                  $authuser && $baseauthuser &&
1803                      defined($config{'preroot_'.$baseauthuser}) ?
1804                         $config{'preroot_'.$baseauthuser} :
1805                         $config{'preroot'};
1806 local @preroots = reverse(split(/\s+/, $preroots));
1807
1808 # Canonicalize the directories
1809 foreach my $preroot (@preroots) {
1810         # Always under the current webmin root
1811         $preroot =~ s/^.*\///g;
1812         $preroot = $roots[0].'/'.$preroot;
1813         }
1814
1815 # Look in the theme root directories first
1816 local ($full, @stfull);
1817 $foundroot = undef;
1818 foreach my $preroot (@preroots) {
1819         $is_directory = 1;
1820         $sofar = "";
1821         $full = $preroot.$sofar;
1822         $scriptname = $simple;
1823         foreach $b (split(/\//, $simple)) {
1824                 if ($b ne "") { $sofar .= "/$b"; }
1825                 $full = $preroot.$sofar;
1826                 @stfull = stat($full);
1827                 if (!@stfull) { undef($full); last; }
1828
1829                 # Check if this is a directory
1830                 if (-d _) {
1831                         # It is.. go on parsing
1832                         $is_directory = 1;
1833                         next;
1834                         }
1835                 else {
1836                         $is_directory = 0;
1837                         }
1838
1839                 # Check if this is a CGI program
1840                 if (&get_type($full) eq "internal/cgi") {
1841                         $pathinfo = substr($simple, length($sofar));
1842                         $pathinfo .= "/" if ($page =~ /\/$/);
1843                         $scriptname = $sofar;
1844                         last;
1845                         }
1846                 }
1847
1848         # Don't stop at a directory unless this is the last theme, which
1849         # is the 'real' one that provides the .cgi scripts
1850         if ($is_directory && $preroot ne $preroots[$#preroots]) {
1851                 next;
1852                 }
1853
1854         if ($full) {
1855                 # Found it!
1856                 if ($sofar eq '') {
1857                         $cgi_pwd = $roots[0];
1858                         }
1859                 elsif ($is_directory) {
1860                         $cgi_pwd = "$roots[0]$sofar";
1861                         }
1862                 else {
1863                         "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1864                         $cgi_pwd = $1;
1865                         }
1866                 $foundroot = $preroot;
1867                 if ($is_directory) {
1868                         # Check for index files in the directory
1869                         local $foundidx;
1870                         foreach $idx (split(/\s+/, $config{"index_docs"})) {
1871                                 $idxfull = "$full/$idx";
1872                                 local @stidxfull = stat($idxfull);
1873                                 if (-r _ && !-d _) {
1874                                         $full = $idxfull;
1875                                         @stfull = @stidxfull;
1876                                         $is_directory = 0;
1877                                         $scriptname .= "/"
1878                                                 if ($scriptname ne "/");
1879                                         $foundidx++;
1880                                         last;
1881                                         }
1882                                 }
1883                         @stfull = stat($full) if (!$foundidx);
1884                         }
1885                 }
1886         last if ($foundroot);
1887         }
1888 print DEBUG "handle_request: initial full=$full\n";
1889
1890 # Look in the real root directories, stopping when we find a file or directory
1891 if (!$full || $is_directory) {
1892         ROOT: foreach $root (@roots) {
1893                 $sofar = "";
1894                 $full = $root.$sofar;
1895                 $scriptname = $simple;
1896                 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
1897                         if ($b ne "") { $sofar .= "/$b"; }
1898                         $full = $root.$sofar;
1899                         @stfull = stat($full);
1900                         if (!@stfull) {
1901                                 next ROOT;
1902                                 }
1903
1904                         # Check if this is a directory
1905                         if (-d _) {
1906                                 # It is.. go on parsing
1907                                 next;
1908                                 }
1909
1910                         # Check if this is a CGI program
1911                         if (&get_type($full) eq "internal/cgi") {
1912                                 $pathinfo = substr($simple, length($sofar));
1913                                 $pathinfo .= "/" if ($page =~ /\/$/);
1914                                 $scriptname = $sofar;
1915                                 last;
1916                                 }
1917                         }
1918
1919                 # Run CGI in the same directory as whatever file
1920                 # was requested
1921                 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
1922
1923                 if (-e $full) {
1924                         # Found something!
1925                         $realroot = $root;
1926                         $foundroot = $root;
1927                         last;
1928                         }
1929                 }
1930         if (!@stfull) { &http_error(404, "File not found"); }
1931         }
1932 print DEBUG "handle_request: full=$full\n";
1933 @stfull = stat($full) if (!@stfull);
1934
1935 # check filename against denyfile regexp
1936 local $denyfile = $config{'denyfile'};
1937 if ($denyfile && $full =~ /$denyfile/) {
1938         &http_error(403, "Access denied to $page");
1939         return 0;
1940         }
1941
1942 # Reached the end of the path OK.. see what we've got
1943 if (-d _) {
1944         # See if the URL ends with a / as it should
1945         print DEBUG "handle_request: found a directory\n";
1946         if ($page !~ /\/$/) {
1947                 # It doesn't.. redirect
1948                 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1949                 $ssl = $use_ssl || $config{'inetd_ssl'};
1950                 $portstr = $port == 80 && !$ssl ? "" :
1951                            $port == 443 && $ssl ? "" : ":$port";
1952                 &write_data("Date: $datestr\r\n");
1953                 &write_data("Server: $config{server}\r\n");
1954                 $prot = $ssl ? "https" : "http";
1955                 &write_data("Location: $prot://$host$portstr$page/\r\n");
1956                 &write_keep_alive(0);
1957                 &write_data("\r\n");
1958                 &log_request($acpthost, $authuser, $reqline, 302, 0);
1959                 return 0;
1960                 }
1961         # A directory.. check for index files
1962         local $foundidx;
1963         foreach $idx (split(/\s+/, $config{"index_docs"})) {
1964                 $idxfull = "$full/$idx";
1965                 @stidxfull = stat($idxfull);
1966                 if (-r _ && !-d _) {
1967                         $cgi_pwd = $full;
1968                         $full = $idxfull;
1969                         @stfull = @stidxfull;
1970                         $scriptname .= "/" if ($scriptname ne "/");
1971                         $foundidx++;
1972                         last;
1973                         }
1974                 }
1975         @stfull = stat($full) if (!$foundidx);
1976         }
1977 if (-d _) {
1978         # This is definately a directory.. list it
1979         print DEBUG "handle_request: listing directory\n";
1980         local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
1981                       "Date: $datestr\r\n".
1982                       "Server: $config{server}\r\n".
1983                       "Content-type: text/html\r\n";
1984         &write_data($resp);
1985         &write_keep_alive(0);
1986         &write_data("\r\n");
1987         &reset_byte_count();
1988         &write_data("<h1>Index of $simple</h1>\n");
1989         &write_data("<pre>\n");
1990         &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
1991                         "Name", "Last Modified", "Size");
1992         &write_data("<hr>\n");
1993         opendir(DIR, $full);
1994         while($df = readdir(DIR)) {
1995                 if ($df =~ /^\./) { next; }
1996                 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
1997                 (@stbuf = stat($fulldf)) || next;
1998                 if (-d _) { $df .= "/"; }
1999                 @tm = localtime($stbuf[9]);
2000                 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2001                                 $tm[3],$tm[4]+1,$tm[5]+1900,
2002                                 $tm[0],$tm[1],$tm[2];
2003                 $len = length($df); $rest = " "x(35-$len);
2004                 &write_data(sprintf 
2005                  "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2006                  $df, $df, $fdate, $stbuf[7]);
2007                 }
2008         closedir(DIR);
2009         &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2010         return 0;
2011         }
2012
2013 # CGI or normal file
2014 local $rv;
2015 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2016         # A CGI program to execute
2017         print DEBUG "handle_request: executing CGI\n";
2018         $envtz = $ENV{"TZ"};
2019         $envuser = $ENV{"USER"};
2020         $envpath = $ENV{"PATH"};
2021         $envlang = $ENV{"LANG"};
2022         $envroot = $ENV{"SystemRoot"};
2023         foreach my $k (keys %ENV) {
2024                 delete($ENV{$k});
2025                 }
2026         $ENV{"PATH"} = $envpath if ($envpath);
2027         $ENV{"TZ"} = $envtz if ($envtz);
2028         $ENV{"USER"} = $envuser if ($envuser);
2029         $ENV{"OLD_LANG"} = $envlang if ($envlang);
2030         $ENV{"SystemRoot"} = $envroot if ($envroot);
2031         $ENV{"HOME"} = $user_homedir;
2032         $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2033         $ENV{"SERVER_NAME"} = $host;
2034         $ENV{"SERVER_ADMIN"} = $config{"email"};
2035         $ENV{"SERVER_ROOT"} = $roots[0];
2036         $ENV{"SERVER_REALROOT"} = $realroot;
2037         $ENV{"SERVER_PORT"} = $port;
2038         $ENV{"REMOTE_HOST"} = $acpthost;
2039         $ENV{"REMOTE_ADDR"} = $acptip;
2040         $ENV{"REMOTE_USER"} = $authuser;
2041         $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2042                                         $baseauthuser : undef;
2043         $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2044                                             $config{'pass_password'});
2045         print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2046         print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2047         $ENV{"SSL_USER"} = $peername if ($validated == 2);
2048         $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2049         $ENV{"DOCUMENT_ROOT"} = $roots[0];
2050         $ENV{"DOCUMENT_REALROOT"} = $realroot;
2051         $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2052         $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2053         $ENV{"REQUEST_METHOD"} = $method;
2054         $ENV{"SCRIPT_NAME"} = $scriptname;
2055         $ENV{"SCRIPT_FILENAME"} = $full;
2056         $ENV{"REQUEST_URI"} = $request_uri;
2057         $ENV{"PATH_INFO"} = $pathinfo;
2058         if ($pathinfo) {
2059                 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2060                 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2061                 }
2062         $ENV{"QUERY_STRING"} = $querystring;
2063         $ENV{"MINISERV_CONFIG"} = $config_file;
2064         $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2065         $ENV{"SESSION_ID"} = $session_id if ($session_id);
2066         $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2067         $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2068         if (defined($header{"content-length"})) {
2069                 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2070                 }
2071         if (defined($header{"content-type"})) {
2072                 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2073                 }
2074         foreach $h (keys %header) {
2075                 ($hname = $h) =~ tr/a-z/A-Z/;
2076                 $hname =~ s/\-/_/g;
2077                 $ENV{"HTTP_$hname"} = $header{$h};
2078                 }
2079         $ENV{"PWD"} = $cgi_pwd;
2080         foreach $k (keys %config) {
2081                 if ($k =~ /^env_(\S+)$/) {
2082                         $ENV{$1} = $config{$k};
2083                         }
2084                 }
2085         delete($ENV{'HTTP_AUTHORIZATION'});
2086         $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2087         $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2088
2089         # Check if the CGI can be handled internally
2090         open(CGI, $full);
2091         local $first = <CGI>;
2092         close(CGI);
2093         $first =~ s/[#!\r\n]//g;
2094         $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2095         seek(STDERR, 0, 2);
2096         if (!$config{'forkcgis'} &&
2097             ($first eq $perl_path || $first eq $linked_perl_path) &&
2098               $] >= 5.004 ||
2099             $config{'internalcgis'}) {
2100                 # setup environment for eval
2101                 chdir($ENV{"PWD"});
2102                 @ARGV = split(/\s+/, $queryargs);
2103                 $0 = $full;
2104                 if ($posted_data) {
2105                         # Already read the post input
2106                         $postinput = $posted_data;
2107                         }
2108                 $clen = $header{"content-length"};
2109                 $SIG{'CHLD'} = 'DEFAULT';
2110                 eval {
2111                         # Have SOCK closed if the perl exec's something
2112                         use Fcntl;
2113                         fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2114                         };
2115                 #shutdown(SOCK, 0);
2116
2117                 if ($config{'log'}) {
2118                         open(MINISERVLOG, ">>$config{'logfile'}");
2119                         if ($config{'logperms'}) {
2120                                 chmod(oct($config{'logperms'}),
2121                                       $config{'logfile'});
2122                                 }
2123                         else {
2124                                 chmod(0600, $config{'logfile'});
2125                                 }
2126                         }
2127                 $doing_eval = 1;
2128                 $main_process_id = $$;
2129                 $pkg = "main";
2130                 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2131                         # Eval in package from Webmin module name
2132                         $pkg = $1;
2133                         $pkg =~ s/[^A-Za-z0-9]/_/g;
2134                         }
2135                 eval "
2136                         \%pkg::ENV = \%ENV;
2137                         package $pkg;
2138                         tie(*STDOUT, 'miniserv');
2139                         tie(*STDIN, 'miniserv');
2140                         do \$miniserv::full;
2141                         die \$@ if (\$@);
2142                         ";
2143                 $doing_eval = 0;
2144                 if ($@) {
2145                         # Error in perl!
2146                         &http_error(500, "Perl execution failed",
2147                                     $config{'noshowstderr'} ? undef : $@);
2148                         }
2149                 elsif (!$doneheaders && !$nph_script) {
2150                         &http_error(500, "Missing Headers");
2151                         }
2152                 $rv = 0;
2153                 }
2154         else {
2155                 $infile = undef;
2156                 if (!$on_windows) {
2157                         # fork the process that actually executes the CGI
2158                         pipe(CGIINr, CGIINw);
2159                         pipe(CGIOUTr, CGIOUTw);
2160                         pipe(CGIERRr, CGIERRw);
2161                         if (!($cgipid = fork())) {
2162                                 @execargs = ( $full, split(/\s+/, $queryargs) );
2163                                 chdir($ENV{"PWD"});
2164                                 close(SOCK);
2165                                 open(STDIN, "<&CGIINr");
2166                                 open(STDOUT, ">&CGIOUTw");
2167                                 open(STDERR, ">&CGIERRw");
2168                                 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2169                                 exec(@execargs) ||
2170                                         die "Failed to exec $full : $!\n";
2171                                 exit(0);
2172                                 }
2173                         close(CGIINr); close(CGIOUTw); close(CGIERRw);
2174                         }
2175                 else {
2176                         # write CGI input to a temp file
2177                         $infile = "$config{'tempbase'}.$$";
2178                         open(CGIINw, ">$infile");
2179                         # NOT binary mode, as CGIs don't read in it!
2180                         }
2181
2182                 # send post data
2183                 if ($posted_data) {
2184                         # already read the posted data
2185                         print CGIINw $posted_data;
2186                         }
2187                 $clen = $header{"content-length"};
2188                 if ($method eq "POST" && $clen_read < $clen) {
2189                         $SIG{'PIPE'} = 'IGNORE';
2190                         $got = $clen_read;
2191                         while($got < $clen) {
2192                                 $buf = &read_data($clen-$got);
2193                                 if (!length($buf)) {
2194                                         kill('TERM', $cgipid);
2195                                         unlink($infile) if ($infile);
2196                                         &http_error(500, "Failed to read ".
2197                                                          "POST request");
2198                                         }
2199                                 $got += length($buf);
2200                                 local ($wrote) = (print CGIINw $buf);
2201                                 last if (!$wrote);
2202                                 }
2203                         # If the CGI terminated early, we still need to read
2204                         # from the browser and throw away
2205                         while($got < $clen) {
2206                                 $buf = &read_data($clen-$got);
2207                                 if (!length($buf)) {
2208                                         kill('TERM', $cgipid);
2209                                         unlink($infile) if ($infile);
2210                                         &http_error(500, "Failed to read ".
2211                                                          "POST request");
2212                                         }
2213                                 $got += length($buf);
2214                                 }
2215                         $SIG{'PIPE'} = 'DEFAULT';
2216                         }
2217                 close(CGIINw);
2218                 shutdown(SOCK, 0);
2219
2220                 if ($on_windows) {
2221                         # Run the CGI program, and feed it input
2222                         chdir($ENV{"PWD"});
2223                         local $qqueryargs = join(" ", map { "\"$_\"" }
2224                                                  split(/\s+/, $queryargs));
2225                         if ($first =~ /(perl|perl.exe)$/i) {
2226                                 # On Windows, run with Perl
2227                                 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2228                                 }
2229                         else {
2230                                 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2231                                 }
2232                         binmode(CGIOUTr);
2233                         }
2234
2235                 if (!$nph_script) {
2236                         # read back cgi headers
2237                         select(CGIOUTr); $|=1; select(STDOUT);
2238                         $got_blank = 0;
2239                         while(1) {
2240                                 $line = <CGIOUTr>;
2241                                 $line =~ s/\r|\n//g;
2242                                 if ($line eq "") {
2243                                         if ($got_blank || %cgiheader) { last; }
2244                                         $got_blank++;
2245                                         next;
2246                                         }
2247                                 if ($line !~ /^(\S+):\s+(.*)$/) {
2248                                         $errs = &read_errors(CGIERRr);
2249                                         close(CGIOUTr); close(CGIERRr);
2250                                         unlink($infile) if ($infile);
2251                                         &http_error(500, "Bad Header", $errs);
2252                                         }
2253                                 $cgiheader{lc($1)} = $2;
2254                                 push(@cgiheader, [ $1, $2 ]);
2255                                 }
2256                         if ($cgiheader{"location"}) {
2257                                 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2258                                 &write_data("Date: $datestr\r\n");
2259                                 &write_data("Server: $config{'server'}\r\n");
2260                                 &write_keep_alive(0);
2261                                 # ignore the rest of the output. This is a hack,
2262                                 # but is necessary for IE in some cases :(
2263                                 close(CGIOUTr); close(CGIERRr);
2264                                 }
2265                         elsif ($cgiheader{"content-type"} eq "") {
2266                                 close(CGIOUTr); close(CGIERRr);
2267                                 unlink($infile) if ($infile);
2268                                 $errs = &read_errors(CGIERRr);
2269                                 &http_error(500, "Missing Content-Type Header",
2270                                     $config{'noshowstderr'} ? undef : $errs);
2271                                 }
2272                         else {
2273                                 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2274                                 &write_data("Date: $datestr\r\n");
2275                                 &write_data("Server: $config{'server'}\r\n");
2276                                 &write_keep_alive(0);
2277                                 }
2278                         foreach $h (@cgiheader) {
2279                                 &write_data("$h->[0]: $h->[1]\r\n");
2280                                 }
2281                         &write_data("\r\n");
2282                         }
2283                 &reset_byte_count();
2284                 while($line = <CGIOUTr>) {
2285                         &write_data($line);
2286                         }
2287                 close(CGIOUTr);
2288                 close(CGIERRr);
2289                 unlink($infile) if ($infile);
2290                 $rv = 0;
2291                 }
2292         }
2293 else {
2294         # A file to output
2295         print DEBUG "handle_request: outputting file\n";
2296         open(FILE, $full) || &http_error(404, "Failed to open file");
2297         binmode(FILE);
2298         local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2299                       "Date: $datestr\r\n".
2300                       "Server: $config{server}\r\n".
2301                       "Content-type: ".&get_type($full)."\r\n".
2302                       "Content-length: $stfull[7]\r\n".
2303                       "Last-Modified: ".&http_date($stfull[9])."\r\n".
2304                       "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2305         &write_data($resp);
2306         $rv = &write_keep_alive();
2307         &write_data("\r\n");
2308         &reset_byte_count();
2309         while(read(FILE, $buf, 1024) > 0) {
2310                 &write_data($buf);
2311                 }
2312         close(FILE);
2313         }
2314
2315 # log the request
2316 &log_request($acpthost, $authuser, $reqline,
2317              $logged_code ? $logged_code :
2318              $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2319 return $rv;
2320 }
2321
2322 # http_error(code, message, body, [dontexit])
2323 sub http_error
2324 {
2325 local $eh = $error_handler_recurse ? undef :
2326             $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2327             $config{'error_handler'} ? $config{'error_handler'} : undef;
2328 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2329 if ($eh) {
2330         # Call a CGI program for the error
2331         $page = "/$eh";
2332         $querystring = "code=$_[0]&message=".&urlize($_[1]).
2333                        "&body=".&urlize($_[2]);
2334         $error_handler_recurse++;
2335         $ok_code = $_[0];
2336         $ok_message = $_[1];
2337         goto rerun;
2338         }
2339 else {
2340         # Use the standard error message display
2341         &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2342         &write_data("Server: $config{server}\r\n");
2343         &write_data("Date: $datestr\r\n");
2344         &write_data("Content-type: text/html\r\n");
2345         &write_keep_alive(0);
2346         &write_data("\r\n");
2347         &reset_byte_count();
2348         &write_data("<h1>Error - $_[1]</h1>\n");
2349         if ($_[2]) {
2350                 &write_data("<pre>$_[2]</pre>\n");
2351                 }
2352         }
2353 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2354         if ($reqline);
2355 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2356 shutdown(SOCK, 1);
2357 exit if (!$_[3]);
2358 }
2359
2360 sub get_type
2361 {
2362 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2363         $t = $mime{$1};
2364         if ($t ne "") {
2365                 return $t;
2366                 }
2367         }
2368 return "text/plain";
2369 }
2370
2371 # simplify_path(path, bogus)
2372 # Given a path, maybe containing stuff like ".." and "." convert it to a
2373 # clean, absolute form.
2374 sub simplify_path
2375 {
2376 local($dir, @bits, @fixedbits, $b);
2377 $dir = $_[0];
2378 $dir =~ s/\\/\//g;      # fix windows \ in path
2379 $dir =~ s/^\/+//g;
2380 $dir =~ s/\/+$//g;
2381 $dir =~ s/\0//g;        # remove null bytes
2382 @bits = split(/\/+/, $dir);
2383 @fixedbits = ();
2384 $_[1] = 0;
2385 foreach $b (@bits) {
2386         if ($b eq ".") {
2387                 # Do nothing..
2388                 }
2389         elsif ($b eq ".." || $b eq "...") {
2390                 # Remove last dir
2391                 if (scalar(@fixedbits) == 0) {
2392                         $_[1] = 1;
2393                         return "/";
2394                         }
2395                 pop(@fixedbits);
2396                 }
2397         else {
2398                 # Add dir to list
2399                 push(@fixedbits, $b);
2400                 }
2401         }
2402 return "/" . join('/', @fixedbits);
2403 }
2404
2405 # b64decode(string)
2406 # Converts a string from base64 format to normal
2407 sub b64decode
2408 {
2409     local($str) = $_[0];
2410     local($res);
2411     $str =~ tr|A-Za-z0-9+=/||cd;
2412     $str =~ s/=+$//;
2413     $str =~ tr|A-Za-z0-9+/| -_|;
2414     while ($str =~ /(.{1,60})/gs) {
2415         my $len = chr(32 + length($1)*3/4);
2416         $res .= unpack("u", $len . $1 );
2417     }
2418     return $res;
2419 }
2420
2421 # ip_match(remoteip, localip, [match]+)
2422 # Checks an IP address against a list of IPs, networks and networks/masks
2423 sub ip_match
2424 {
2425 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2426 @io = split(/\./, $_[0]);
2427 for($i=2; $i<@_; $i++) {
2428         $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2429         }
2430 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2431         $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
2432         $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2433         $ip_match_cache{$_[0]} = $hn;
2434         }
2435 for($i=2; $i<@_; $i++) {
2436         local $mismatch = 0;
2437         if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2438                 # Convert CIDR to netmask format
2439                 $_[$i] = $1."/".&prefix_to_mask($2);
2440                 }
2441         if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2442                 # Compare with network/mask
2443                 @mo = split(/\./, $1); @ms = split(/\./, $2);
2444                 for($j=0; $j<4; $j++) {
2445                         if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2446                                 $mismatch = 1;
2447                                 }
2448                         }
2449                 }
2450         elsif ($_[$i] =~ /^\*(\S+)$/) {
2451                 # Compare with hostname regexp
2452                 $mismatch = 1 if ($hn !~ /$1$/);
2453                 }
2454         elsif ($_[$i] eq 'LOCAL') {
2455                 # Compare with local network
2456                 local @lo = split(/\./, $_[1]);
2457                 if ($lo[0] < 128) {
2458                         $mismatch = 1 if ($lo[0] != $io[0]);
2459                         }
2460                 elsif ($lo[0] < 192) {
2461                         $mismatch = 1 if ($lo[0] != $io[0] ||
2462                                           $lo[1] != $io[1]);
2463                         }
2464                 else {
2465                         $mismatch = 1 if ($lo[0] != $io[0] ||
2466                                           $lo[1] != $io[1] ||
2467                                           $lo[2] != $io[2]);
2468                         }
2469                 }
2470         elsif ($_[$i] !~ /^[0-9\.]+$/) {
2471                 # Compare with hostname
2472                 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2473                 }
2474         else {
2475                 # Compare with IP or network
2476                 @mo = split(/\./, $_[$i]);
2477                 while(@mo && !$mo[$#mo]) { pop(@mo); }
2478                 for($j=0; $j<@mo; $j++) {
2479                         if ($mo[$j] != $io[$j]) {
2480                                 $mismatch = 1;
2481                                 }
2482                         }
2483                 }
2484         return 1 if (!$mismatch);
2485         }
2486 return 0;
2487 }
2488
2489 # users_match(&uinfo, user, ...)
2490 # Returns 1 if a user is in a list of users and groups
2491 sub users_match
2492 {
2493 local $uinfo = shift(@_);
2494 local $u;
2495 local @ginfo = getgrgid($uinfo->[3]);
2496 foreach $u (@_) {
2497         if ($u =~ /^\@(\S+)$/) {
2498                 return 1 if (&is_group_member($uinfo, $1));
2499                 }
2500         elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2501                 return (!$1 || $uinfo[2] >= $1) &&
2502                        (!$2 || $uinfo[2] <= $2);
2503                 }
2504         else {
2505                 return 1 if ($u eq $uinfo->[0]);
2506                 }
2507         }
2508 return 0;
2509 }
2510
2511 # restart_miniserv()
2512 # Called when a SIGHUP is received to restart the web server. This is done
2513 # by exec()ing perl with the same command line as was originally used
2514 sub restart_miniserv
2515 {
2516 print STDERR "restarting miniserv\n";
2517 &log_error("Restarting");
2518 close(SOCK);
2519 &close_all_sockets();
2520 &close_all_pipes();
2521 dbmclose(%sessiondb);
2522 kill('KILL', $logclearer) if ($logclearer);
2523 kill('KILL', $extauth) if ($extauth);
2524 exec($perl_path, $miniserv_path, @miniserv_argv);
2525 die "Failed to restart miniserv with $perl_path $miniserv_path";
2526 }
2527
2528 sub trigger_restart
2529 {
2530 $need_restart = 1;
2531 }
2532
2533 sub trigger_reload
2534 {
2535 $need_reload = 1;
2536 }
2537
2538 sub to_ipaddress
2539 {
2540 local (@rv, $i);
2541 foreach $i (@_) {
2542         if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2543             $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/) { push(@rv, $i); }
2544         else { push(@rv, join('.', unpack("CCCC", inet_aton($i)))); }
2545         }
2546 return wantarray ? @rv : $rv[0];
2547 }
2548
2549 # read_line(no-wait, no-limit)
2550 # Reads one line from SOCK or SSL
2551 sub read_line
2552 {
2553 local ($nowait, $nolimit) = @_;
2554 local($idx, $more, $rv);
2555 while(($idx = index($main::read_buffer, "\n")) < 0) {
2556         if (length($main::read_buffer) > 10000 && !$nolimit) {
2557                 &http_error(414, "Request too long",
2558                     "Received excessive line <pre>$main::read_buffer</pre>");
2559                 }
2560
2561         # need to read more..
2562         &wait_for_data_error() if (!$nowait);
2563         if ($use_ssl) {
2564                 $more = Net::SSLeay::read($ssl_con);
2565                 }
2566         else {
2567                 local $ok = sysread(SOCK, $more, 1024);
2568                 $more = undef if ($ok <= 0);
2569                 }
2570         if ($more eq '') {
2571                 # end of the data
2572                 $rv = $main::read_buffer;
2573                 undef($main::read_buffer);
2574                 return $rv;
2575                 }
2576         $main::read_buffer .= $more;
2577         }
2578 $rv = substr($main::read_buffer, 0, $idx+1);
2579 $main::read_buffer = substr($main::read_buffer, $idx+1);
2580 return $rv;
2581 }
2582
2583 # read_data(length)
2584 # Reads up to some amount of data from SOCK or the SSL connection
2585 sub read_data
2586 {
2587 local ($rv);
2588 if (length($main::read_buffer)) {
2589         if (length($main::read_buffer) > $_[0]) {
2590                 # Return the first part of the buffer
2591                 $rv = substr($main::read_buffer, 0, $_[0]);
2592                 $main::read_buffer = substr($main::read_buffer, $_[0]);
2593                 return $rv;
2594                 }
2595         else {
2596                 # Return the whole buffer
2597                 $rv = $main::read_buffer;
2598                 undef($main::read_buffer);
2599                 return $rv;
2600                 }
2601         }
2602 elsif ($use_ssl) {
2603         # Call SSL read function
2604         return Net::SSLeay::read($ssl_con, $_[0]);
2605         }
2606 else {
2607         # Just do a normal read
2608         local $buf;
2609         sysread(SOCK, $buf, $_[0]) || return undef;
2610         return $buf;
2611         }
2612 }
2613
2614 # sysread_line(fh)
2615 # Read a line from a file handle, using sysread to get a byte at a time
2616 sub sysread_line
2617 {
2618 local ($fh) = @_;
2619 local $line;
2620 while(1) {
2621         local ($buf, $got);
2622         $got = sysread($fh, $buf, 1);
2623         last if ($got <= 0);
2624         $line .= $buf;
2625         last if ($buf eq "\n");
2626         }
2627 return $line;
2628 }
2629
2630 # wait_for_data(secs)
2631 # Waits at most the given amount of time for some data on SOCK, returning
2632 # 0 if not found, 1 if some arrived.
2633 sub wait_for_data
2634 {
2635 local $rmask;
2636 vec($rmask, fileno(SOCK), 1) = 1;
2637 local $got = select($rmask, undef, undef, $_[0]);
2638 return $got == 0 ? 0 : 1;
2639 }
2640
2641 # wait_for_data_error()
2642 # Waits 60 seconds for data on SOCK, and fails if none arrives
2643 sub wait_for_data_error
2644 {
2645 local $got = &wait_for_data(60);
2646 if (!$got) {
2647         &http_error(400, "Timeout",
2648                     "Waited more than 60 seconds for request data");
2649         }
2650 }
2651
2652 # write_data(data, ...)
2653 # Writes a string to SOCK or the SSL connection
2654 sub write_data
2655 {
2656 local $str = join("", @_);
2657 if ($use_ssl) {
2658         Net::SSLeay::write($ssl_con, $str);
2659         }
2660 else {
2661         syswrite(SOCK, $str, length($str));
2662         }
2663 # Intentionally introduce a small delay to avoid problems where IE reports
2664 # the page as empty / DNS failed when it get a large response too quickly!
2665 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2666 $write_data_count += length($str);
2667 }
2668
2669 # reset_byte_count()
2670 sub reset_byte_count { $write_data_count = 0; }
2671
2672 # byte_count()
2673 sub byte_count { return $write_data_count; }
2674
2675 # log_request(hostname, user, request, code, bytes)
2676 sub log_request
2677 {
2678 if ($config{'log'}) {
2679         local ($user, $ident, $headers);
2680         if ($config{'logident'}) {
2681                 # add support for rfc1413 identity checking here
2682                 }
2683         else { $ident = "-"; }
2684         $user = $_[1] ? $_[1] : "-";
2685         local $dstr = &make_datestr();
2686         if (fileno(MINISERVLOG)) {
2687                 seek(MINISERVLOG, 0, 2);
2688                 }
2689         else {
2690                 open(MINISERVLOG, ">>$config{'logfile'}");
2691                 chmod(0600, $config{'logfile'});
2692                 }
2693         if (defined($config{'logheaders'})) {
2694                 foreach $h (split(/\s+/, $config{'logheaders'})) {
2695                         $headers .= " $h=\"$header{$h}\"";
2696                         }
2697                 }
2698         elsif ($config{'logclf'}) {
2699                 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2700                 }
2701         else {
2702                 $headers = "";
2703                 }
2704         print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2705                           "$_[3] $_[4]$headers\n";
2706         close(MINISERVLOG);
2707         }
2708 }
2709
2710 # make_datestr()
2711 sub make_datestr
2712 {
2713 local @tm = localtime(time());
2714 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2715                 $tm[3], $month[$tm[4]], $tm[5]+1900,
2716                 $tm[2], $tm[1], $tm[0], $timezone;
2717 }
2718
2719 # log_error(message)
2720 sub log_error
2721 {
2722 seek(STDERR, 0, 2);
2723 print STDERR "[",&make_datestr(),"] ",
2724         $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2725         $page ? ( $page," : " ) : ( ),
2726         @_,"\n";
2727 }
2728
2729 # read_errors(handle)
2730 # Read and return all input from some filehandle
2731 sub read_errors
2732 {
2733 local($fh, $_, $rv);
2734 $fh = $_[0];
2735 while(<$fh>) { $rv .= $_; }
2736 return $rv;
2737 }
2738
2739 sub write_keep_alive
2740 {
2741 local $mode;
2742 if ($config{'nokeepalive'}) {
2743         # Keep alives have been disabled in config
2744         $mode = 0;
2745         }
2746 elsif (@childpids > $config{'maxconns'}*.8) {
2747         # Disable because nearing process limit
2748         $mode = 0;
2749         }
2750 elsif (@_) {
2751         # Keep alive specified by caller
2752         $mode = $_[0];
2753         }
2754 else {
2755         # Keep alive determined by browser
2756         $mode = $header{'connection'} =~ /keep-alive/i;
2757         }
2758 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2759 return $mode;
2760 }
2761
2762 sub term_handler
2763 {
2764 kill('TERM', @childpids) if (@childpids);
2765 kill('KILL', $logclearer) if ($logclearer);
2766 kill('KILL', $extauth) if ($extauth);
2767 exit(1);
2768 }
2769
2770 sub http_date
2771 {
2772 local @tm = gmtime($_[0]);
2773 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2774                 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2775                 $tm[2], $tm[1], $tm[0];
2776 }
2777
2778 sub TIEHANDLE
2779 {
2780 my $i; bless \$i, shift;
2781 }
2782  
2783 sub WRITE
2784 {
2785 $r = shift;
2786 my($buf,$len,$offset) = @_;
2787 &write_to_sock(substr($buf, $offset, $len));
2788 }
2789  
2790 sub PRINT
2791 {
2792 $r = shift;
2793 $$r++;
2794 my $buf = join(defined($,) ? $, : "", @_);
2795 $buf .= $\ if defined($\);
2796 &write_to_sock($buf);
2797 }
2798  
2799 sub PRINTF
2800 {
2801 shift;
2802 my $fmt = shift;
2803 &write_to_sock(sprintf $fmt, @_);
2804 }
2805  
2806 # Send back already read data while we have it, then read from SOCK
2807 sub READ
2808 {
2809 my $r = shift;
2810 my $bufref = \$_[0];
2811 my $len = $_[1];
2812 my $offset = $_[2];
2813 if ($postpos < length($postinput)) {
2814         # Reading from already fetched array
2815         my $left = length($postinput) - $postpos;
2816         my $canread = $len > $left ? $left : $len;
2817         substr($$bufref, $offset, $canread) =
2818                 substr($postinput, $postpos, $canread);
2819         $postpos += $canread;
2820         return $canread;
2821         }
2822 else {
2823         # Read from network socket
2824         local $data = &read_data($len);
2825         if ($data eq '' && $len) {
2826                 # End of socket
2827                 print STDERR "finished reading - shutting down socket\n";
2828                 shutdown(SOCK, 0);
2829                 }
2830         substr($$bufref, $offset, length($data)) = $data;
2831         return length($data);
2832         }
2833 }
2834
2835 sub OPEN
2836 {
2837 #print STDERR "open() called - should never happen!\n";
2838 }
2839  
2840 # Read a line of input
2841 sub READLINE
2842 {
2843 my $r = shift;
2844 if ($postpos < length($postinput) &&
2845     ($idx = index($postinput, "\n", $postpos)) >= 0) {
2846         # A line exists in the memory buffer .. use it
2847         my $line = substr($postinput, $postpos, $idx-$postpos+1);
2848         $postpos = $idx+1;
2849         return $line;
2850         }
2851 else {
2852         # Need to read from the socket
2853         my $line;
2854         if ($postpos < length($postinput)) {
2855                 # Start with in-memory data
2856                 $line = substr($postinput, $postpos);
2857                 $postpos = length($postinput);
2858                 }
2859         my $nl = &read_line(0, 1);
2860         if ($nl eq '') {
2861                 # End of socket
2862                 print STDERR "finished reading - shutting down socket\n";
2863                 shutdown(SOCK, 0);
2864                 }
2865         $line .= $nl if (defined($nl));
2866         return $line;
2867         }
2868 }
2869  
2870 # Read one character of input
2871 sub GETC
2872 {
2873 my $r = shift;
2874 my $buf;
2875 my $got = READ($r, \$buf, 1, 0);
2876 return $got > 0 ? $buf : undef;
2877 }
2878
2879 sub FILENO
2880 {
2881 return fileno(SOCK);
2882 }
2883  
2884 sub CLOSE { }
2885  
2886 sub DESTROY { }
2887
2888 # write_to_sock(data, ...)
2889 sub write_to_sock
2890 {
2891 local $d;
2892 foreach $d (@_) {
2893         if ($doneheaders || $miniserv::nph_script) {
2894                 &write_data($d);
2895                 }
2896         else {
2897                 $headers .= $d;
2898                 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
2899                         if ($1 =~ /^(\S+):\s+(.*)$/) {
2900                                 $cgiheader{lc($1)} = $2;
2901                                 push(@cgiheader, [ $1, $2 ]);
2902                                 }
2903                         elsif ($1 !~ /\S/) {
2904                                 $doneheaders++;
2905                                 }
2906                         else {
2907                                 &http_error(500, "Bad Header");
2908                                 }
2909                         }
2910                 if ($doneheaders) {
2911                         if ($cgiheader{"location"}) {
2912                                 &write_data(
2913                                         "HTTP/1.0 302 Moved Temporarily\r\n");
2914                                 &write_data("Date: $datestr\r\n");
2915                                 &write_data("Server: $config{server}\r\n");
2916                                 &write_keep_alive(0);
2917                                 }
2918                         elsif ($cgiheader{"content-type"} eq "") {
2919                                 &http_error(500, "Missing Content-Type Header");
2920                                 }
2921                         else {
2922                                 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2923                                 &write_data("Date: $datestr\r\n");
2924                                 &write_data("Server: $config{server}\r\n");
2925                                 &write_keep_alive(0);
2926                                 }
2927                         foreach $h (@cgiheader) {
2928                                 &write_data("$h->[0]: $h->[1]\r\n");
2929                                 }
2930                         &write_data("\r\n");
2931                         &reset_byte_count();
2932                         &write_data($headers);
2933                         }
2934                 }
2935         }
2936 }
2937
2938 sub verify_client
2939 {
2940 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
2941 if ($cert) {
2942         local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
2943         $verified_client = 1 if (!$errnum);
2944         }
2945 return 1;
2946 }
2947
2948 sub END
2949 {
2950 if ($doing_eval && $$ == $main_process_id) {
2951         # A CGI program called exit! This is a horrible hack to 
2952         # finish up before really exiting
2953         shutdown(SOCK, 1);
2954         close(SOCK);
2955         close($PASSINw); close($PASSOUTw);
2956         &log_request($acpthost, $authuser, $reqline,
2957                      $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2958         }
2959 }
2960
2961 # urlize
2962 # Convert a string to a form ok for putting in a URL
2963 sub urlize {
2964   local($tmp, $tmp2, $c);
2965   $tmp = $_[0];
2966   $tmp2 = "";
2967   while(($c = chop($tmp)) ne "") {
2968         if ($c !~ /[A-z0-9]/) {
2969                 $c = sprintf("%%%2.2X", ord($c));
2970                 }
2971         $tmp2 = $c . $tmp2;
2972         }
2973   return $tmp2;
2974 }
2975
2976 # validate_user(username, password, host)
2977 # Checks if some username and password are valid. Returns the modified username,
2978 # the expired / temp pass flag, and the non-existence flag
2979 sub validate_user
2980 {
2981 local ($user, $pass, $host) = @_;
2982 return ( ) if (!$user);
2983 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
2984 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
2985         &can_user_login($user, undef, $host);
2986 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
2987 if ($notexist) {
2988         # User doesn't even exist, so go no further
2989         return ( undef, 0, 1 );
2990         }
2991 elsif ($canmode == 0) {
2992         # User does exist but cannot login
2993         return ( $canuser, 0, 0 );
2994         }
2995 elsif ($canmode == 1) {
2996         # Attempt Webmin authentication
2997         if ($users{$webminuser} eq
2998             &password_crypt($pass, $users{$webminuser})) {
2999                 # Password is valid .. but check for expiry
3000                 local $lc = $lastchanges{$user};
3001                 if ($config{'pass_maxdays'} && $lc && !$nochange{$user}) {
3002                         local $daysold = (time() - $lc)/(24*60*60);
3003                         print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$temppass{$user}\n";
3004                         if ($config{'pass_lockdays'} &&
3005                             $daysold > $config{'pass_lockdays'}) {
3006                                 # So old that the account is locked
3007                                 return ( undef, 0, 0 );
3008                                 }
3009                         elsif ($daysold > $config{'pass_maxdays'}) {
3010                                 # Password has expired
3011                                 return ( $user, 1, 0 );
3012                                 }
3013                         }
3014                 if ($temppass{$user}) {
3015                         # Temporary password - force change now
3016                         return ( $user, 2, 0 );
3017                         }
3018                 return ( $user, 0, 0 );
3019                 }
3020         else {
3021                 return ( undef, 0, 0 );
3022                 }
3023         }
3024 elsif ($canmode == 2 || $canmode == 3) {
3025         # Attempt PAM or passwd file authentication
3026         local $val = &validate_unix_user($canuser, $pass);
3027         print DEBUG "validate_user: unix val=$val\n";
3028         if ($val && $sudo) {
3029                 # Need to check if this Unix user can sudo
3030                 if (!&check_sudo_permissions($canuser, $pass)) {
3031                         print DEBUG "validate_user: sudo failed\n";
3032                         $val = 0;
3033                         }
3034                 else {
3035                         print DEBUG "validate_user: sudo passed\n";
3036                         }
3037                 }
3038         return $val == 2 ? ( $canuser, 1, 0 ) :
3039                $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3040         }
3041 elsif ($canmode == 4) {
3042         # Attempt external authentication
3043         return &validate_external_user($canuser, $pass) ?
3044                 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3045         }
3046 else {
3047         # Can't happen!
3048         return ( );
3049         }
3050 }
3051
3052 # validate_unix_user(user, password)
3053 # Returns 1 if a username and password are valid under unix, 0 if not,
3054 # or 2 if the account has expired.
3055 # Checks PAM if available, and falls back to reading the system password
3056 # file otherwise.
3057 sub validate_unix_user
3058 {
3059 if ($use_pam) {
3060         # Check with PAM
3061         $pam_username = $_[0];
3062         $pam_password = $_[1];
3063         local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3064                                       \&pam_conv_func);
3065         if (ref($pamh)) {
3066                 local $pam_ret = $pamh->pam_authenticate();
3067                 if ($pam_ret == PAM_SUCCESS()) {
3068                         # Logged in OK .. make sure password hasn't expired
3069                         local $acct_ret = $pamh->pam_acct_mgmt();
3070                         if ($acct_ret == PAM_SUCCESS()) {
3071                                 $pamh->pam_open_session();
3072                                 return 1;
3073                                 }
3074                         elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3075                                $acct_ret == PAM_ACCT_EXPIRED()) {
3076                                 return 2;
3077                                 }
3078                         else {
3079                                 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3080                                 return 0;
3081                                 }
3082                         }
3083                 return 0;
3084                 }
3085         }
3086 elsif ($config{'pam_only'}) {
3087         # Pam is not available, but configuration forces it's use!
3088         return 0;
3089         }
3090 elsif ($config{'passwd_file'}) {
3091         # Check in a password file
3092         local $rv = 0;
3093         open(FILE, $config{'passwd_file'});
3094         if ($config{'passwd_file'} eq '/etc/security/passwd') {
3095                 # Assume in AIX format
3096                 while(<FILE>) {
3097                         s/\s*$//;
3098                         if (/^\s*(\S+):/ && $1 eq $_[0]) {
3099                                 $_ = <FILE>;
3100                                 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3101                                         $rv = $1 eq &password_crypt($_[1], $1) ?
3102                                                 1 : 0;
3103                                         }
3104                                 last;
3105                                 }
3106                         }
3107                 }
3108         else {
3109                 # Read the system password or shadow file
3110                 while(<FILE>) {
3111                         local @l = split(/:/, $_, -1);
3112                         local $u = $l[$config{'passwd_uindex'}];
3113                         local $p = $l[$config{'passwd_pindex'}];
3114                         if ($u eq $_[0]) {
3115                                 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3116                                 if ($config{'passwd_cindex'} ne '' && $rv) {
3117                                         # Password may have expired!
3118                                         local $c = $l[$config{'passwd_cindex'}];
3119                                         local $m = $l[$config{'passwd_mindex'}];
3120                                         local $day = time()/(24*60*60);
3121                                         if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3122                                             $day - $c > $m) {
3123                                                 # Yep, it has ..
3124                                                 $rv = 2;
3125                                                 }
3126                                         }
3127                                 if ($p eq "" && $config{'passwd_blank'}) {
3128                                         # Force password change
3129                                         $rv = 2;
3130                                         }
3131                                 last;
3132                                 }
3133                         }
3134                 }
3135         close(FILE);
3136         return $rv if ($rv);
3137         }
3138
3139 # Fallback option - check password returned by getpw*
3140 local @uinfo = getpwnam($_[0]);
3141 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3142         return 1;
3143         }
3144
3145 return 0;       # Totally failed
3146 }
3147
3148 # validate_external_user(user, pass)
3149 # Validate a user by passing the username and password to an external
3150 # squid-style authentication program
3151 sub validate_external_user
3152 {
3153 return 0 if (!$config{'extauth'});
3154 flock(EXTAUTH, 2);
3155 local $str = "$_[0] $_[1]\n";
3156 syswrite(EXTAUTH, $str, length($str));
3157 local $resp = <EXTAUTH>;
3158 flock(EXTAUTH, 8);
3159 return $resp =~ /^OK/i ? 1 : 0;
3160 }
3161
3162 # can_user_login(username, no-append, host)
3163 # Checks if a user can login or not.
3164 # First return value is the username.
3165 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3166 # file, 4 if external.
3167 # Third is 1 if the user does not exist at all, 0 if he does.
3168 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3169 # Fifth is a flag indicating if a sudo check is needed.
3170 sub can_user_login
3171 {
3172 if (!$users{$_[0]}) {
3173         # See if this user exists in Unix and can be validated by the same
3174         # method as the unixauth webmin user
3175         local $realuser = $unixauth{$_[0]};
3176         local @uinfo;
3177         local $sudo = 0;
3178         local $pamany = 0;
3179         eval { @uinfo = getpwnam($_[0]); };     # may fail on windows
3180         if (!$realuser && @uinfo) {
3181                 # No unixauth entry for the username .. try his groups 
3182                 foreach my $ua (keys %unixauth) {
3183                         if ($ua =~ /^\@(.*)$/) {
3184                                 if (&is_group_member(\@uinfo, $1)) {
3185                                         $realuser = $unixauth{$ua};
3186                                         last;
3187                                         }
3188                                 }
3189                         }
3190                 }
3191         if (!$realuser && @uinfo) {
3192                 # Fall back to unix auth for all Unix users
3193                 $realuser = $unixauth{"*"};
3194                 }
3195         if (!$realuser && $use_sudo && @uinfo) {
3196                 # Allow login effectively as root, if sudo permits it
3197                 $sudo = 1;
3198                 $realuser = "root";
3199                 }
3200         if (!$realuser && !@uinfo && $config{'pamany'}) {
3201                 # If the user completely doesn't exist, we can still allow
3202                 # him to authenticate via PAM
3203                 $realuser = $config{'pamany'};
3204                 $pamany = 1;
3205                 }
3206         if (!$realuser) {
3207                 # For Usermin, always fall back to unix auth for any user,
3208                 # so that later checks with domain added / removed are done.
3209                 $realuser = $unixauth{"*"};
3210                 }
3211         return (undef, 0, 1, undef) if (!$realuser);
3212         local $up = $users{$realuser};
3213         return (undef, 0, 1, undef) if (!defined($up));
3214
3215         # Work out possible domain names from the hostname
3216         local @doms = ( $_[2] );
3217         if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3218                 push(@doms, $2);
3219                 }
3220
3221         if ($config{'user_mapping'} && !defined(%user_mapping)) {
3222                 # Read the user mapping file
3223                 %user_mapping = ();
3224                 open(MAPPING, $config{'user_mapping'});
3225                 while(<MAPPING>) {
3226                         s/\r|\n//g;
3227                         s/#.*$//;
3228                         if (/^(\S+)\s+(\S+)/) {
3229                                 if ($config{'user_mapping_reverse'}) {
3230                                         $user_mapping{$1} = $2;
3231                                         }
3232                                 else {
3233                                         $user_mapping{$2} = $1;
3234                                         }
3235                                 }
3236                         }
3237                 close(MAPPING);
3238                 }
3239
3240         # Check the user mapping file to see if there is an entry for the
3241         # user login in which specifies a new effective user
3242         local $um;
3243         foreach my $d (@doms) {
3244                 $um ||= $user_mapping{"$_[0]\@$d"};
3245                 }
3246         $um ||= $user_mapping{$_[0]};
3247         if (defined($um) && ($_[1]&4) == 0) {
3248                 # A mapping exists - use it!
3249                 return &can_user_login($um, $_[1]+4, $_[2]);
3250                 }
3251
3252         # Check if a user with the entered login and the domains appended
3253         # or prepended exists, and if so take it to be the effective user
3254         if (!@uinfo && $config{'domainuser'}) {
3255                 # Try again with name.domain and name.firstpart
3256                 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3257                 if (($_[1]&1) == 0) {
3258                         local ($a, $p);
3259                         foreach $a (@firsts, @doms) {
3260                                 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3261                                             "${a}.$_[0]", "${a}-$_[0]",
3262                                             "$_[0]_${a}", "${a}_$_[0]") {
3263                                         local @vu = &can_user_login(
3264                                                         $p, $_[1]+1, $_[2]);
3265                                         return @vu if ($vu[1]);
3266                                         }
3267                                 }
3268                         }
3269                 }
3270
3271         # Check if the user entered a domain at the end of his username when
3272         # he really shouldn't have, and if so try without it
3273         if (!@uinfo && $config{'domainstrip'} &&
3274             $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3275                 local ($stripped, $dom) = ($1, $2);
3276                 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3277                 return @vu if ($vu[1]);
3278                 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3279                 return @vu if ($vu[1]);
3280                 }
3281
3282         return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3283
3284         if (@uinfo) {
3285                 if (defined(@allowusers)) {
3286                         # Only allow people on the allow list
3287                         return ( undef, 0, 0, undef )
3288                                 if (!&users_match(\@uinfo, @allowusers));
3289                         }
3290                 elsif (defined(@denyusers)) {
3291                         # Disallow people on the deny list
3292                         return ( undef, 0, 0, undef )
3293                                 if (&users_match(\@uinfo, @denyusers));
3294                         }
3295                 if ($config{'shells_deny'}) {
3296                         local $found = 0;
3297                         open(SHELLS, $config{'shells_deny'});
3298                         while(<SHELLS>) {
3299                                 s/\r|\n//g;
3300                                 s/#.*$//;
3301                                 $found++ if ($_ eq $uinfo[8]);
3302                                 }
3303                         close(SHELLS);
3304                         return ( undef, 0, 0, undef ) if (!$found);
3305                         }
3306                 }
3307
3308         if ($up eq 'x') {
3309                 # PAM or passwd file authentication
3310                 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3311                 }
3312         elsif ($up eq 'e') {
3313                 # External authentication
3314                 return ( $_[0], 4, 0, $realuser, $sudo );
3315                 }
3316         else {
3317                 # Fixed Webmin password
3318                 return ( $_[0], 1, 0, $realuser, $sudo );
3319                 }
3320         }
3321 elsif ($users{$_[0]} eq 'x') {
3322         # Webmin user authenticated via PAM or password file
3323         return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3324         }
3325 elsif ($users{$_[0]} eq 'e') {
3326         # Webmin user authenticated externally
3327         return ( $_[0], 4, 0, $_[0] );
3328         }
3329 else {
3330         # Normal Webmin user
3331         return ( $_[0], 1, 0, $_[0] );
3332         }
3333 }
3334
3335 # the PAM conversation function for interactive logins
3336 sub pam_conv_func
3337 {
3338 $pam_conv_func_called++;
3339 my @res;
3340 while ( @_ ) {
3341         my $code = shift;
3342         my $msg = shift;
3343         my $ans = "";
3344
3345         $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3346         $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3347
3348         push @res, PAM_SUCCESS();
3349         push @res, $ans;
3350         }
3351 push @res, PAM_SUCCESS();
3352 return @res;
3353 }
3354
3355 sub urandom_timeout
3356 {
3357 close(RANDOM);
3358 }
3359
3360 # get_socket_name(handle)
3361 # Returns the local hostname or IP address of some connection
3362 sub get_socket_name
3363 {
3364 return $config{'host'} if ($config{'host'});
3365 local $sn = getsockname($_[0]);
3366 return undef if (!$sn);
3367 local $myaddr = (unpack_sockaddr_in($sn))[1];
3368 if (!$get_socket_name_cache{$myaddr}) {
3369         local $myname;
3370         if (!$config{'no_resolv_myname'}) {
3371                 $myname = gethostbyaddr($myaddr, AF_INET);
3372                 }
3373         if ($myname eq "") {
3374                 $myname = inet_ntoa($myaddr);
3375                 }
3376         $get_socket_name_cache{$myaddr} = $myname;
3377         }
3378 return $get_socket_name_cache{$myaddr};
3379 }
3380
3381 # run_login_script(username, sid, remoteip, localip)
3382 sub run_login_script
3383 {
3384 if ($config{'login_script'}) {
3385         system($config{'login_script'}.
3386                " ".join(" ", map { quotemeta($_) } @_).
3387                " >/dev/null 2>&1 </dev/null");
3388         }
3389 }
3390
3391 # run_logout_script(username, sid, remoteip, localip)
3392 sub run_logout_script
3393 {
3394 if ($config{'logout_script'}) {
3395         system($config{'logout_script'}.
3396                " ".join(" ", map { quotemeta($_) } @_).
3397                " >/dev/null 2>&1 </dev/null");
3398         }
3399 }
3400
3401 # close_all_sockets()
3402 # Closes all the main listening sockets
3403 sub close_all_sockets
3404 {
3405 local $s;
3406 foreach $s (@socketfhs) {
3407         close($s);
3408         }
3409 }
3410
3411 # close_all_pipes()
3412 # Close all pipes for talking to sub-processes
3413 sub close_all_pipes
3414 {
3415 local $p;
3416 foreach $p (@passin) { close($p); }
3417 foreach $p (@passout) { close($p); }
3418 foreach $p (values %conversations) {
3419         if ($p->{'PAMOUTr'}) {
3420                 close($p->{'PAMOUTr'});
3421                 close($p->{'PAMINw'});
3422                 }
3423         }
3424 }
3425
3426 # check_user_ip(user)
3427 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3428 sub check_user_ip
3429 {
3430 if ($deny{$_[0]} &&
3431     &ip_match($acptip, $localip, @{$deny{$_[0]}}) ||
3432     $allow{$_[0]} &&
3433     !&ip_match($acptip, $localip, @{$allow{$_[0]}})) {
3434         return 0;
3435         }
3436 return 1;
3437 }
3438
3439 # check_user_time(user)
3440 # Returns 1 if some user is allowed to login at the current date and time
3441 sub check_user_time
3442 {
3443 return 1 if (!$allowdays{$_[0]} && !$allowhours{$_[0]});
3444 local @tm = localtime(time());
3445 if ($allowdays{$_[0]}) {
3446         # Make sure day is allowed
3447         return 0 if (&indexof($tm[6], @{$allowdays{$_[0]}}) < 0);
3448         }
3449 if ($allowhours{$_[0]}) {
3450         # Make sure time is allowed
3451         local $m = $tm[2]*60+$tm[1];
3452         return 0 if ($m < $allowhours{$_[0]}->[0] ||
3453                      $m > $allowhours{$_[0]}->[1]);
3454         }
3455 return 1;
3456 }
3457
3458 # generate_random_id(password, [force-urandom])
3459 # Returns a random session ID number
3460 sub generate_random_id
3461 {
3462 local ($pass, $force_urandom) = @_;
3463 local $sid;
3464 if (!$bad_urandom) {
3465         # First try /dev/urandom, unless we have marked it as bad
3466         $SIG{ALRM} = "miniserv::urandom_timeout";
3467         alarm(5);
3468         if (open(RANDOM, "/dev/urandom")) {
3469                 my $tmpsid;
3470                 if (read(RANDOM, $tmpsid, 16) == 16) {
3471                         $sid = lc(unpack('h*',$tmpsid));
3472                         }
3473                 close(RANDOM);
3474                 }
3475         alarm(0);
3476         }
3477 if (!$sid && !$force_urandom) {
3478         $sid = time();
3479         local $mul = 1;
3480         foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3481                 $sid += ord($c) * $mul;
3482                 $mul *= 3;
3483                 }
3484         }
3485 return $sid;
3486 }
3487
3488 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3489 # Called from handle_session to either mark a user as logged in, or not
3490 sub handle_login
3491 {
3492 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3493 $authuser = $vu if ($ok);
3494
3495 # check if the test cookie is set
3496 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3497     !$config{'no_testing_cookie'} && !$notest) {
3498         &http_error(500, "No cookies",
3499            "Your browser does not support cookies, ".
3500            "which are required for this web server to ".
3501            "work in session authentication mode");
3502         }
3503
3504 # check with main process for delay
3505 if ($config{'passdelay'} && $vu) {
3506         print $PASSINw "delay $vu $acptip $ok\n";
3507         <$PASSOUTr> =~ /(\d+) (\d+)/;
3508         $blocked = $2;
3509         sleep($1);
3510         }
3511
3512 if ($ok && (!$expired ||
3513             $config{'passwd_mode'} == 1)) {
3514         # Logged in OK! Tell the main process about
3515         # the new SID
3516         local $sid = &generate_random_id($pass);
3517         print $PASSINw "new $sid $authuser $acptip\n";
3518
3519         # Run the post-login script, if any
3520         &run_login_script($authuser, $sid,
3521                           $acptip, $localip);
3522
3523         # Check for a redirect URL for the user
3524         local $rurl = &login_redirect($authuser, $pass, $host);
3525         if ($rurl) {
3526                 # Got one .. go to it
3527                 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3528                 &write_data("Date: $datestr\r\n");
3529                 &write_data("Server: $config{'server'}\r\n");
3530                 &write_data("Location: $rurl\r\n");
3531                 &write_keep_alive(0);
3532                 &write_data("\r\n");
3533                 &log_request($acpthost, $authuser, $reqline, 302, 0);
3534                 }
3535         else {
3536                 # Set cookie and redirect to originally requested page
3537                 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3538                 &write_data("Date: $datestr\r\n");
3539                 &write_data("Server: $config{'server'}\r\n");
3540                 local $ssl = $use_ssl || $config{'inetd_ssl'};
3541                 $portstr = $port == 80 && !$ssl ? "" :
3542                            $port == 443 && $ssl ? "" : ":$port";
3543                 $prot = $ssl ? "https" : "http";
3544                 local $sec = $ssl ? "; secure" : "";
3545                 #$sec .= "; httpOnly";
3546                 if ($in{'save'}) {
3547                         &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3548                         }
3549                 else {
3550                         &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3551                         }
3552                 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3553                 &write_keep_alive(0);
3554                 &write_data("\r\n");
3555                 &log_request($acpthost, $authuser, $reqline, 302, 0);
3556                 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3557                 &write_login_utmp($authuser, $acpthost);
3558                 }
3559         return 0;
3560         }
3561 elsif ($ok && $expired &&
3562        ($config{'passwd_mode'} == 2 || $expired == 2)) {
3563         # Login was ok, but password has expired or was temporary. Need
3564         # to force display of password change form.
3565         $validated = 1;
3566         $authuser = undef;
3567         $querystring = "&user=".&urlize($vu).
3568                        "&pam=".$use_pam.
3569                        "&expired=".$expired;
3570         $method = "GET";
3571         $queryargs = "";
3572         $page = $config{'password_form'};
3573         $logged_code = 401;
3574         $miniserv_internal = 2;
3575         syslog("crit", "%s",
3576                 "Expired login as $vu ".
3577                 "from $acpthost") if ($use_syslog);
3578         }
3579 else {
3580         # Login failed, or password has expired. The login form will be
3581         # displayed again by later code
3582         $failed_user = $vu;
3583         $request_uri = $in{'page'};
3584         $already_session_id = undef;
3585         $method = "GET";
3586         $authuser = $baseauthuser = undef;
3587         syslog("crit", "%s",
3588                 ($nonexist ? "Non-existent" :
3589                  $expired ? "Expired" : "Invalid").
3590                 " login as $vu from $acpthost")
3591                 if ($use_syslog);
3592         }
3593 return undef;
3594 }
3595
3596 # write_login_utmp(user, host)
3597 # Record the login by some user in utmp
3598 sub write_login_utmp
3599 {
3600 if ($write_utmp) {
3601         # Write utmp record for login
3602         %utmp = ( 'ut_host' => $_[1],
3603                   'ut_time' => time(),
3604                   'ut_user' => $_[0],
3605                   'ut_type' => 7,       # user process
3606                   'ut_pid' => $main_process_id,
3607                   'ut_line' => $config{'pam'},
3608                   'ut_id' => '' );
3609         if (defined(&User::Utmp::putut)) {
3610                 User::Utmp::putut(\%utmp);
3611                 }
3612         else {
3613                 User::Utmp::pututline(\%utmp);
3614                 }
3615         }
3616 }
3617
3618 # write_logout_utmp(user, host)
3619 # Record the logout by some user in utmp
3620 sub write_logout_utmp
3621 {
3622 if ($write_utmp) {
3623         # Write utmp record for logout
3624         %utmp = ( 'ut_host' => $_[1],
3625                   'ut_time' => time(),
3626                   'ut_user' => $_[0],
3627                   'ut_type' => 8,       # dead process
3628                   'ut_pid' => $main_process_id,
3629                   'ut_line' => $config{'pam'},
3630                   'ut_id' => '' );
3631         if (defined(&User::Utmp::putut)) {
3632                 User::Utmp::putut(\%utmp);
3633                 }
3634         else {
3635                 User::Utmp::pututline(\%utmp);
3636                 }
3637         }
3638 }
3639
3640 # pam_conversation_process(username, write-pipe, read-pipe)
3641 # This function is called inside a sub-process to communicate with PAM. It sends
3642 # questions down one pipe, and reads responses from another
3643 sub pam_conversation_process
3644 {
3645 local ($user, $writer, $reader) = @_;
3646 $miniserv::pam_conversation_process_writer = $writer;
3647 $miniserv::pam_conversation_process_reader = $reader;
3648 local $convh = new Authen::PAM(
3649         $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3650 local $pam_ret = $convh->pam_authenticate();
3651 if ($pam_ret == PAM_SUCCESS()) {
3652         local $acct_ret = $convh->pam_acct_mgmt();
3653         if ($acct_ret == PAM_SUCCESS()) {
3654                 $convh->pam_open_session();
3655                 print $writer "x2 $user 1 0 0\n";
3656                 }
3657         elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3658                $acct_ret == PAM_ACCT_EXPIRED()) {
3659                 print $writer "x2 $user 1 1 0\n";
3660                 }
3661         else {
3662                 print $writer "x0 Unknown PAM account status $acct_ret\n";
3663                 }
3664         }
3665 else {
3666         print $writer "x2 $user 0 0 0\n";
3667         }
3668 exit(0);
3669 }
3670
3671 # pam_conversation_process_func(type, message, [type, message, ...])
3672 # A pipe that talks to both PAM and the master process
3673 sub pam_conversation_process_func
3674 {
3675 local @rv;
3676 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3677 while(@_) {
3678         local ($type, $msg) = (shift, shift);
3679         $msg =~ s/\r|\n//g;
3680         local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3681         print $miniserv::pam_conversation_process_writer "\n";
3682         local $answer = <$miniserv::pam_conversation_process_reader>;
3683         $answer =~ s/\r|\n//g;
3684         push(@rv, PAM_SUCCESS(), $answer);
3685         }
3686 push(@rv, PAM_SUCCESS());
3687 return @rv;
3688 }
3689
3690 # allocate_pipes()
3691 # Returns 4 new pipe file handles
3692 sub allocate_pipes
3693 {
3694 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3695 local $p;
3696 local %taken = ( (map { $_, 1 } @passin),
3697                  (map { $_->{'PASSINr'} } values %conversations) );
3698 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3699 $PASSINr = "PASSINr$p";
3700 $PASSINw = "PASSINw$p";
3701 $PASSOUTr = "PASSOUTr$p";
3702 $PASSOUTw = "PASSOUTw$p";
3703 pipe($PASSINr, $PASSINw);
3704 pipe($PASSOUTr, $PASSOUTw);
3705 select($PASSINw); $| = 1;
3706 select($PASSINr); $| = 1;
3707 select($PASSOUTw); $| = 1;
3708 select($PASSOUTw); $| = 1;
3709 select(STDOUT);
3710 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3711 }
3712
3713 # recv_pam_question(&conv, fd)
3714 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3715 # Returns 0 if the conversation is over, 1 if not.
3716 sub recv_pam_question
3717 {
3718 local ($conf, $fh) = @_;
3719 local $pr = $conf->{'PAMOUTr'};
3720 select($pr); $| = 1; select(STDOUT);
3721 local $line = <$pr>;
3722 $line =~ s/\r|\n//g;
3723 if (!$line) {
3724         $line = <$pr>;
3725         $line =~ s/\r|\n//g;
3726         }
3727 $conf->{'last'} = time();
3728 if (!$line) {
3729         # Failed!
3730         print $fh "0 PAM conversation error\n";
3731         return 0;
3732         }
3733 else {
3734         local ($type, $msg) = split(/\s+/, $line, 2);
3735         if ($type =~ /^x(\d+)/) {
3736                 # Pass this status code through
3737                 print $fh "$1 $msg\n";
3738                 return $1 == 2 || $1 == 0 ? 0 : 1;
3739                 }
3740         elsif ($type == PAM_PROMPT_ECHO_ON()) {
3741                 # A normal question
3742                 print $fh "1 $msg\n";
3743                 return 1;
3744                 }
3745         elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3746                 # A password
3747                 print $fh "3 $msg\n";
3748                 return 1;
3749                 }
3750         elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3751                 # A message that does not require a response
3752                 print $fh "4 $msg\n";
3753                 return 1;
3754                 }
3755         else {
3756                 # Unknown type!
3757                 print $fh "0 Unknown PAM message type $type\n";
3758                 return 0;
3759                 }
3760         }
3761 }
3762
3763 # send_pam_answer(&conv, answer)
3764 # Sends a response from the user to the PAM sub-process
3765 sub send_pam_answer
3766 {
3767 local ($conf, $answer) = @_;
3768 local $pw = $conf->{'PAMINw'};
3769 $conf->{'last'} = time();
3770 print $pw "$answer\n";
3771 }
3772
3773 # end_pam_conversation(&conv)
3774 # Clean up PAM conversation pipes and processes
3775 sub end_pam_conversation
3776 {
3777 local ($conv) = @_;
3778 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
3779 if ($conv->{'PAMINr'}) {
3780         close($conv->{'PAMINr'});
3781         close($conv->{'PAMOUTr'});
3782         close($conv->{'PAMINw'});
3783         close($conv->{'PAMOUTw'});
3784         }
3785 delete($conversations{$conv->{'cid'}});
3786 }
3787
3788 # get_ipkeys(&miniserv)
3789 # Returns a list of IP address to key file mappings from a miniserv.conf entry
3790 sub get_ipkeys
3791 {
3792 local (@rv, $k);
3793 foreach $k (keys %{$_[0]}) {
3794         if ($k =~ /^ipkey_(\S+)/) {
3795                 local $ipkey = { 'ips' => [ split(/,/, $1) ],
3796                                  'key' => $_[0]->{$k},
3797                                  'index' => scalar(@rv) };
3798                 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
3799                 push(@rv, $ipkey);
3800                 }
3801         }
3802 return @rv;
3803 }
3804
3805 # create_ssl_context(keyfile, [certfile])
3806 sub create_ssl_context
3807 {
3808 local ($keyfile, $certfile) = @_;
3809 local $ssl_ctx;
3810 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
3811 $ssl_ctx ||= Net::SSLeay::CTX_new();
3812 $ssl_ctx || die "Failed to create SSL context : $!";
3813 if ($client_certs) {
3814         Net::SSLeay::CTX_load_verify_locations(
3815                 $ssl_ctx, $config{'ca'}, "");
3816         Net::SSLeay::CTX_set_verify(
3817                 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
3818         }
3819 if ($config{'extracas'}) {
3820         local $p;
3821         foreach $p (split(/\s+/, $config{'extracas'})) {
3822                 Net::SSLeay::CTX_load_verify_locations(
3823                         $ssl_ctx, $p, "");
3824                 }
3825         }
3826
3827 Net::SSLeay::CTX_use_RSAPrivateKey_file(
3828         $ssl_ctx, $keyfile,
3829         &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
3830 Net::SSLeay::CTX_use_certificate_file(
3831         $ssl_ctx, $certfile || $keyfile,
3832         &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
3833
3834 return $ssl_ctx;
3835 }
3836
3837 # ssl_connection_for_ip(socket)
3838 # Returns a new SSL connection object for some socket, or undef if failed
3839 sub ssl_connection_for_ip
3840 {
3841 local ($sock) = @_;
3842 local $sn = getsockname($sock);
3843 if (!$sn) {
3844         print STDERR "Failed to get address for socket $sock\n";
3845         return undef;
3846         }
3847 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
3848 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
3849 local $ssl_con = Net::SSLeay::new($ssl_ctx);
3850 if ($config{'ssl_cipher_list'}) {
3851         # Force use of ciphers
3852         eval "Net::SSLeay::set_cipher_list(
3853                         \$ssl_con, \$config{'ssl_cipher_list'})";
3854         if ($@) {
3855                 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
3856                              "$@\n";
3857                 }
3858         else {
3859                 }
3860         }
3861 Net::SSLeay::set_fd($ssl_con, fileno($sock));
3862 if (!Net::SSLeay::accept($ssl_con)) {
3863         print STDERR "Failed to initialize SSL connection\n";
3864         return undef;
3865         }
3866 return $ssl_con;
3867 }
3868
3869 # login_redirect(username, password, host)
3870 # Calls the login redirect script (if configured), which may output a URL to
3871 # re-direct a user to after logging in.
3872 sub login_redirect
3873 {
3874 return undef if (!$config{'login_redirect'});
3875 local $quser = quotemeta($_[0]);
3876 local $qpass = quotemeta($_[1]);
3877 local $qhost = quotemeta($_[2]);
3878 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
3879 chop($url);
3880 return $url;
3881 }
3882
3883 # reload_config_file()
3884 # Re-read %config, and call post-config actions
3885 sub reload_config_file
3886 {
3887 &log_error("Reloading configuration");
3888 %config = &read_config_file($config_file);
3889 &update_vital_config();
3890 &read_users_file();
3891 &read_mime_types();
3892 &build_config_mappings();
3893 if ($config{'session'}) {
3894         dbmclose(%sessiondb);
3895         dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
3896         }
3897 }
3898
3899 # read_config_file(file)
3900 # Reads the given config file, and returns a hash of values
3901 sub read_config_file
3902 {
3903 local %rv;
3904 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
3905 while(<CONF>) {
3906         s/\r|\n//g;
3907         if (/^#/ || !/\S/) { next; }
3908         /^([^=]+)=(.*)$/;
3909         $name = $1; $val = $2;
3910         $name =~ s/^\s+//g; $name =~ s/\s+$//g;
3911         $val =~ s/^\s+//g; $val =~ s/\s+$//g;
3912         $rv{$name} = $val;
3913         }
3914 close(CONF);
3915 return %rv;
3916 }
3917
3918 # update_vital_config()
3919 # Updates %config with defaults, and dies if something vital is missing
3920 sub update_vital_config
3921 {
3922 my %vital = ("port", 80,
3923           "root", "./",
3924           "server", "MiniServ/0.01",
3925           "index_docs", "index.html index.htm index.cgi index.php",
3926           "addtype_html", "text/html",
3927           "addtype_txt", "text/plain",
3928           "addtype_gif", "image/gif",
3929           "addtype_jpg", "image/jpeg",
3930           "addtype_jpeg", "image/jpeg",
3931           "realm", "MiniServ",
3932           "session_login", "/session_login.cgi",
3933           "pam_login", "/pam_login.cgi",
3934           "password_form", "/password_form.cgi",
3935           "password_change", "/password_change.cgi",
3936           "maxconns", 50,
3937           "pam", "webmin",
3938           "sidname", "sid",
3939           "unauth", "^/unauthenticated/ ^[A-Za-z0-9\\-/]+\\.jar\$ ^[A-Za-z0-9\\-/]+\\.class\$ ^[A-Za-z0-9\\-/]+\\.gif\$ ^[A-Za-z0-9\\-/]+\\.conf\$ ^[A-Za-z0-9\\-/]+\\.ico\$",
3940           "max_post", 10000,
3941           "expires", 7*24*60*60,
3942          );
3943 foreach my $v (keys %vital) {
3944         if (!$config{$v}) {
3945                 if ($vital{$v} eq "") {
3946                         die "Missing config option $v";
3947                         }
3948                 $config{$v} = $vital{$v};
3949                 }
3950         }
3951 if (!$config{'sessiondb'}) {
3952         $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3953         $config{'sessiondb'} = "$1/sessiondb";
3954         }
3955 if (!$config{'errorlog'}) {
3956         $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
3957         $config{'errorlog'} = "$1/miniserv.error";
3958         }
3959 if (!$config{'tempbase'}) {
3960         $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3961         $config{'tempbase'} = "$1/cgitemp";
3962         }
3963 if (!$config{'blockedfile'}) {
3964         $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3965         $config{'blockedfile'} = "$1/blocked";
3966         }
3967 }
3968
3969 # read_users_file()
3970 # Fills the %users and %certs hashes from the users file in %config
3971 sub read_users_file
3972 {
3973 undef(%users);
3974 undef(%certs);
3975 undef(%allow);
3976 undef(%deny);
3977 undef(%allowdays);
3978 undef(%allowhours);
3979 undef(%lastchanges);
3980 undef(%nochange);
3981 undef(%temppass);
3982 if ($config{'userfile'}) {
3983         open(USERS, $config{'userfile'});
3984         while(<USERS>) {
3985                 s/\r|\n//g;
3986                 local @user = split(/:/, $_, -1);
3987                 $users{$user[0]} = $user[1];
3988                 $certs{$user[0]} = $user[3] if ($user[3]);
3989                 if ($user[4] =~ /^allow\s+(.*)/) {
3990                         $allow{$user[0]} = $config{'alwaysresolve'} ?
3991                                 [ split(/\s+/, $1) ] :
3992                                 [ &to_ipaddress(split(/\s+/, $1)) ];
3993                         }
3994                 elsif ($user[4] =~ /^deny\s+(.*)/) {
3995                         $deny{$user[0]} = $config{'alwaysresolve'} ?
3996                                 [ split(/\s+/, $1) ] :
3997                                 [ &to_ipaddress(split(/\s+/, $1)) ];
3998                         }
3999                 if ($user[5] =~ /days\s+(\S+)/) {
4000                         $allowdays{$user[0]} = [ split(/,/, $1) ];
4001                         }
4002                 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4003                         $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4004                         }
4005                 $lastchanges{$user[0]} = $user[6];
4006                 $nochange{$user[0]} = $user[9];
4007                 $temppass{$user[0]} = $user[10];
4008                 }
4009         close(USERS);
4010         }
4011 }
4012
4013 # read_mime_types()
4014 # Fills %mime with entries from file in %config and extra settings in %config
4015 sub read_mime_types
4016 {
4017 undef(%mime);
4018 if ($config{"mimetypes"} ne "") {
4019         open(MIME, $config{"mimetypes"});
4020         while(<MIME>) {
4021                 chop; s/#.*$//;
4022                 if (/^(\S+)\s+(.*)$/) {
4023                         my $type = $1;
4024                         my @exts = split(/\s+/, $2);
4025                         foreach my $ext (@exts) {
4026                                 $mime{$ext} = $type;
4027                                 }
4028                         }
4029                 }
4030         close(MIME);
4031         }
4032 foreach my $k (keys %config) {
4033         if ($k !~ /^addtype_(.*)$/) { next; }
4034         $mime{$1} = $config{$k};
4035         }
4036 }
4037
4038 # build_config_mappings()
4039 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4040 # redirect mapping and allow and deny lists from %config
4041 sub build_config_mappings
4042 {
4043 # build anonymous access list
4044 undef(%anonymous);
4045 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4046         if ($a =~ /^([^=]+)=(\S+)$/) {
4047                 $anonymous{$1} = $2;
4048                 }
4049         }
4050
4051 # build IP access list
4052 undef(%ipaccess);
4053 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4054         if ($a =~ /^([^=]+)=(\S+)$/) {
4055                 $ipaccess{$1} = $2;
4056                 }
4057         }
4058
4059 # build unauthenticated URLs list
4060 @unauth = split(/\s+/, $config{'unauth'});
4061
4062 # build redirect mapping
4063 undef(%redirect);
4064 foreach my $r (split(/\s+/, $config{'redirect'})) {
4065         if ($r =~ /^([^=]+)=(\S+)$/) {
4066                 $redirect{$1} = $2;
4067                 }
4068         }
4069
4070 # build prefixes to be stripped
4071 undef(@strip_prefix);
4072 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4073         push(@strip_prefix, $r);
4074         }
4075
4076 # Init allow and deny lists
4077 @deny = split(/\s+/, $config{"deny"});
4078 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4079 @allow = split(/\s+/, $config{"allow"});
4080 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4081 undef(@allowusers);
4082 undef(@denyusers);
4083 if ($config{'allowusers'}) {
4084         @allowusers = split(/\s+/, $config{'allowusers'});
4085         }
4086 elsif ($config{'denyusers'}) {
4087         @denyusers = split(/\s+/, $config{'denyusers'});
4088         }
4089
4090 # Build list of unixauth mappings
4091 undef(%unixauth);
4092 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4093         if ($ua =~ /^(\S+)=(\S+)$/) {
4094                 $unixauth{$1} = $2;
4095                 }
4096         else {
4097                 $unixauth{"*"} = $ua;
4098                 }
4099         }
4100
4101 # Build list of non-session-auth pages
4102 undef(%sessiononly);
4103 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4104         $sessiononly{$sp} = 1;
4105         }
4106
4107 # Build list of logout times
4108 undef(@logouttimes);
4109 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4110         if ($a =~ /^([^=]+)=(\S+)$/) {
4111                 push(@logouttimes, [ $1, $2 ]);
4112                 }
4113         }
4114 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4115
4116 # Build list of DAV pathss
4117 undef(@davpaths);
4118 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4119         push(@davpaths, $d);
4120         }
4121 @davusers = split(/\s+/, $config{'dav_users'});
4122
4123 # Mobile agent substrings and hostname prefixes
4124 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4125 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4126
4127 # Open debug log
4128 close(DEBUG);
4129 if ($config{'debug'}) {
4130         open(DEBUG, ">>$config{'debug'}");
4131         }
4132 else {
4133         open(DEBUG, ">/dev/null");
4134         }
4135
4136 # Reset cache of sudo checks
4137 undef(%sudocache);
4138 }
4139
4140 # is_group_member(&uinfo, groupname)
4141 # Returns 1 if some user is a primary or secondary member of a group
4142 sub is_group_member
4143 {
4144 local ($uinfo, $group) = @_;
4145 local @ginfo = getgrnam($group);
4146 return 0 if (!@ginfo);
4147 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4148 foreach my $m (split(/\s+/, $ginfo[3])) {
4149         return 1 if ($m eq $uinfo->[0]);
4150         }
4151 return 0;
4152 }
4153
4154 # prefix_to_mask(prefix)
4155 # Converts a number like 24 to a mask like 255.255.255.0
4156 sub prefix_to_mask
4157 {
4158 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4159        $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4160        $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4161                      (256-(2 ** (8-$_[0]))).".0.0.0";
4162 }
4163
4164 # get_logout_time(user, session-id)
4165 # Given a username, returns the idle time before he will be logged out
4166 sub get_logout_time
4167 {
4168 local ($user, $sid) = @_;
4169 if (!defined($logout_time_cache{$user,$sid})) {
4170         local $time;
4171         foreach my $l (@logouttimes) {
4172                 if ($l->[0] =~ /^\@(.*)$/) {
4173                         # Check group membership
4174                         local @uinfo = getpwnam($user);
4175                         if (@uinfo && &is_group_member(\@uinfo, $1)) {
4176                                 $time = $l->[1];
4177                                 }
4178                         }
4179                 elsif ($l->[0] =~ /^\//) {
4180                         # Check file contents
4181                         open(FILE, $l->[0]);
4182                         while(<FILE>) {
4183                                 s/\r|\n//g;
4184                                 s/^\s*#.*$//;
4185                                 if ($user eq $_) {
4186                                         $time = $l->[1];
4187                                         last;
4188                                         }
4189                                 }
4190                         close(FILE);
4191                         }
4192                 elsif (!$l->[0]) {
4193                         # Always match
4194                         $time = $l->[1];
4195                         }
4196                 else {
4197                         # Check username
4198                         if ($l->[0] eq $user) {
4199                                 $time = $l->[1];
4200                                 }
4201                         }
4202                 last if (defined($time));
4203                 }
4204         $logout_time_cache{$user,$sid} = $time;
4205         }
4206 return $logout_time_cache{$user,$sid};
4207 }
4208
4209 # password_crypt(password, salt)
4210 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4211 # of a password. Otherwise, do Unix crypt.
4212 sub password_crypt
4213 {
4214 local ($pass, $salt) = @_;
4215 if ($salt =~ /^\$1\$/ && $use_md5) {
4216         return &encrypt_md5($pass, $salt);
4217         }
4218 else {
4219         return &unix_crypt($pass, $salt);
4220         }
4221 }
4222
4223 # unix_crypt(password, salt)
4224 # Performs standard Unix hashing for a password
4225 sub unix_crypt
4226 {
4227 local ($pass, $salt) = @_;
4228 if ($use_perl_crypt) {
4229         return Crypt::UnixCrypt::crypt($pass, $salt);
4230         }
4231 else {
4232         return crypt($pass, $salt);
4233         }
4234 }
4235
4236 # handle_dav_request(davpath)
4237 # Pass a request on to the Net::DAV::Server module
4238 sub handle_dav_request
4239 {
4240 local ($path) = @_;
4241 eval "use Filesys::Virtual::Plain";
4242 eval "use Net::DAV::Server";
4243 eval "use HTTP::Request";
4244 eval "use HTTP::Headers";
4245
4246 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4247         delete $Net::DAV::Server::implemented{lock};
4248         delete $Net::DAV::Server::implemented{unlock};
4249         }
4250
4251 # Read in request data
4252 if (!$posted_data) {
4253         local $clen = $header{"content-length"};
4254         while(length($posted_data) < $clen) {
4255                 $buf = &read_data($clen - length($posted_data));
4256                 if (!length($buf)) {
4257                         &http_error(500, "Failed to read POST request");
4258                         }
4259                 chomp($posted_data);
4260                 #$posted_data =~ s/\015$//mg;
4261                 $posted_data .= $buf;
4262                 }
4263         }
4264
4265 # For subsequent logging
4266 open(MINISERVLOG, ">>$config{'logfile'}");
4267
4268 # Switch to user
4269 local $root;
4270 local @u = getpwnam($authuser);
4271 if ($config{'dav_remoteuser'} && !$< && $validated) {
4272         if (@u) {
4273                 if ($u[2] != 0) {
4274                         $( = $u[3]; $) = "$u[3] $u[3]";
4275                         ($>, $<) = ($u[2], $u[2]);
4276                         }
4277                 if ($config{'dav_root'} eq '*') {
4278                         $root = $u[7];
4279                         }
4280                 }
4281         else {
4282                 &http_error(500, "Unix user $authuser does not exist");
4283                 return 0;
4284                 }
4285         }
4286 $root ||= $config{'dav_root'};
4287 $root ||= "/";
4288
4289 # Check if this user can use DAV
4290 if (@davusers) {
4291         &users_match(\@u, @davusers) ||
4292                 &http_error(500, "You are not allowed to access DAV");
4293         }
4294
4295 # Create DAV server
4296 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4297 my $webdav = Net::DAV::Server->new();
4298 $webdav->filesys($filesys);
4299
4300 # Make up a request object, and feed to DAV
4301 local $ho = HTTP::Headers->new;
4302 foreach my $h (keys %header) {
4303         next if (lc($h) eq "connection");
4304         $ho->header($h => $header{$h});
4305         }
4306 if ($path ne "/") {
4307         $request_uri =~ s/^\Q$path\E//;
4308         $request_uri = "/" if ($request_uri eq "");
4309         }
4310 my $request = HTTP::Request->new($method, $request_uri, $ho,
4311                                  $posted_data);
4312 if ($config{'dav_debug'}) {
4313         print STDERR "DAV request :\n";
4314         print STDERR "---------------------------------------------\n";
4315         print STDERR $request->as_string();
4316         print STDERR "---------------------------------------------\n";
4317         }
4318 my $response = $webdav->run($request);
4319
4320 # Send back the reply
4321 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4322 local $content = $response->content();
4323 if ($path ne "/") {
4324         $content =~ s|href>/(.+)<|href>$path/$1<|g;
4325         $content =~ s|href>/<|href>$path<|g;
4326         }
4327 foreach my $h ($response->header_field_names) {
4328         next if (lc($h) eq "connection" || lc($h) eq "content-length");
4329         &write_data("$h: ",$response->header($h),"\r\n");
4330         }
4331 &write_data("Content-length: ",length($content),"\r\n");
4332 local $rv = &write_keep_alive(0);
4333 &write_data("\r\n");
4334 &write_data($content);
4335
4336 if ($config{'dav_debug'}) {
4337         print STDERR "DAV reply :\n";
4338         print STDERR "---------------------------------------------\n";
4339         print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4340         foreach my $h ($response->header_field_names) {
4341                 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4342                 print STDERR "$h: ",$response->header($h),"\r\n";
4343                 }
4344         print STDERR "Content-length: ",length($content),"\r\n";
4345         print STDERR "\r\n";
4346         print STDERR $content;
4347         print STDERR "---------------------------------------------\n";
4348         }
4349
4350 # Log it
4351 &log_request($acpthost, $authuser, $reqline, $response->code(), 
4352              length($response->content()));
4353 }
4354
4355 # get_system_hostname()
4356 # Returns the hostname of this system, for reporting to listeners
4357 sub get_system_hostname
4358 {
4359 # On Windows, try computername environment variable
4360 return $ENV{'computername'} if ($ENV{'computername'});
4361 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4362
4363 # If a specific command is set, use it first
4364 if ($config{'hostname_command'}) {
4365         local $out = `($config{'hostname_command'}) 2>&1`;
4366         if (!$?) {
4367                 $out =~ s/\r|\n//g;
4368                 return $out;
4369                 }
4370         }
4371
4372 # First try the hostname command
4373 local $out = `hostname 2>&1`;
4374 if (!$? && $out =~ /\S/) {
4375         $out =~ s/\r|\n//g;
4376         return $out;
4377         }
4378
4379 # Try the Sys::Hostname module
4380 eval "use Sys::Hostname";
4381 if (!$@) {
4382         local $rv = eval "hostname()";
4383         if (!$@ && $rv) {
4384                 return $rv;
4385                 }
4386         }
4387
4388 # Must use net name on Windows
4389 local $out = `net name 2>&1`;
4390 if ($out =~ /\-+\r?\n(\S+)/) {
4391         return $1;
4392         }
4393
4394 return undef;
4395 }
4396
4397 # indexof(string, array)
4398 # Returns the index of some value in an array, or -1
4399 sub indexof {
4400   local($i);
4401   for($i=1; $i <= $#_; $i++) {
4402     if ($_[$i] eq $_[0]) { return $i - 1; }
4403   }
4404   return -1;
4405 }
4406
4407
4408 # has_command(command)
4409 # Returns the full path if some command is in the path, undef if not
4410 sub has_command
4411 {
4412 local($d);
4413 if (!$_[0]) { return undef; }
4414 if (exists($has_command_cache{$_[0]})) {
4415         return $has_command_cache{$_[0]};
4416         }
4417 local $rv = undef;
4418 if ($_[0] =~ /^\//) {
4419         $rv = -x $_[0] ? $_[0] : undef;
4420         }
4421 else {
4422         local $sp = $on_windows ? ';' : ':';
4423         foreach $d (split($sp, $ENV{PATH})) {
4424                 if (-x "$d/$_[0]") {
4425                         $rv = "$d/$_[0]";
4426                         last;
4427                         }
4428                 if ($on_windows) {
4429                         foreach my $sfx (".exe", ".com", ".bat") {
4430                                 if (-r "$d/$_[0]".$sfx) {
4431                                         $rv = "$d/$_[0]".$sfx;
4432                                         last;
4433                                         }
4434                                 }
4435                         }
4436                 }
4437         }
4438 $has_command_cache{$_[0]} = $rv;
4439 return $rv;
4440 }
4441
4442 # check_sudo_permissions(user, pass)
4443 # Returns 1 if some user can run any command via sudo
4444 sub check_sudo_permissions
4445 {
4446 local ($user, $pass) = @_;
4447
4448 # First try the pipes
4449 if ($PASSINw) {
4450         print DEBUG "check_sudo_permissions: querying cache for $user\n";
4451         print $PASSINw "readsudo $user\n";
4452         local $can = <$PASSOUTr>;
4453         chop($can);
4454         print DEBUG "check_sudo_permissions: cache said $can\n";
4455         if ($can =~ /^\d+$/ && $can != 2) {
4456                 return int($can);
4457                 }
4458         }
4459
4460 local $ptyfh = new IO::Pty;
4461 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
4462 if (!$ptyfh) {
4463         print STDERR "Failed to create new PTY with IO::Pty\n";
4464         return 0;
4465         }
4466 local @uinfo = getpwnam($user);
4467 if (!@uinfo) {
4468         print STDERR "Unix user $user does not exist for sudo\n";
4469         return 0;
4470         }
4471
4472 # Execute sudo in a sub-process, via a pty
4473 local $ttyfh = $ptyfh->slave();
4474 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
4475 local $tty = $ptyfh->ttyname();
4476 print DEBUG "check_sudo_permissions: tty=$tty\n";
4477 chown($uinfo[2], $uinfo[3], $tty);
4478 pipe(SUDOr, SUDOw);
4479 print DEBUG "check_sudo_permissions: about to fork..\n";
4480 local $pid = fork();
4481 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
4482 if ($pid < 0) {
4483         print STDERR "fork for sudo failed : $!\n";
4484         return 0;
4485         }
4486 if (!$pid) {
4487         setsid();
4488         $ptyfh->make_slave_controlling_terminal();
4489         close(STDIN); close(STDOUT); close(STDERR);
4490         untie(*STDIN); untie(*STDOUT); untie(*STDERR);
4491         close($PASSINw); close($PASSOUTr);
4492         $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
4493         ($>, $<) = ($uinfo[2], $uinfo[2]);
4494
4495         close(SUDOw);
4496         close(SOCK);
4497         close(MAIN);
4498         open(STDIN, "<&SUDOr");
4499         open(STDOUT, ">$tty");
4500         open(STDERR, ">&STDOUT");
4501         close($ptyfh);
4502         exec("sudo -l -S");
4503         print "Exec failed : $!\n";
4504         exit 1;
4505         }
4506 print DEBUG "check_sudo_permissions: pid=$pid\n";
4507 close(SUDOr);
4508 $ptyfh->close_slave();
4509
4510 # Send password, and get back response
4511 local $oldfh = select(SUDOw);
4512 $| = 1;
4513 select($oldfh);
4514 print DEBUG "check_sudo_permissions: about to send pass\n";
4515 local $SIG{'PIPE'} = 'ignore';  # Sometimes sudo doesn't ask for a password
4516 print SUDOw $pass,"\n";
4517 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
4518 close(SUDOw);
4519 local $out;
4520 while(<$ptyfh>) {
4521         print DEBUG "check_sudo_permissions: got $_";
4522         $out .= $_;
4523         }
4524 close($ptyfh);
4525 kill('KILL', $pid);
4526 waitpid($pid, 0);
4527 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
4528
4529 # Update cache
4530 if ($PASSINw) {
4531         print $PASSINw "writesudo $user $ok\n";
4532         }
4533
4534 return $ok;
4535 }
4536
4537 # is_mobile_useragent(agent)
4538 # Returns 1 if some user agent looks like a cellphone or other mobile device,
4539 # such as a treo.
4540 sub is_mobile_useragent
4541 {
4542 local ($agent) = @_;
4543 local @prefixes = ( 
4544     "UP.Link",    # Openwave
4545     "Nokia",      # All Nokias start with Nokia
4546     "MOT-",       # All Motorola phones start with MOT-
4547     "SAMSUNG",    # Samsung browsers
4548     "Samsung",    # Samsung browsers
4549     "SEC-",       # Samsung browsers
4550     "AU-MIC",     # Samsung browsers
4551     "AUDIOVOX",   # Audiovox
4552     "BlackBerry", # BlackBerry
4553     "hiptop",     # Danger hiptop Sidekick
4554     "SonyEricsson", # Sony Ericsson
4555     "Ericsson",     # Old Ericsson browsers , mostly WAP
4556     "Mitsu/1.1.A",  # Mitsubishi phones
4557     "Panasonic WAP", # Panasonic old WAP phones
4558     "DoCoMo",     # DoCoMo phones
4559     "Lynx",       # Lynx text-mode linux browser
4560     "Links",      # Another text-mode linux browser
4561     );
4562 local @substrings = (
4563     "UP.Browser",         # Openwave
4564     "MobilePhone",        # NetFront
4565     "AU-MIC-A700",        # Samsung A700 Obigo browsers
4566     "Danger hiptop",      # Danger Sidekick hiptop
4567     "Windows CE",         # Windows CE Pocket PC
4568     "IEMobile",           # Windows mobile browser
4569     "Blazer",             # Palm Treo Blazer
4570     "BlackBerry",         # BlackBerries can emulate other browsers, but
4571                           # they still keep this string in the UserAgent
4572     "SymbianOS",          # New Series60 browser has safari in it and
4573                           # SymbianOS is the only distinguishing string
4574     "iPhone",             # Apple iPhone KHTML browser
4575     "iPod",               # iPod touch browser
4576     "MobileSafari",       # HTTP client in iPhone
4577     "Android",            # gPhone
4578     "Opera Mini",         # Opera Mini
4579     "HTC_P3700",          # HTC mobile device
4580     );
4581 foreach my $p (@prefixes) {
4582         return 1 if ($agent =~ /^\Q$p\E/);
4583         }
4584 foreach my $s (@substrings, @mobile_agents) {
4585         return 1 if ($agent =~ /\Q$s\E/);
4586         }
4587 return 0;
4588 }
4589
4590 # write_blocked_file()
4591 # Writes out a text file of blocked hosts and users
4592 sub write_blocked_file
4593 {
4594 open(BLOCKED, ">$config{'blockedfile'}");
4595 foreach my $d (grep { $hostfail{$_} } @deny) {
4596         print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
4597         }
4598 foreach my $d (grep { $userfail{$_} } @denyusers) {
4599         print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
4600         }
4601 close(BLOCKED);
4602 chmod(0700, $config{'blockedfile'});
4603 }
4604
4605 sub write_pid_file
4606 {
4607 open(PIDFILE, ">$config{'pidfile'}");
4608 printf PIDFILE "%d\n", getpid();
4609 close(PIDFILE);
4610 }
4611
4612 # lock_user_password(user)
4613 # Updates a user's password file entry to lock it, both in memory and on disk.
4614 # Returns 1 if done, -1 if no such user, 0 if already locked
4615 sub lock_user_password
4616 {
4617 local ($user) = @_;
4618 if ($users{$user}) {
4619         if ($users{$user} !~ /^\!/) {
4620                 # Lock the password
4621                 $users{$user} = "!".$users{$user};
4622                 open(USERS, $config{'userfile'});
4623                 local @ufile = <USERS>;
4624                 close(USERS);
4625                 foreach my $u (@ufile) {
4626                         local @uinfo = split(/:/, $u);
4627                         if ($uinfo[0] eq $user) {
4628                                 $uinfo[1] = $users{$user};
4629                                 }
4630                         $u = join(":", @uinfo);
4631                         }
4632                 open(USERS, ">$config{'userfile'}");
4633                 print USERS @ufile;
4634                 close(USERS);
4635                 return 1;
4636                 }
4637         return 0;
4638         }
4639 return -1;
4640 }
4641
4642 # hash_session_id(sid)
4643 # Returns an MD5 or Unix-crypted session ID
4644 sub hash_session_id
4645 {
4646 local ($sid) = @_;
4647 if (!$hash_session_id_cache{$sid}) {
4648         if ($use_md5) {
4649                 # Take MD5 hash
4650                 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
4651                 }
4652         else {
4653                 # Unix crypt
4654                 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
4655                 }
4656         }
4657 return $hash_session_id_cache{$sid};
4658 }
4659
4660 # encrypt_md5(string, [salt])
4661 # Returns a string encrypted in MD5 format
4662 sub encrypt_md5
4663 {
4664 local ($passwd, $salt) = @_;
4665 local $magic = '$1$';
4666 if ($salt =~ /^\$1\$([^\$]+)/) {
4667         # Extract actual salt from already encrypted password
4668         $salt = $1;
4669         }
4670
4671 # Add the password
4672 local $ctx = eval "new $use_md5";
4673 $ctx->add($passwd);
4674 if ($salt) {
4675         $ctx->add($magic);
4676         $ctx->add($salt);
4677         }
4678
4679 # Add some more stuff from the hash of the password and salt
4680 local $ctx1 = eval "new $use_md5";
4681 $ctx1->add($passwd);
4682 if ($salt) {
4683         $ctx1->add($salt);
4684         }
4685 $ctx1->add($passwd);
4686 local $final = $ctx1->digest();
4687 for($pl=length($passwd); $pl>0; $pl-=16) {
4688         $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
4689         }
4690
4691 # This piece of code seems rather pointless, but it's in the C code that
4692 # does MD5 in PAM so it has to go in!
4693 local $j = 0;
4694 local ($i, $l);
4695 for($i=length($passwd); $i; $i >>= 1) {
4696         if ($i & 1) {
4697                 $ctx->add("\0");
4698                 }
4699         else {
4700                 $ctx->add(substr($passwd, $j, 1));
4701                 }
4702         }
4703 $final = $ctx->digest();
4704
4705 if ($salt) {
4706         # This loop exists only to waste time
4707         for($i=0; $i<1000; $i++) {
4708                 $ctx1 = eval "new $use_md5";
4709                 $ctx1->add($i & 1 ? $passwd : $final);
4710                 $ctx1->add($salt) if ($i % 3);
4711                 $ctx1->add($passwd) if ($i % 7);
4712                 $ctx1->add($i & 1 ? $final : $passwd);
4713                 $final = $ctx1->digest();
4714                 }
4715         }
4716
4717 # Convert the 16-byte final string into a readable form
4718 local $rv;
4719 local @final = map { ord($_) } split(//, $final);
4720 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
4721 $rv .= &to64($l, 4);
4722 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
4723 $rv .= &to64($l, 4);
4724 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
4725 $rv .= &to64($l, 4);
4726 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
4727 $rv .= &to64($l, 4);
4728 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
4729 $rv .= &to64($l, 4);
4730 $l = $final[11];
4731 $rv .= &to64($l, 2);
4732
4733 # Add salt if needed
4734 if ($salt) {
4735         return $magic.$salt.'$'.$rv;
4736         }
4737 else {
4738         return $rv;
4739         }
4740 }
4741
4742 sub to64
4743 {
4744 local ($v, $n) = @_;
4745 local $r;
4746 while(--$n >= 0) {
4747         $r .= $itoa64[$v & 0x3f];
4748         $v >>= 6;
4749         }
4750 return $r;
4751 }
4752