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