2 # A very simple perl web server used by Webmin
4 # Require basic libraries
10 @itoa64 = split(//, "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
12 # Find and read config file
14 die "Usage: miniserv.pl <config file>";
16 if ($ARGV[0] =~ /^([a-z]:)?\//i) {
17 $config_file = $ARGV[0];
21 $config_file = "$pwd/$ARGV[0]";
23 %config = &read_config_file($config_file);
24 if ($config{'perllib'}) {
25 push(@INC, split(/:/, $config{'perllib'}));
26 $ENV{'PERLLIB'} .= ':'.$config{'perllib'};
29 # Check is SSL is enabled and available
31 eval "use Net::SSLeay";
34 # These functions only exist for SSLeay 1.0
35 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
36 eval "Net::SSLeay::load_error_strings()";
37 if ($config{'no_ssl2'}) {
38 eval "Net::SSLeay::CTX_set_options($ctx,&Net::SSLeay::OP_NO_SSLv2)";
40 if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
41 defined(&Net::SSLeay::CTX_load_verify_locations) &&
42 defined(&Net::SSLeay::CTX_set_verify)) {
48 # Check if the syslog module is available to log hacking attempts
49 if ($config{'syslog'} && !$config{'inetd'}) {
50 eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
56 # check if the TCP-wrappers module is available
57 if ($config{'libwrap'}) {
58 eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
64 # Check if the MD5 perl module is available
70 eval "use Digest::MD5";
72 $use_md5 = "Digest::MD5";
76 # Get miniserv's perl path and location
78 open(SOURCE, $miniserv_path);
79 <SOURCE> =~ /^#!(\S+)/;
86 $linked_perl_path = readlink($perl_path);
88 @miniserv_argv = @ARGV;
90 # Check vital config options
91 &update_vital_config();
93 $sidname = $config{'sidname'};
94 die "Session authentication cannot be used in inetd mode"
95 if ($config{'inetd'} && $config{'session'});
97 # check if the PAM module is available to authenticate
98 if (!$config{'no_pam'}) {
99 eval "use Authen::PAM;";
101 # check if the PAM authentication can be used by opening a
104 if (ref($pamh = new Authen::PAM($config{'pam'}, "root",
106 # Now test a login to see if /etc/pam.d/XXX is set
108 $pam_conv_func_called = 0;
109 $pam_username = "test";
110 $pam_password = "test";
111 $pamh->pam_authenticate();
112 if ($pam_conv_func_called) {
113 $pam_msg = "PAM authentication enabled";
117 $pam_msg = "PAM test failed - maybe /etc/pam.d/$config{'pam'} does not exist";
121 $pam_msg = "PAM initialization of Authen::PAM failed";
125 $pam_msg = "Perl module Authen::PAM needed for PAM is not installed : $@";
128 if ($config{'pam_only'} && !$use_pam) {
129 $pam_msg2 = "PAM use is mandatory, but could not be enabled!";
131 elsif ($pam_msg && !$use_pam) {
132 $pam_msg2 = "Continuing without the Authen::PAM perl module";
135 # Check if the User::Utmp perl module is installed
136 if ($config{'utmp'}) {
137 eval "use User::Utmp;";
140 $utmp_msg = "UTMP logging enabled";
143 $utmp_msg = "Perl module User::Utmp needed for Utmp logging is not installed : $@";
147 # See if the crypt function fails
148 eval "crypt('foo', 'xx')";
150 eval "use Crypt::UnixCrypt";
153 $crypt_msg = "Using Crypt::UnixCrypt for password encryption\n";
156 $crypt_msg = "crypt() function un-implemented, and Crypt::UnixCrypt not installed - password authentication will probably fail\n";
160 # Check if /dev/urandom really generates random IDs, by calling it twice
161 local $rand1 = &generate_random_id("foo", 1);
162 local $rand2 = &generate_random_id("foo", 2);
164 if ($rand1 eq $rand2) {
166 $rand_msg = "Random number generator file /dev/urandom is not reliable";
169 # Check if we can call sudo
170 if ($config{'sudo'} && &has_command("sudo")) {
176 $sudo_msg = "Perl module IO::Pty needed for calling sudo is not installed : $@";
180 # init days and months for http_date
181 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
182 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
183 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
185 # Change dir to the server root
186 @roots = ( $config{'root'} );
187 for($i=0; defined($config{"extraroot_$i"}); $i++) {
188 push(@roots, $config{"extraroot_$i"});
191 eval { $user_homedir = (getpwuid($<))[7]; };
193 # getpwuid doesn't work on windows
194 $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
201 # Setup SSL if possible and if requested
202 if (!-r $config{'keyfile'} ||
203 $config{'certfile'} && !-r $config{'certfile'}) {
204 # Key file doesn't exist!
207 @ipkeys = &get_ipkeys(\%config);
209 if ($config{'ssl_version'}) {
210 # Force an SSL version
211 $Net::SSLeay::version = $config{'ssl_version'};
212 $Net::SSLeay::ssl_version = $config{'ssl_version'};
214 $client_certs = 0 if (!-r $config{'ca'} || !%certs);
215 $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
216 $config{'certfile'});
217 foreach $ipkey (@ipkeys) {
218 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'});
219 foreach $ip (@{$ipkey->{'ips'}}) {
220 $ssl_contexts{$ip} = $ctx;
225 # Setup syslog support if possible and if requested
227 open(ERRDUP, ">&STDERR");
228 open(STDERR, ">/dev/null");
229 $log_socket = $config{"logsock"} || "unix";
230 eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
235 local $msg = ucfirst($config{'pam'})." starting";
236 eval { syslog("info", "%s", $msg); };
240 syslog("info", "%s", $msg);
243 # All attempts to use syslog have failed..
248 open(STDERR, ">&ERRDUP");
252 # Read MIME types file and add extra types
256 if ($config{'log'}) {
257 local(@gmt, @lct, $days, $hours, $mins);
258 @gmt = gmtime(time());
259 @lct = localtime(time());
260 $days = $lct[3] - $gmt[3];
261 $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
263 $mins = $hours * 60 + $lct[1] - $gmt[1];
264 $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
265 $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
268 # Build various maps from the config files
269 &build_config_mappings();
271 # start up external authentication program, if needed
272 if ($config{'extauth'}) {
273 socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
274 if (!($extauth = fork())) {
278 open(STDIN, "<&EXTAUTH2");
279 open(STDOUT, ">&EXTAUTH2");
280 exec($config{'extauth'}) or die "exec failed : $!\n";
283 local $os = select(EXTAUTH);
287 # Pre-load any libraries
288 foreach $pl (split(/\s+/, $config{'preload'})) {
289 ($pkg, $lib) = split(/=/, $pl);
290 $pkg =~ s/[^A-Za-z0-9]/_/g;
291 eval "package $pkg; do '$config{'root'}/$lib'";
293 print STDERR "Failed to pre-load $lib in $pkg : $@\n";
296 print STDERR "Pre-loaded $lib in $pkg\n";
299 foreach $pl (split(/\s+/, $config{'premodules'})) {
301 ($dir, $mod) = split(/\//, $pl);
304 ($dir, $mod) = (undef, $pl);
306 push(@INC, "$config{'root'}/$dir");
307 eval "package $mod; use $mod ()";
309 print STDERR "Failed to pre-load $mod : $@\n";
312 print STDERR "Pre-loaded $mod\n";
316 # Open debug log if set
317 if ($config{'debuglog'}) {
318 open(DEBUG, ">>$config{'debuglog'}");
319 chmod(0700, $config{'debuglog'});
320 select(DEBUG); $| = 1; select(STDOUT);
321 print DEBUG "miniserv.pl starting ..\n";
324 # Write out (empty) blocked hosts file
325 &write_blocked_file();
327 # Re-direct STDERR to a log file
328 if ($config{'errorlog'} ne '-') {
329 open(STDERR, ">>$config{'errorlog'}") || die "failed to open $config{'errorlog'} : $!";
330 if ($config{'logperms'}) {
331 chmod(oct($config{'logperms'}), $config{'errorlog'});
334 select(STDERR); $| = 1; select(STDOUT);
336 if ($config{'inetd'}) {
337 # We are being run from inetd - go direct to handling the request
338 $SIG{'HUP'} = 'IGNORE';
339 $SIG{'TERM'} = 'DEFAULT';
340 $SIG{'PIPE'} = 'DEFAULT';
341 open(SOCK, "+>&STDIN");
343 # Check if it is time for the logfile to be cleared
344 if ($config{'logclear'}) {
345 local $write_logtime = 0;
346 local @st = stat("$config{'logfile'}.time");
348 if ($st[9]+$config{'logtime'}*60*60 < time()){
351 unlink($config{'logfile'});
354 else { $write_logtime = 1; }
355 if ($write_logtime) {
356 open(LOGTIME, ">$config{'logfile'}.time");
357 print LOGTIME time(),"\n";
362 # Initialize SSL for this connection
364 $ssl_con = &ssl_connection_for_ip(SOCK);
368 # Work out the hostname for this web server
369 $host = &get_socket_name(SOCK);
371 $port = $config{'port'};
372 $acptaddr = getpeername(SOCK);
375 print DEBUG "main: Starting handle_request loop pid=$$\n";
376 while(&handle_request($acptaddr, getsockname(SOCK))) { }
377 print DEBUG "main: Done handle_request loop pid=$$\n";
382 # Build list of sockets to listen on
383 if ($config{"bind"} && $config{"bind"} ne "*") {
384 push(@sockets, [ inet_aton($config{'bind'}), $config{'port'} ]);
387 push(@sockets, [ INADDR_ANY, $config{'port'} ]);
389 foreach $s (split(/\s+/, $config{'sockets'})) {
390 if ($s =~ /^(\d+)$/) {
391 # Just listen on another port on the main IP
392 push(@sockets, [ $sockets[0]->[0], $s ]);
394 elsif ($s =~ /^(\S+):(\d+)$/) {
395 # Listen on a specific port and IP
396 push(@sockets, [ $1 eq "*" ? INADDR_ANY : inet_aton($1), $2 ]);
398 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
399 # Listen on the main port on another IP
400 push(@sockets, [ inet_aton($1), $sockets[0]->[1] ]);
404 # Open all the sockets
405 $proto = getprotobyname('tcp');
407 $tried_inaddr_any = 0;
408 for($i=0; $i<@sockets; $i++) {
410 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
411 die "Failed to open socket : $!";
412 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
413 for($j=0; $j<5; $j++) {
414 last if (bind($fh, pack_sockaddr_in($sockets[$i]->[1],
415 $sockets[$i]->[0])));
419 # All attempts failed .. give up
420 if ($sockets[$i]->[0] eq INADDR_ANY) {
421 push(@sockerrs, "Failed to bind to port $sockets[$i]->[1] : $!");
422 $tried_inaddr_any = 1;
425 $ip = inet_ntoa($sockets[$i]->[0]);
426 push(@sockerrs, "Failed to bind to IP $ip port $sockets[$i]->[1] : $!");
430 listen($fh, SOMAXCONN);
431 push(@socketfhs, $fh);
434 foreach $se (@sockerrs) {
435 print STDERR $se,"\n";
438 # If all binds failed, try binding to any address
439 if (!@socketfhs && !$tried_inaddr_any) {
440 print STDERR "Falling back to listening on any address\n";
442 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
443 die "Failed to open socket : $!";
444 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
445 bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY)) ||
446 die "Failed to bind to port $sockets[0]->[1] : $!";
447 listen($fh, SOMAXCONN);
448 push(@socketfhs, $fh);
450 elsif (!@socketfhs && $tried_inaddr_any) {
451 die "Could not listen on any ports";
454 if ($config{'listen'}) {
455 # Open the socket that allows other webmin servers to find this one
456 $proto = getprotobyname('udp');
457 if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
458 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
459 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
460 listen(LISTEN, SOMAXCONN);
463 $config{'listen'} = 0;
467 # Split from the controlling terminal, unless configured not to
468 if (!$config{'nofork'}) {
469 if (fork()) { exit; }
471 eval { setsid(); }; # may not work on Windows
473 # Close standard file handles
474 open(STDIN, "</dev/null");
475 open(STDOUT, ">/dev/null");
476 &log_error("miniserv.pl started");
477 &log_error($pam_msg) if ($pam_msg);
478 &log_error($pam_msg2) if ($pam_msg2);
479 &log_error($utmp_msg) if ($utmp_msg);
480 &log_error($crypt_msg) if ($crypt_msg);
481 &log_error($sudo_msg) if ($sudo_msg);
482 &log_error($rand_msg) if ($rand_msg);
484 # write out the PID file
487 # Start the log-clearing process, if needed. This checks every minute
488 # to see if the log has passed its reset time, and if so clears it
489 if ($config{'logclear'}) {
490 if (!($logclearer = fork())) {
491 &close_all_sockets();
494 local $write_logtime = 0;
495 local @st = stat("$config{'logfile'}.time");
497 if ($st[9]+$config{'logtime'}*60*60 < time()){
500 unlink($config{'logfile'});
503 else { $write_logtime = 1; }
504 if ($write_logtime) {
505 open(LOGTIME, ">$config{'logfile'}.time");
506 print LOGTIME time(),"\n";
513 push(@childpids, $logclearer);
516 # Setup the logout time dbm if needed
517 if ($config{'session'}) {
518 eval "use SDBM_File";
519 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
520 eval "\$sessiondb{'1111111111'} = 'foo bar';";
522 dbmclose(%sessiondb);
523 eval "use NDBM_File";
524 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
527 delete($sessiondb{'1111111111'});
532 $SIG{'HUP'} = 'miniserv::trigger_restart';
533 $SIG{'TERM'} = 'miniserv::term_handler';
534 $SIG{'USR1'} = 'miniserv::trigger_reload';
535 $SIG{'PIPE'} = 'IGNORE';
536 local $remove_session_count = 0;
537 $need_pipes = $config{'passdelay'} || $config{'session'};
538 $last_pid_time = time();
540 # wait for a new connection, or a message from a child process
542 if (@childpids <= $config{'maxconns'}) {
543 # Only accept new main socket connects when ready
545 foreach $s (@socketfhs) {
546 vec($rmask, fileno($s), 1) = 1;
550 printf STDERR "too many children (%d > %d)\n",
551 scalar(@childpids), $config{'maxconns'};
554 for($i=0; $i<@passin; $i++) {
555 vec($rmask, fileno($passin[$i]), 1) = 1;
558 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
560 # Wait for a connection
561 local $sel = select($rmask, undef, undef, 10);
563 # Check the flag files
564 if ($config{'restartflag'} && -r $config{'restartflag'}) {
565 print STDERR "restart flag file detected\n";
566 unlink($config{'restartflag'});
569 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
570 unlink($config{'reloadflag'});
575 # Got a HUP signal while in select() .. restart now
579 # Got a USR1 signal while in select() .. re-read config
581 &reload_config_file();
583 local $time_now = time();
585 # Write the PID every 10 seconds
586 if ($time_now - $last_pid_time > 10) {
588 $last_pid_time = $time_now;
591 # Clean up finished processes
593 do { $pid = waitpid(-1, WNOHANG);
594 @childpids = grep { $_ != $pid } @childpids;
595 } while($pid != 0 && $pid != -1);
597 # run the unblocking procedure to check if enough time has passed to
598 # unblock hosts that heve been blocked because of password failures
600 if ($config{'blockhost_failures'}) {
602 while ($i <= $#deny) {
603 if ($blockhosttime{$deny[$i]} &&
604 $config{'blockhost_time'} != 0 &&
605 ($time_now - $blockhosttime{$deny[$i]}) >=
606 $config{'blockhost_time'}) {
607 # the host can be unblocked now
608 $hostfail{$deny[$i]} = 0;
609 splice(@deny, $i, 1);
616 # Do the same for blocked users
617 if ($config{'blockuser_failures'}) {
619 while ($i <= $#deny) {
620 if ($blockusertime{$deny[$i]} &&
621 $config{'blockuser_time'} != 0 &&
622 ($time_now - $blockusertime{$deny[$i]}) >=
623 $config{'blockuser_time'}) {
624 # the user can be unblocked now
625 $userfail{$deny[$i]} = 0;
626 splice(@denyusers, $i, 1);
633 &write_blocked_file();
636 if ($config{'session'} && (++$remove_session_count%50) == 0) {
637 # Remove sessions with more than 7 days of inactivity,
639 foreach $s (keys %sessiondb) {
640 local ($user, $ltime, $lip) =
641 split(/\s+/, $sessiondb{$s});
642 if ($time_now - $ltime > 7*24*60*60) {
643 &run_logout_script($s, $user);
644 &write_logout_utmp($user, $lip);
645 delete($sessiondb{$s});
648 "Timeout of session for $user");
654 if ($use_pam && $config{'pam_conv'}) {
655 # Remove PAM sessions with more than 5 minutes of inactivity
657 foreach $c (values %conversations) {
658 if ($time_now - $c->{'time'} > 5*60) {
659 &end_pam_conversation($c);
661 syslog("info", "%s", "Timeout of PAM ".
662 "session for $c->{'user'}");
668 # Don't check any sockets if there is no activity
671 # Check if any of the main sockets have received a new connection
673 foreach $s (@socketfhs) {
674 if (vec($rmask, fileno($s), 1)) {
676 $acptaddr = accept(SOCK, $s);
677 if (!$acptaddr) { next; }
678 binmode(SOCK); # turn off any Perl IO stuff
681 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
683 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
687 # Check username of connecting user
688 local ($peerp, $peera) = unpack_sockaddr_in($acptaddr);
689 $localauth_user = undef;
690 if ($config{'localauth'} && inet_ntoa($peera) eq "127.0.0.1") {
691 if (open(TCP, "/proc/net/tcp")) {
692 # Get the info direct from the kernel
695 local @t = split(/[\s:]+/, $_);
696 if ($t[1] eq '0100007F' &&
697 $t[2] eq sprintf("%4.4X", $peerp)) {
698 $localauth_user = getpwuid($t[11]);
704 if (!$localauth_user) {
705 # Call lsof for the info
706 local $lsofpid = open(LSOF,
707 "$config{'localauth'} -i TCP\@127.0.0.1:$peerp |");
709 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
710 $2 != $$ && $2 != $lsofpid) {
711 $localauth_user = $3;
718 # Work out the hostname for this web server
719 $host = &get_socket_name(SOCK);
721 print STDERR "Failed to get local socket name : $!\n";
725 $port = $sockets[$sn]->[1];
727 # fork the subprocess
729 if (!($handpid = fork())) {
730 # setup signal handlers
731 $SIG{'TERM'} = 'DEFAULT';
732 $SIG{'PIPE'} = 'DEFAULT';
733 #$SIG{'CHLD'} = 'IGNORE';
734 $SIG{'HUP'} = 'IGNORE';
735 $SIG{'USR1'} = 'IGNORE';
737 # Initialize SSL for this connection
739 $ssl_con = &ssl_connection_for_ip(SOCK);
743 # Close the file handle for the session DBM
744 dbmclose(%sessiondb);
746 # close useless pipes
749 close($PASSINr); close($PASSOUTw);
751 &close_all_sockets();
755 "main: Starting handle_request loop pid=$$\n";
756 while(&handle_request($acptaddr,
757 getsockname(SOCK))) { }
759 "main: Done handle_request loop pid=$$\n";
762 close($PASSINw); close($PASSOUTw);
765 push(@childpids, $handpid);
767 close($PASSINw); close($PASSOUTr);
768 push(@passin, $PASSINr);
769 push(@passout, $PASSOUTw);
776 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
777 # Got UDP packet from another webmin server
779 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
781 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
782 local $toip = inet_ntoa((unpack_sockaddr_in(
783 getsockname(LISTEN)))[1]);
784 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
785 (!@allow || &ip_match($fromip, $toip, @allow))) {
786 local $listenhost = &get_socket_name(LISTEN);
787 send(LISTEN, "$listenhost:$config{'port'}:".
788 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
789 ($config{'listenhost'} ?
790 &get_system_hostname() : ""),
796 # check for session, password-timeout and PAM messages from subprocesses
797 for($i=0; $i<@passin; $i++) {
798 if (vec($rmask, fileno($passin[$i]), 1)) {
799 # this sub-process is asking about a password
800 local $infd = $passin[$i];
801 local $outfd = $passout[$i];
802 #local $inline = <$infd>;
803 local $inline = &sysread_line($infd);
805 print DEBUG "main: inline $inline";
808 print DEBUG "main: inline EOF\n";
810 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
811 # Got a delay request from a subprocess.. for
812 # valid logins, there is no delay (to prevent
813 # denial of service attacks), but for invalid
814 # logins the delay increases with each failed
817 # login OK.. no delay
818 print $outfd "0 0\n";
819 $wasblocked = $hostfail{$2} ||
824 &write_blocked_file();
833 # add the host to the block list,
835 if ($config{'blockhost_failures'} &&
837 $config{'blockhost_failures'}) {
839 $blockhosttime{$2} = $time_now;
842 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
848 # add the user to the user block list,
850 if ($config{'blockuser_failures'} &&
852 $config{'blockuser_failures'}) {
853 push(@denyusers, $1);
854 $blockusertime{$1} = $time_now;
857 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
863 # Lock out the user's password, if enabled
864 if ($config{'blocklock'} &&
866 $config{'blockuser_failures'}) {
867 my $lk = &lock_user_password($1);
870 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";
877 $dl = $userdlay{$1} -
878 int(($time_now - $userlast{$1})/50);
879 $dl = $dl < 0 ? 0 : $dl+1;
880 print $outfd "$dl $blocked\n";
883 # Write out blocked status file
885 &write_blocked_file();
888 $userlast{$1} = $time_now;
890 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
891 # Verifying a session ID
892 local $session_id = $1;
893 local $notimeout = $2;
894 local $skey = $sessiondb{$session_id} ?
896 &hash_session_id($session_id);
897 if (!defined($sessiondb{$skey})) {
898 # Session doesn't exist
899 print $outfd "0 0\n";
902 local ($user, $ltime) =
903 split(/\s+/, $sessiondb{$skey});
904 local $lot = &get_logout_time($user, $session_id);
906 $time_now - $ltime > $lot*60 &&
908 # Session has timed out
909 print $outfd "1 ",$time_now - $ltime,"\n";
910 #delete($sessiondb{$skey});
914 print $outfd "2 $user\n";
918 $sessiondb{$skey} = "$user $time_now";
923 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
924 # Creating a new session
925 local $session_id = $1;
928 $sessiondb{&hash_session_id($session_id)} =
929 "$user $time_now $ip";
931 elsif ($inline =~ /^delete\s+(\S+)/) {
932 # Logging out a session
933 local $session_id = $1;
934 local $skey = $sessiondb{$session_id} ?
936 &hash_session_id($session_id);
937 local @sdb = split(/\s+/, $sessiondb{$skey});
938 print $outfd $sdb[0],"\n";
939 delete($sessiondb{$skey});
941 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
942 # Starting a new PAM conversation
943 local ($cid, $host, $user) = ($1, $2, $3);
945 # Does this user even need PAM?
946 local ($realuser, $canlogin) =
947 &can_user_login($user, undef, $host);
949 if ($canlogin == 0) {
951 print $outfd "0 Invalid username\n";
953 elsif ($canlogin != 2) {
954 # Not using PAM .. so just ask for
956 $conv = { 'user' => $realuser,
961 print $outfd "3 Password\n";
964 # Start the PAM conversation
965 # sub-process, and get a question
966 $conv = { 'user' => $realuser,
970 local ($PAMINr, $PAMINw, $PAMOUTr,
971 $PAMOUTw) = &allocate_pipes();
972 local $pampid = fork();
974 close($PAMOUTr); close($PAMINw);
975 &pam_conversation_process(
979 close($PAMOUTw); close($PAMINr);
980 $conv->{'pid'} = $pampid;
981 $conv->{'PAMOUTr'} = $PAMOUTr;
982 $conv->{'PAMINw'} = $PAMINw;
983 push(@childpids, $pampid);
985 # Get the first PAM question
986 local $pok = &recv_pam_question(
989 &end_pam_conversation($conv);
993 $conversations{$cid} = $conv if ($conv);
995 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
996 # A response to a PAM question
997 local ($cid, $answer) = ($1, $2);
998 local $conv = $conversations{$cid};
1000 # No such conversation?
1001 print $outfd "0 Bad login session\n";
1003 elsif ($conv->{'pid'}) {
1004 # Send the PAM response and get
1006 &send_pam_answer($conv, $answer);
1007 local $pok = &recv_pam_question($conv, $outfd);
1009 &end_pam_conversation($conv);
1013 # This must be the password .. try it
1014 # and send back the results
1015 local ($vu, $expired, $nonexist) =
1016 &validate_user($conv->{'user'},
1019 local $ok = $vu ? 1 : 0;
1020 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1021 &end_pam_conversation($conv);
1024 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1025 # Store the fact that some user can sudo to root
1026 local ($user, $ok) = ($1, $2);
1027 $sudocache{$user} = $ok." ".time();
1029 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1030 # Query the user sudo cache (valid for 1 minute)
1032 local ($ok, $last) =
1033 split(/\s+/, $sudocache{$user});
1034 if ($last < time()-60) {
1039 # Tell client OK or not
1040 print $outfd "$ok\n";
1043 elsif ($inline =~ /\S/) {
1044 # Unknown line from pipe?
1045 print DEBUG "main: Unknown line from pipe $inline\n";
1046 print STDERR "Unknown line from pipe $inline\n";
1050 close($infd); close($outfd);
1051 $passin[$i] = $passout[$i] = undef;
1055 @passin = grep { defined($_) } @passin;
1056 @passout = grep { defined($_) } @passout;
1059 # handle_request(remoteaddress, localaddress)
1060 # Where the real work is done
1063 $acptip = inet_ntoa((unpack_sockaddr_in($_[0]))[1]);
1064 $localip = $_[1] ? inet_ntoa((unpack_sockaddr_in($_[1]))[1]) : undef;
1065 print DEBUG "handle_request: from $acptip to $localip\n";
1066 if ($config{'loghost'}) {
1067 $acpthost = gethostbyaddr(inet_aton($acptip), AF_INET);
1068 $acpthost = $acptip if (!$acpthost);
1071 $acpthost = $acptip;
1073 $datestr = &http_date(time());
1075 $ok_message = "Document follows";
1076 $logged_code = undef;
1077 $reqline = $request_uri = $page = undef;
1081 # check address against access list
1082 if (@deny && &ip_match($acptip, $localip, @deny) ||
1083 @allow && !&ip_match($acptip, $localip, @allow)) {
1084 &http_error(403, "Access denied for $acptip");
1089 # Check address with TCP-wrappers
1090 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1091 $acptip, STRING_UNKNOWN)) {
1092 &http_error(403, "Access denied for $acptip by TCP wrappers");
1096 print DEBUG "handle_request: passed IP checks\n";
1098 # Compute a timeout for the start of headers, based on the number of
1099 # child processes. As this increases, we use a shorter timeout to avoid
1100 # an attacker overloading the system.
1101 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1103 # Wait at most 60 secs for start of headers for initial requests, or
1104 # 10 minutes for kept-alive connections
1106 vec($rmask, fileno(SOCK), 1) = 1;
1107 local $to = $checked_timeout ? 10*60 : $header_timeout;
1108 local $sel = select($rmask, undef, undef, $to);
1110 if ($checked_timeout) {
1111 print DEBUG "handle_request: exiting due to timeout of $to\n";
1115 &http_error(400, "Timeout",
1116 "Waited for that $to seconds for start of headers");
1120 print DEBUG "handle_request: passed timeout check\n";
1122 # Read the HTTP request and headers
1123 local $origreqline = &read_line();
1124 ($reqline = $origreqline) =~ s/\r|\n//g;
1125 $method = $page = $request_uri = undef;
1126 print DEBUG "handle_request reqline=$reqline\n";
1127 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1128 # An empty request .. just close the connection
1129 print DEBUG "handle_request: rejecting empty request\n";
1132 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1133 print DEBUG "handle_request: invalid reqline=$reqline\n";
1135 # This could be an http request when it should be https
1137 local $url = $config{'musthost'} ?
1138 "https://$config{'musthost'}:$port/" :
1139 "https://$host:$port/";
1140 if ($config{'ssl_redirect'}) {
1141 # Just re-direct to the correct URL
1142 sleep(1); # Give browser a change to finish
1143 # sending its request
1144 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1145 &write_data("Date: $datestr\r\n");
1146 &write_data("Server: $config{'server'}\r\n");
1147 &write_data("Location: $url\r\n");
1148 &write_keep_alive(0);
1149 &write_data("\r\n");
1153 # Tell user the correct URL
1154 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1157 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1158 # This could be an https request when it should be http ..
1159 # need to fake a HTTP response
1162 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1163 eval "Net::SSLeay::load_error_strings()";
1164 $ssl_ctx = Net::SSLeay::CTX_new();
1165 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1166 $ssl_ctx, $config{'keyfile'},
1167 &Net::SSLeay::FILETYPE_PEM);
1168 Net::SSLeay::CTX_use_certificate_file(
1170 $config{'certfile'} || $config{'keyfile'},
1171 &Net::SSLeay::FILETYPE_PEM);
1172 $ssl_con = Net::SSLeay::new($ssl_ctx);
1176 select(SSLw); $| = 1; select(STDOUT);
1177 print SSLw $origreqline;
1179 while(sysread(SOCK, $buf, 1) > 0) {
1186 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1187 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1188 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1190 local $url = $config{'musthost'} ?
1191 "https://$config{'musthost'}:$port/" :
1192 "https://$host:$port/";
1193 if ($config{'ssl_redirect'}) {
1194 # Just re-direct to the correct URL
1195 sleep(1); # Give browser a change to
1196 # finish sending its request
1197 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1198 &write_data("Date: $datestr\r\n");
1199 &write_data("Server: $config{'server'}\r\n");
1200 &write_data("Location: $url\r\n");
1201 &write_keep_alive(0);
1202 &write_data("\r\n");
1206 # Tell user the correct URL
1207 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1211 &http_error(400, "Bad Request");
1215 &http_error(400, "Bad Request");
1219 $request_uri = $page = $2;
1223 ($headline = &read_line()) =~ s/\r|\n//g;
1224 last if ($headline eq "");
1225 print DEBUG "handle_request: got headline $headline\n";
1226 if ($headline =~ /^(\S+):\s*(.*)$/) {
1227 $header{$lastheader = lc($1)} = $2;
1229 elsif ($headline =~ /^\s+(.*)$/) {
1230 $header{$lastheader} .= $headline;
1233 &http_error(400, "Bad Header $headline");
1236 if (defined($header{'host'})) {
1237 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1238 ($host, $port) = ($1, $2);
1241 $host = $header{'host'};
1243 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1244 # Disallowed hostname used
1245 &http_error(400, "Invalid HTTP hostname");
1249 if ($page =~ /^([^\?]+)\?(.*)$/) {
1250 # There is some query string information
1253 print DEBUG "handle_request: querystring=$querystring\n";
1254 if ($querystring !~ /=/) {
1255 $queryargs = $querystring;
1256 $queryargs =~ s/\+/ /g;
1257 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1261 # Parse query-string parameters
1262 local @in = split(/\&/, $querystring);
1264 local ($k, $v) = split(/=/, $i, 2);
1265 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1266 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1271 $posted_data = undef;
1272 if ($method eq 'POST' &&
1273 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1274 # Read in posted query string information, up the configured maximum
1275 # post request length
1276 $clen = $header{"content-length"};
1277 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1278 while(length($posted_data) < $clen_read) {
1279 $buf = &read_data($clen_read - length($posted_data));
1280 if (!length($buf)) {
1281 &http_error(500, "Failed to read POST request");
1283 chomp($posted_data);
1284 $posted_data =~ s/\015$//mg;
1285 $posted_data .= $buf;
1287 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1288 if ($clen_read != $clen && length($posted_data) > $clen) {
1289 # If the client sent more data than we asked for, chop the
1291 $posted_data = substr($posted_data, 0, $clen);
1293 if (length($posted_data) > $clen) {
1294 # When the client sent too much, delay so that it gets headers
1297 if ($header{'user-agent'} =~ /MSIE/ &&
1298 $header{'user-agent'} !~ /Opera/i) {
1299 # MSIE includes an extra newline in the data
1300 $posted_data =~ s/\r|\n//g;
1302 local @in = split(/\&/, $posted_data);
1304 local ($k, $v) = split(/=/, $i, 2);
1306 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1307 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1310 print DEBUG "handle_request: posted_data=$posted_data\n";
1313 # replace %XX sequences in page
1314 $page =~ s/%(..)/pack("c",hex($1))/ge;
1316 # Check if the browser's user agent indicates a mobile device
1317 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1319 # Check if Host: header is for a mobile URL
1320 foreach my $m (@mobile_prefixes) {
1321 if ($header{'host'} =~ /^\Q$m\E/i) {
1326 # check for the logout flag file, and if existant deny authentication
1327 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1328 print DEBUG "handle_request: logout flag set\n";
1329 $deny_authentication++;
1330 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1331 chop($count = <LOGOUT>);
1335 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1336 print LOGOUT "$count\n";
1340 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1344 # check for any redirect for the requested URL
1345 foreach my $pfx (@strip_prefix) {
1346 my $l = length($pfx);
1347 if(length($page) >= $l &&
1348 substr($page,0,$l) eq $pfx) {
1349 $page=substr($page,$l);
1353 $simple = &simplify_path($page, $bogus);
1355 $rpath .= "&".$querystring if (defined($querystring));
1356 $redir = $redirect{$rpath};
1357 if (defined($redir)) {
1358 print DEBUG "handle_request: redir=$redir\n";
1359 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1360 &write_data("Date: $datestr\r\n");
1361 &write_data("Server: $config{'server'}\r\n");
1362 local $ssl = $use_ssl || $config{'inetd_ssl'};
1363 $portstr = $port == 80 && !$ssl ? "" :
1364 $port == 443 && $ssl ? "" : ":$port";
1365 $prot = $ssl ? "https" : "http";
1366 &write_data("Location: $prot://$host$portstr$redir\r\n");
1367 &write_keep_alive(0);
1368 &write_data("\r\n");
1372 # Check for a DAV request
1374 foreach my $d (@davpaths) {
1375 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1380 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1381 &http_error(400, "Bad Request method $method");
1384 # Check for password if needed
1386 print DEBUG "handle_request: Need authentication\n";
1390 # Session authentication is never used for connections by
1391 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1392 # or mobile browsers if requested.
1393 if ($header{'user-agent'} =~ /webmin/i ||
1394 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1395 $sessiononly{$simple} || $davpath ||
1396 $simple eq "/xmlrpc.cgi" ||
1397 $acptip eq $config{'host_nosession'} ||
1398 $mobile_device && $config{'mobile_nosession'}) {
1399 print DEBUG "handle_request: Forcing HTTP authentication\n";
1400 $config{'session'} = 0;
1403 # check for SSL authentication
1404 if ($use_ssl && $verified_client) {
1405 $peername = Net::SSLeay::X509_NAME_oneline(
1406 Net::SSLeay::X509_get_subject_name(
1407 Net::SSLeay::get_peer_certificate(
1409 local $peername2 = $peername;
1410 $peername2 =~ s/Email=/emailAddress=/ ||
1411 $peername2 =~ s/emailAddress=/Email=/;
1412 foreach $u (keys %certs) {
1413 if ($certs{$u} eq $peername ||
1414 $certs{$u} eq $peername2) {
1417 #syslog("info", "%s", "SSL login as $authuser from $acpthost") if ($use_syslog);
1421 if ($use_syslog && !$validated) {
1422 syslog("crit", "%s",
1423 "Unknown SSL certificate $peername");
1427 if (!$validated && !$deny_authentication) {
1428 # check for IP-based authentication
1430 foreach $a (keys %ipaccess) {
1431 if ($acptip eq $a) {
1432 # It does! Auth as the user
1434 $baseauthuser = $authuser =
1440 # Check for normal HTTP authentication
1441 if (!$validated && !$deny_authentication && !$config{'session'} &&
1442 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1443 # authorization given..
1444 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1445 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1446 local ($vu, $expired, $nonexist) =
1447 &validate_user($authuser, $authpass, $host);
1448 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1449 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1456 if ($use_syslog && !$validated) {
1457 syslog("crit", "%s",
1458 ($nonexist ? "Non-existent" :
1459 $expired ? "Expired" : "Invalid").
1460 " login as $authuser from $acpthost");
1462 if ($authuser =~ /\r|\n|\s/) {
1463 &http_error(500, "Invalid username",
1464 "Username contains invalid characters");
1466 if ($authpass =~ /\r|\n/) {
1467 &http_error(500, "Invalid password",
1468 "Password contains invalid characters");
1471 if ($config{'passdelay'} && !$config{'inetd'}) {
1472 # check with main process for delay
1473 print DEBUG "handle_request: about to ask for password delay\n";
1474 print $PASSINw "delay $authuser $acptip $validated\n";
1475 <$PASSOUTr> =~ /(\d+) (\d+)/;
1477 print DEBUG "handle_request: password delay $1 $2\n";
1482 # Check for a visit to the special session login page
1483 if ($config{'session'} && !$deny_authentication &&
1484 $page eq $config{'session_login'}) {
1485 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1486 # Logout clicked .. remove the session
1488 print $PASSINw "delete $sid\n";
1489 local $louser = <$PASSOUTr>;
1492 $already_session_id = undef;
1493 $authuser = $baseauthuser = undef;
1496 syslog("info", "%s", "Logout by $louser from $acpthost");
1498 &run_logout_script($louser, $sid,
1500 &write_logout_utmp($louser, $actphost);
1505 if ($in{'user'} =~ /\r|\n|\s/) {
1506 &http_error(500, "Invalid username",
1507 "Username contains invalid characters");
1509 if ($in{'pass'} =~ /\r|\n/) {
1510 &http_error(500, "Invalid password",
1511 "Password contains invalid characters");
1514 local ($vu, $expired, $nonexist) =
1515 &validate_user($in{'user'}, $in{'pass'}, $host);
1516 local $hrv = &handle_login(
1517 $vu || $in{'user'}, $vu ? 1 : 0,
1518 $expired, $nonexist, $in{'pass'},
1519 $in{'notestingcookie'});
1520 return $hrv if (defined($hrv));
1524 # Check for a visit to the special PAM login page
1525 if ($config{'session'} && !$deny_authentication &&
1526 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1528 # A question has been entered .. submit it to the main process
1529 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1530 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1531 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1532 &http_error(500, "Invalid response",
1533 "Response contains invalid characters");
1537 # Start of a new conversation - answer must be username
1538 $cid = &generate_random_id($in{'answer'});
1539 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1542 # A response to a previous question
1544 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1547 # Read back the response, and the next question (if any)
1548 local $line = <$PASSOUTr>;
1549 $line =~ s/\r|\n//g;
1550 local ($rv, $question) = split(/\s+/, $line, 2);
1553 local $hrv = &handle_login(
1554 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1557 return $hrv if (defined($hrv));
1559 elsif ($rv == 1 || $rv == 3) {
1560 # Another question .. force use of PAM CGI
1563 $querystring .= "&cid=$cid&question=".
1565 $querystring .= "&password=1" if ($rv == 3);
1567 $page = $config{'pam_login'};
1568 $miniserv_internal = 1;
1572 # Got back a final ok or failure
1573 local ($user, $ok, $expired, $nonexist) =
1574 split(/\s+/, $question);
1575 local $hrv = &handle_login(
1576 $user, $ok, $expired, $nonexist, undef,
1577 $in{'notestingcookie'});
1578 return $hrv if (defined($hrv));
1581 # A message from PAM .. tell the user
1584 $querystring .= "&cid=$cid&message=".
1587 $page = $config{'pam_login'};
1588 $miniserv_internal = 1;
1593 # Check for a visit to the special password change page
1594 if ($config{'session'} && !$deny_authentication &&
1595 $page eq $config{'password_change'} && !$validated) {
1596 # Just let this slide ..
1598 $miniserv_internal = 3;
1601 # Check for an existing session
1602 if ($config{'session'} && !$validated) {
1603 if ($already_session_id) {
1604 $session_id = $already_session_id;
1605 $authuser = $already_authuser;
1608 elsif (!$deny_authentication &&
1609 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1611 local $notimeout = $in{'webmin_notimeout'} ? 1 : 0;
1612 print $PASSINw "verify $session_id $notimeout\n";
1613 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1615 # Valid session continuation
1618 #$already_session_id = $session_id;
1619 $already_authuser = $authuser;
1626 # Invalid session ID .. don't set verified
1631 # Check for local authentication
1632 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1633 if (defined($users{$localauth_user})) {
1634 # Local user exists in webmin users file
1636 $authuser = $localauth_user;
1639 # Check if local user is allowed by unixauth
1640 local @can = &can_user_login($localauth_user,
1644 $authuser = $localauth_user;
1647 $localauth_user = undef;
1653 # Check if this path allows anonymous access
1655 foreach $a (keys %anonymous) {
1656 if (substr($simple, 0, length($a)) eq $a) {
1657 # It does! Auth as the user, if IP access
1658 # control allows him.
1659 if (&check_user_ip($anonymous{$a}) &&
1660 &check_user_time($anonymous{$a})) {
1662 $baseauthuser = $authuser =
1670 # Check if this path allows unauthenticated access
1671 local ($u, $unauth);
1672 foreach $u (@unauth) {
1673 $unauth++ if ($simple =~ /$u/);
1675 if (!$bogus && $unauth) {
1676 # Unauthenticated directory or file request - approve it
1678 $baseauthuser = $authuser = undef;
1683 if ($blocked == 0) {
1684 # No password given.. ask
1685 if ($config{'pam_conv'} && $use_pam) {
1686 # Force CGI for PAM question, starting with
1687 # the username which is always needed
1690 $querystring .= "&initial=1&question=".
1691 &urlize("Username");
1692 $querystring .= "&failed=$failed_user" if ($failed_user);
1693 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1695 $page = $config{'pam_login'};
1696 $miniserv_internal = 1;
1699 elsif ($config{'session'}) {
1700 # Force CGI for session login
1703 $querystring .= "&logout=1&page=/";
1706 # Re-direct to current module only
1707 local $rpage = $request_uri;
1708 if (!$config{'loginkeeppage'}) {
1709 $rpage =~ s/\?.*$//;
1710 $rpage =~ s/[^\/]+$//
1712 $querystring = "page=".&urlize($rpage);
1715 $querystring .= "&failed=$failed_user" if ($failed_user);
1716 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1718 $page = $config{'session_login'};
1719 $miniserv_internal = 1;
1723 # Ask for login with HTTP authentication
1724 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1725 &write_data("Date: $datestr\r\n");
1726 &write_data("Server: $config{'server'}\r\n");
1727 &write_data("WWW-authenticate: Basic ".
1728 "realm=\"$config{'realm'}\"\r\n");
1729 &write_keep_alive(0);
1730 &write_data("Content-type: text/html\r\n");
1731 &write_data("\r\n");
1732 &reset_byte_count();
1733 &write_data("<html>\n");
1734 &write_data("<head><title>Unauthorized</title></head>\n");
1735 &write_data("<body><h1>Unauthorized</h1>\n");
1736 &write_data("A password is required to access this\n");
1737 &write_data("web server. Please try again. <p>\n");
1738 &write_data("</body></html>\n");
1739 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1743 elsif ($blocked == 1) {
1744 # when the host has been blocked, give it an error
1745 &http_error(403, "Access denied for $acptip. The host ".
1746 "has been blocked because of too ".
1747 "many authentication failures.");
1749 elsif ($blocked == 2) {
1750 # when the user has been blocked, give it an error
1751 &http_error(403, "Access denied. The user ".
1752 "has been blocked because of too ".
1753 "many authentication failures.");
1757 # Get the real Webmin username
1758 local @can = &can_user_login($authuser, undef, $host);
1759 $baseauthuser = $can[3] || $authuser;
1761 if ($config{'remoteuser'} && !$< && $validated) {
1762 # Switch to the UID of the remote user (if he exists)
1763 local @u = getpwnam($authuser);
1764 if (@u && $< != $u[2]) {
1765 $( = $u[3]; $) = "$u[3] $u[3]";
1766 ($>, $<) = ($u[2], $u[2]);
1769 &http_error(500, "Unix user $authuser does not exist");
1775 # Check per-user IP access control
1776 if (!&check_user_ip($baseauthuser)) {
1777 &http_error(403, "Access denied for $acptip for $baseauthuser");
1781 # Check per-user allowed times
1782 if (!&check_user_time($baseauthuser)) {
1783 &http_error(403, "Access denied at the current time");
1788 # Validate the path, and convert to canonical form
1790 $simple = &simplify_path($page, $bogus);
1791 print DEBUG "handle_request: page=$page simple=$simple\n";
1793 &http_error(400, "Invalid path");
1796 # Check for a DAV request
1798 return &handle_dav_request($davpath);
1801 # Work out the active theme(s)
1802 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1803 $config{'mobile_preroot'} :
1804 $authuser && defined($config{'preroot_'.$authuser}) ?
1805 $config{'preroot_'.$authuser} :
1806 $authuser && $baseauthuser &&
1807 defined($config{'preroot_'.$baseauthuser}) ?
1808 $config{'preroot_'.$baseauthuser} :
1810 local @preroots = reverse(split(/\s+/, $preroots));
1812 # Canonicalize the directories
1813 foreach my $preroot (@preroots) {
1814 # Always under the current webmin root
1815 $preroot =~ s/^.*\///g;
1816 $preroot = $roots[0].'/'.$preroot;
1819 # Look in the theme root directories first
1820 local ($full, @stfull);
1822 foreach my $preroot (@preroots) {
1825 $full = $preroot.$sofar;
1826 $scriptname = $simple;
1827 foreach $b (split(/\//, $simple)) {
1828 if ($b ne "") { $sofar .= "/$b"; }
1829 $full = $preroot.$sofar;
1830 @stfull = stat($full);
1831 if (!@stfull) { undef($full); last; }
1833 # Check if this is a directory
1835 # It is.. go on parsing
1843 # Check if this is a CGI program
1844 if (&get_type($full) eq "internal/cgi") {
1845 $pathinfo = substr($simple, length($sofar));
1846 $pathinfo .= "/" if ($page =~ /\/$/);
1847 $scriptname = $sofar;
1852 # Don't stop at a directory unless this is the last theme, which
1853 # is the 'real' one that provides the .cgi scripts
1854 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1861 $cgi_pwd = $roots[0];
1863 elsif ($is_directory) {
1864 $cgi_pwd = "$roots[0]$sofar";
1867 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1870 $foundroot = $preroot;
1871 if ($is_directory) {
1872 # Check for index files in the directory
1874 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1875 $idxfull = "$full/$idx";
1876 local @stidxfull = stat($idxfull);
1877 if (-r _ && !-d _) {
1879 @stfull = @stidxfull;
1882 if ($scriptname ne "/");
1887 @stfull = stat($full) if (!$foundidx);
1890 last if ($foundroot);
1892 print DEBUG "handle_request: initial full=$full\n";
1894 # Look in the real root directories, stopping when we find a file or directory
1895 if (!$full || $is_directory) {
1896 ROOT: foreach $root (@roots) {
1898 $full = $root.$sofar;
1899 $scriptname = $simple;
1900 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
1901 if ($b ne "") { $sofar .= "/$b"; }
1902 $full = $root.$sofar;
1903 @stfull = stat($full);
1908 # Check if this is a directory
1910 # It is.. go on parsing
1914 # Check if this is a CGI program
1915 if (&get_type($full) eq "internal/cgi") {
1916 $pathinfo = substr($simple, length($sofar));
1917 $pathinfo .= "/" if ($page =~ /\/$/);
1918 $scriptname = $sofar;
1923 # Run CGI in the same directory as whatever file
1925 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
1934 if (!@stfull) { &http_error(404, "File not found"); }
1936 print DEBUG "handle_request: full=$full\n";
1937 @stfull = stat($full) if (!@stfull);
1939 # check filename against denyfile regexp
1940 local $denyfile = $config{'denyfile'};
1941 if ($denyfile && $full =~ /$denyfile/) {
1942 &http_error(403, "Access denied to $page");
1946 # Reached the end of the path OK.. see what we've got
1948 # See if the URL ends with a / as it should
1949 print DEBUG "handle_request: found a directory\n";
1950 if ($page !~ /\/$/) {
1951 # It doesn't.. redirect
1952 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1953 $ssl = $use_ssl || $config{'inetd_ssl'};
1954 $portstr = $port == 80 && !$ssl ? "" :
1955 $port == 443 && $ssl ? "" : ":$port";
1956 &write_data("Date: $datestr\r\n");
1957 &write_data("Server: $config{server}\r\n");
1958 $prot = $ssl ? "https" : "http";
1959 &write_data("Location: $prot://$host$portstr$page/\r\n");
1960 &write_keep_alive(0);
1961 &write_data("\r\n");
1962 &log_request($acpthost, $authuser, $reqline, 302, 0);
1965 # A directory.. check for index files
1967 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1968 $idxfull = "$full/$idx";
1969 @stidxfull = stat($idxfull);
1970 if (-r _ && !-d _) {
1973 @stfull = @stidxfull;
1974 $scriptname .= "/" if ($scriptname ne "/");
1979 @stfull = stat($full) if (!$foundidx);
1982 # This is definately a directory.. list it
1983 print DEBUG "handle_request: listing directory\n";
1984 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
1985 "Date: $datestr\r\n".
1986 "Server: $config{server}\r\n".
1987 "Content-type: text/html\r\n";
1989 &write_keep_alive(0);
1990 &write_data("\r\n");
1991 &reset_byte_count();
1992 &write_data("<h1>Index of $simple</h1>\n");
1993 &write_data("<pre>\n");
1994 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
1995 "Name", "Last Modified", "Size");
1996 &write_data("<hr>\n");
1997 opendir(DIR, $full);
1998 while($df = readdir(DIR)) {
1999 if ($df =~ /^\./) { next; }
2000 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2001 (@stbuf = stat($fulldf)) || next;
2002 if (-d _) { $df .= "/"; }
2003 @tm = localtime($stbuf[9]);
2004 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2005 $tm[3],$tm[4]+1,$tm[5]+1900,
2006 $tm[0],$tm[1],$tm[2];
2007 $len = length($df); $rest = " "x(35-$len);
2009 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2010 $df, $df, $fdate, $stbuf[7]);
2013 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2017 # CGI or normal file
2019 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2020 # A CGI program to execute
2021 print DEBUG "handle_request: executing CGI\n";
2022 $envtz = $ENV{"TZ"};
2023 $envuser = $ENV{"USER"};
2024 $envpath = $ENV{"PATH"};
2025 $envlang = $ENV{"LANG"};
2026 $envroot = $ENV{"SystemRoot"};
2027 $envperllib = $ENV{'PERLLIB'};
2028 foreach my $k (keys %ENV) {
2031 $ENV{"PATH"} = $envpath if ($envpath);
2032 $ENV{"TZ"} = $envtz if ($envtz);
2033 $ENV{"USER"} = $envuser if ($envuser);
2034 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2035 $ENV{"SystemRoot"} = $envroot if ($envroot);
2036 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2037 $ENV{"HOME"} = $user_homedir;
2038 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2039 $ENV{"SERVER_NAME"} = $host;
2040 $ENV{"SERVER_ADMIN"} = $config{"email"};
2041 $ENV{"SERVER_ROOT"} = $roots[0];
2042 $ENV{"SERVER_REALROOT"} = $realroot;
2043 $ENV{"SERVER_PORT"} = $port;
2044 $ENV{"REMOTE_HOST"} = $acpthost;
2045 $ENV{"REMOTE_ADDR"} = $acptip;
2046 $ENV{"REMOTE_USER"} = $authuser;
2047 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2048 $baseauthuser : undef;
2049 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2050 $config{'pass_password'});
2051 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2052 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2053 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2054 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2055 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2056 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2057 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2058 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2059 $ENV{"REQUEST_METHOD"} = $method;
2060 $ENV{"SCRIPT_NAME"} = $scriptname;
2061 $ENV{"SCRIPT_FILENAME"} = $full;
2062 $ENV{"REQUEST_URI"} = $request_uri;
2063 $ENV{"PATH_INFO"} = $pathinfo;
2065 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2066 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2068 $ENV{"QUERY_STRING"} = $querystring;
2069 $ENV{"MINISERV_CONFIG"} = $config_file;
2070 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2071 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2072 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2073 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2074 if (defined($header{"content-length"})) {
2075 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2077 if (defined($header{"content-type"})) {
2078 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2080 foreach $h (keys %header) {
2081 ($hname = $h) =~ tr/a-z/A-Z/;
2083 $ENV{"HTTP_$hname"} = $header{$h};
2085 $ENV{"PWD"} = $cgi_pwd;
2086 foreach $k (keys %config) {
2087 if ($k =~ /^env_(\S+)$/) {
2088 $ENV{$1} = $config{$k};
2091 delete($ENV{'HTTP_AUTHORIZATION'});
2092 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2093 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2095 # Check if the CGI can be handled internally
2097 local $first = <CGI>;
2099 $first =~ s/[#!\r\n]//g;
2100 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2102 if (!$config{'forkcgis'} &&
2103 ($first eq $perl_path || $first eq $linked_perl_path) &&
2105 $config{'internalcgis'}) {
2106 # setup environment for eval
2108 @ARGV = split(/\s+/, $queryargs);
2111 # Already read the post input
2112 $postinput = $posted_data;
2114 $clen = $header{"content-length"};
2115 $SIG{'CHLD'} = 'DEFAULT';
2117 # Have SOCK closed if the perl exec's something
2119 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2123 if ($config{'log'}) {
2124 open(MINISERVLOG, ">>$config{'logfile'}");
2125 if ($config{'logperms'}) {
2126 chmod(oct($config{'logperms'}),
2127 $config{'logfile'});
2130 chmod(0600, $config{'logfile'});
2134 $main_process_id = $$;
2136 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2137 # Eval in package from Webmin module name
2139 $pkg =~ s/[^A-Za-z0-9]/_/g;
2144 tie(*STDOUT, 'miniserv');
2145 tie(*STDIN, 'miniserv');
2146 do \$miniserv::full;
2152 &http_error(500, "Perl execution failed",
2153 $config{'noshowstderr'} ? undef : $@);
2155 elsif (!$doneheaders && !$nph_script) {
2156 &http_error(500, "Missing Headers");
2163 # fork the process that actually executes the CGI
2164 pipe(CGIINr, CGIINw);
2165 pipe(CGIOUTr, CGIOUTw);
2166 pipe(CGIERRr, CGIERRw);
2167 if (!($cgipid = fork())) {
2168 @execargs = ( $full, split(/\s+/, $queryargs) );
2171 open(STDIN, "<&CGIINr");
2172 open(STDOUT, ">&CGIOUTw");
2173 open(STDERR, ">&CGIERRw");
2174 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2176 die "Failed to exec $full : $!\n";
2179 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2182 # write CGI input to a temp file
2183 $infile = "$config{'tempbase'}.$$";
2184 open(CGIINw, ">$infile");
2185 # NOT binary mode, as CGIs don't read in it!
2190 # already read the posted data
2191 print CGIINw $posted_data;
2193 $clen = $header{"content-length"};
2194 if ($method eq "POST" && $clen_read < $clen) {
2195 $SIG{'PIPE'} = 'IGNORE';
2197 while($got < $clen) {
2198 $buf = &read_data($clen-$got);
2199 if (!length($buf)) {
2200 kill('TERM', $cgipid);
2201 unlink($infile) if ($infile);
2202 &http_error(500, "Failed to read ".
2205 $got += length($buf);
2206 local ($wrote) = (print CGIINw $buf);
2209 # If the CGI terminated early, we still need to read
2210 # from the browser and throw away
2211 while($got < $clen) {
2212 $buf = &read_data($clen-$got);
2213 if (!length($buf)) {
2214 kill('TERM', $cgipid);
2215 unlink($infile) if ($infile);
2216 &http_error(500, "Failed to read ".
2219 $got += length($buf);
2221 $SIG{'PIPE'} = 'DEFAULT';
2227 # Run the CGI program, and feed it input
2229 local $qqueryargs = join(" ", map { "\"$_\"" }
2230 split(/\s+/, $queryargs));
2231 if ($first =~ /(perl|perl.exe)$/i) {
2232 # On Windows, run with Perl
2233 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2236 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2242 # read back cgi headers
2243 select(CGIOUTr); $|=1; select(STDOUT);
2247 $line =~ s/\r|\n//g;
2249 if ($got_blank || %cgiheader) { last; }
2253 if ($line !~ /^(\S+):\s+(.*)$/) {
2254 $errs = &read_errors(CGIERRr);
2255 close(CGIOUTr); close(CGIERRr);
2256 unlink($infile) if ($infile);
2257 &http_error(500, "Bad Header", $errs);
2259 $cgiheader{lc($1)} = $2;
2260 push(@cgiheader, [ $1, $2 ]);
2262 if ($cgiheader{"location"}) {
2263 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2264 &write_data("Date: $datestr\r\n");
2265 &write_data("Server: $config{'server'}\r\n");
2266 &write_keep_alive(0);
2267 # ignore the rest of the output. This is a hack,
2268 # but is necessary for IE in some cases :(
2269 close(CGIOUTr); close(CGIERRr);
2271 elsif ($cgiheader{"content-type"} eq "") {
2272 close(CGIOUTr); close(CGIERRr);
2273 unlink($infile) if ($infile);
2274 $errs = &read_errors(CGIERRr);
2275 &http_error(500, "Missing Content-Type Header",
2276 $config{'noshowstderr'} ? undef : $errs);
2279 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2280 &write_data("Date: $datestr\r\n");
2281 &write_data("Server: $config{'server'}\r\n");
2282 &write_keep_alive(0);
2284 foreach $h (@cgiheader) {
2285 &write_data("$h->[0]: $h->[1]\r\n");
2287 &write_data("\r\n");
2289 &reset_byte_count();
2290 while($line = <CGIOUTr>) {
2295 unlink($infile) if ($infile);
2301 print DEBUG "handle_request: outputting file\n";
2302 open(FILE, $full) || &http_error(404, "Failed to open file");
2304 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2305 "Date: $datestr\r\n".
2306 "Server: $config{server}\r\n".
2307 "Content-type: ".&get_type($full)."\r\n".
2308 "Content-length: $stfull[7]\r\n".
2309 "Last-Modified: ".&http_date($stfull[9])."\r\n".
2310 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2312 $rv = &write_keep_alive();
2313 &write_data("\r\n");
2314 &reset_byte_count();
2315 while(read(FILE, $buf, 1024) > 0) {
2322 &log_request($acpthost, $authuser, $reqline,
2323 $logged_code ? $logged_code :
2324 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2328 # http_error(code, message, body, [dontexit])
2331 local $eh = $error_handler_recurse ? undef :
2332 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2333 $config{'error_handler'} ? $config{'error_handler'} : undef;
2334 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2336 # Call a CGI program for the error
2338 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2339 "&body=".&urlize($_[2]);
2340 $error_handler_recurse++;
2342 $ok_message = $_[1];
2346 # Use the standard error message display
2347 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2348 &write_data("Server: $config{server}\r\n");
2349 &write_data("Date: $datestr\r\n");
2350 &write_data("Content-type: text/html\r\n");
2351 &write_keep_alive(0);
2352 &write_data("\r\n");
2353 &reset_byte_count();
2354 &write_data("<h1>Error - $_[1]</h1>\n");
2356 &write_data("<pre>$_[2]</pre>\n");
2359 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2361 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2368 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2374 return "text/plain";
2377 # simplify_path(path, bogus)
2378 # Given a path, maybe containing stuff like ".." and "." convert it to a
2379 # clean, absolute form.
2382 local($dir, @bits, @fixedbits, $b);
2384 $dir =~ s/\\/\//g; # fix windows \ in path
2387 $dir =~ s/\0//g; # remove null bytes
2388 @bits = split(/\/+/, $dir);
2391 foreach $b (@bits) {
2395 elsif ($b eq ".." || $b eq "...") {
2397 if (scalar(@fixedbits) == 0) {
2405 push(@fixedbits, $b);
2408 return "/" . join('/', @fixedbits);
2412 # Converts a string from base64 format to normal
2415 local($str) = $_[0];
2417 $str =~ tr|A-Za-z0-9+=/||cd;
2419 $str =~ tr|A-Za-z0-9+/| -_|;
2420 while ($str =~ /(.{1,60})/gs) {
2421 my $len = chr(32 + length($1)*3/4);
2422 $res .= unpack("u", $len . $1 );
2427 # ip_match(remoteip, localip, [match]+)
2428 # Checks an IP address against a list of IPs, networks and networks/masks
2431 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2432 @io = split(/\./, $_[0]);
2433 for($i=2; $i<@_; $i++) {
2434 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2436 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2437 $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
2438 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2439 $ip_match_cache{$_[0]} = $hn;
2441 for($i=2; $i<@_; $i++) {
2442 local $mismatch = 0;
2443 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2444 # Convert CIDR to netmask format
2445 $_[$i] = $1."/".&prefix_to_mask($2);
2447 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2448 # Compare with network/mask
2449 @mo = split(/\./, $1); @ms = split(/\./, $2);
2450 for($j=0; $j<4; $j++) {
2451 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2456 elsif ($_[$i] =~ /^\*(\S+)$/) {
2457 # Compare with hostname regexp
2458 $mismatch = 1 if ($hn !~ /$1$/);
2460 elsif ($_[$i] eq 'LOCAL') {
2461 # Compare with local network
2462 local @lo = split(/\./, $_[1]);
2464 $mismatch = 1 if ($lo[0] != $io[0]);
2466 elsif ($lo[0] < 192) {
2467 $mismatch = 1 if ($lo[0] != $io[0] ||
2471 $mismatch = 1 if ($lo[0] != $io[0] ||
2476 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2477 # Compare with hostname
2478 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2481 # Compare with IP or network
2482 @mo = split(/\./, $_[$i]);
2483 while(@mo && !$mo[$#mo]) { pop(@mo); }
2484 for($j=0; $j<@mo; $j++) {
2485 if ($mo[$j] != $io[$j]) {
2490 return 1 if (!$mismatch);
2495 # users_match(&uinfo, user, ...)
2496 # Returns 1 if a user is in a list of users and groups
2499 local $uinfo = shift(@_);
2501 local @ginfo = getgrgid($uinfo->[3]);
2503 if ($u =~ /^\@(\S+)$/) {
2504 return 1 if (&is_group_member($uinfo, $1));
2506 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2507 return (!$1 || $uinfo[2] >= $1) &&
2508 (!$2 || $uinfo[2] <= $2);
2511 return 1 if ($u eq $uinfo->[0]);
2517 # restart_miniserv()
2518 # Called when a SIGHUP is received to restart the web server. This is done
2519 # by exec()ing perl with the same command line as was originally used
2520 sub restart_miniserv
2522 print STDERR "restarting miniserv\n";
2523 &log_error("Restarting");
2525 &close_all_sockets();
2527 dbmclose(%sessiondb);
2528 kill('KILL', $logclearer) if ($logclearer);
2529 kill('KILL', $extauth) if ($extauth);
2530 exec($perl_path, $miniserv_path, @miniserv_argv);
2531 die "Failed to restart miniserv with $perl_path $miniserv_path";
2548 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2549 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/) { push(@rv, $i); }
2550 else { push(@rv, join('.', unpack("CCCC", inet_aton($i)))); }
2552 return wantarray ? @rv : $rv[0];
2555 # read_line(no-wait, no-limit)
2556 # Reads one line from SOCK or SSL
2559 local ($nowait, $nolimit) = @_;
2560 local($idx, $more, $rv);
2561 while(($idx = index($main::read_buffer, "\n")) < 0) {
2562 if (length($main::read_buffer) > 10000 && !$nolimit) {
2563 &http_error(414, "Request too long",
2564 "Received excessive line <pre>$main::read_buffer</pre>");
2567 # need to read more..
2568 &wait_for_data_error() if (!$nowait);
2570 $more = Net::SSLeay::read($ssl_con);
2573 local $ok = sysread(SOCK, $more, 1024);
2574 $more = undef if ($ok <= 0);
2578 $rv = $main::read_buffer;
2579 undef($main::read_buffer);
2582 $main::read_buffer .= $more;
2584 $rv = substr($main::read_buffer, 0, $idx+1);
2585 $main::read_buffer = substr($main::read_buffer, $idx+1);
2590 # Reads up to some amount of data from SOCK or the SSL connection
2594 if (length($main::read_buffer)) {
2595 if (length($main::read_buffer) > $_[0]) {
2596 # Return the first part of the buffer
2597 $rv = substr($main::read_buffer, 0, $_[0]);
2598 $main::read_buffer = substr($main::read_buffer, $_[0]);
2602 # Return the whole buffer
2603 $rv = $main::read_buffer;
2604 undef($main::read_buffer);
2609 # Call SSL read function
2610 return Net::SSLeay::read($ssl_con, $_[0]);
2613 # Just do a normal read
2615 sysread(SOCK, $buf, $_[0]) || return undef;
2621 # Read a line from a file handle, using sysread to get a byte at a time
2628 $got = sysread($fh, $buf, 1);
2629 last if ($got <= 0);
2631 last if ($buf eq "\n");
2636 # wait_for_data(secs)
2637 # Waits at most the given amount of time for some data on SOCK, returning
2638 # 0 if not found, 1 if some arrived.
2642 vec($rmask, fileno(SOCK), 1) = 1;
2643 local $got = select($rmask, undef, undef, $_[0]);
2644 return $got == 0 ? 0 : 1;
2647 # wait_for_data_error()
2648 # Waits 60 seconds for data on SOCK, and fails if none arrives
2649 sub wait_for_data_error
2651 local $got = &wait_for_data(60);
2653 &http_error(400, "Timeout",
2654 "Waited more than 60 seconds for request data");
2658 # write_data(data, ...)
2659 # Writes a string to SOCK or the SSL connection
2662 local $str = join("", @_);
2664 Net::SSLeay::write($ssl_con, $str);
2667 syswrite(SOCK, $str, length($str));
2669 # Intentionally introduce a small delay to avoid problems where IE reports
2670 # the page as empty / DNS failed when it get a large response too quickly!
2671 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2672 $write_data_count += length($str);
2675 # reset_byte_count()
2676 sub reset_byte_count { $write_data_count = 0; }
2679 sub byte_count { return $write_data_count; }
2681 # log_request(hostname, user, request, code, bytes)
2684 if ($config{'log'}) {
2685 local ($user, $ident, $headers);
2686 if ($config{'logident'}) {
2687 # add support for rfc1413 identity checking here
2689 else { $ident = "-"; }
2690 $user = $_[1] ? $_[1] : "-";
2691 local $dstr = &make_datestr();
2692 if (fileno(MINISERVLOG)) {
2693 seek(MINISERVLOG, 0, 2);
2696 open(MINISERVLOG, ">>$config{'logfile'}");
2697 chmod(0600, $config{'logfile'});
2699 if (defined($config{'logheaders'})) {
2700 foreach $h (split(/\s+/, $config{'logheaders'})) {
2701 $headers .= " $h=\"$header{$h}\"";
2704 elsif ($config{'logclf'}) {
2705 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2710 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2711 "$_[3] $_[4]$headers\n";
2719 local @tm = localtime(time());
2720 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2721 $tm[3], $month[$tm[4]], $tm[5]+1900,
2722 $tm[2], $tm[1], $tm[0], $timezone;
2725 # log_error(message)
2729 print STDERR "[",&make_datestr(),"] ",
2730 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2731 $page ? ( $page," : " ) : ( ),
2735 # read_errors(handle)
2736 # Read and return all input from some filehandle
2739 local($fh, $_, $rv);
2741 while(<$fh>) { $rv .= $_; }
2745 sub write_keep_alive
2748 if ($config{'nokeepalive'}) {
2749 # Keep alives have been disabled in config
2752 elsif (@childpids > $config{'maxconns'}*.8) {
2753 # Disable because nearing process limit
2757 # Keep alive specified by caller
2761 # Keep alive determined by browser
2762 $mode = $header{'connection'} =~ /keep-alive/i;
2764 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2770 kill('TERM', @childpids) if (@childpids);
2771 kill('KILL', $logclearer) if ($logclearer);
2772 kill('KILL', $extauth) if ($extauth);
2778 local @tm = gmtime($_[0]);
2779 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2780 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2781 $tm[2], $tm[1], $tm[0];
2786 my $i; bless \$i, shift;
2792 my($buf,$len,$offset) = @_;
2793 &write_to_sock(substr($buf, $offset, $len));
2800 my $buf = join(defined($,) ? $, : "", @_);
2801 $buf .= $\ if defined($\);
2802 &write_to_sock($buf);
2809 &write_to_sock(sprintf $fmt, @_);
2812 # Send back already read data while we have it, then read from SOCK
2816 my $bufref = \$_[0];
2819 if ($postpos < length($postinput)) {
2820 # Reading from already fetched array
2821 my $left = length($postinput) - $postpos;
2822 my $canread = $len > $left ? $left : $len;
2823 substr($$bufref, $offset, $canread) =
2824 substr($postinput, $postpos, $canread);
2825 $postpos += $canread;
2829 # Read from network socket
2830 local $data = &read_data($len);
2831 if ($data eq '' && $len) {
2833 print STDERR "finished reading - shutting down socket\n";
2836 substr($$bufref, $offset, length($data)) = $data;
2837 return length($data);
2843 #print STDERR "open() called - should never happen!\n";
2846 # Read a line of input
2850 if ($postpos < length($postinput) &&
2851 ($idx = index($postinput, "\n", $postpos)) >= 0) {
2852 # A line exists in the memory buffer .. use it
2853 my $line = substr($postinput, $postpos, $idx-$postpos+1);
2858 # Need to read from the socket
2860 if ($postpos < length($postinput)) {
2861 # Start with in-memory data
2862 $line = substr($postinput, $postpos);
2863 $postpos = length($postinput);
2865 my $nl = &read_line(0, 1);
2868 print STDERR "finished reading - shutting down socket\n";
2871 $line .= $nl if (defined($nl));
2876 # Read one character of input
2881 my $got = READ($r, \$buf, 1, 0);
2882 return $got > 0 ? $buf : undef;
2887 return fileno(SOCK);
2894 # write_to_sock(data, ...)
2899 if ($doneheaders || $miniserv::nph_script) {
2904 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
2905 if ($1 =~ /^(\S+):\s+(.*)$/) {
2906 $cgiheader{lc($1)} = $2;
2907 push(@cgiheader, [ $1, $2 ]);
2909 elsif ($1 !~ /\S/) {
2913 &http_error(500, "Bad Header");
2917 if ($cgiheader{"location"}) {
2919 "HTTP/1.0 302 Moved Temporarily\r\n");
2920 &write_data("Date: $datestr\r\n");
2921 &write_data("Server: $config{server}\r\n");
2922 &write_keep_alive(0);
2924 elsif ($cgiheader{"content-type"} eq "") {
2925 &http_error(500, "Missing Content-Type Header");
2928 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2929 &write_data("Date: $datestr\r\n");
2930 &write_data("Server: $config{server}\r\n");
2931 &write_keep_alive(0);
2933 foreach $h (@cgiheader) {
2934 &write_data("$h->[0]: $h->[1]\r\n");
2936 &write_data("\r\n");
2937 &reset_byte_count();
2938 &write_data($headers);
2946 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
2948 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
2949 $verified_client = 1 if (!$errnum);
2956 if ($doing_eval && $$ == $main_process_id) {
2957 # A CGI program called exit! This is a horrible hack to
2958 # finish up before really exiting
2961 close($PASSINw); close($PASSOUTw);
2962 &log_request($acpthost, $authuser, $reqline,
2963 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2968 # Convert a string to a form ok for putting in a URL
2970 local($tmp, $tmp2, $c);
2973 while(($c = chop($tmp)) ne "") {
2974 if ($c !~ /[A-z0-9]/) {
2975 $c = sprintf("%%%2.2X", ord($c));
2982 # validate_user(username, password, host)
2983 # Checks if some username and password are valid. Returns the modified username,
2984 # the expired / temp pass flag, and the non-existence flag
2987 local ($user, $pass, $host) = @_;
2988 return ( ) if (!$user);
2989 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
2990 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
2991 &can_user_login($user, undef, $host);
2992 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
2994 # User doesn't even exist, so go no further
2995 return ( undef, 0, 1 );
2997 elsif ($canmode == 0) {
2998 # User does exist but cannot login
2999 return ( $canuser, 0, 0 );
3001 elsif ($canmode == 1) {
3002 # Attempt Webmin authentication
3003 if ($users{$webminuser} eq
3004 &password_crypt($pass, $users{$webminuser})) {
3005 # Password is valid .. but check for expiry
3006 local $lc = $lastchanges{$user};
3007 if ($config{'pass_maxdays'} && $lc && !$nochange{$user}) {
3008 local $daysold = (time() - $lc)/(24*60*60);
3009 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$temppass{$user}\n";
3010 if ($config{'pass_lockdays'} &&
3011 $daysold > $config{'pass_lockdays'}) {
3012 # So old that the account is locked
3013 return ( undef, 0, 0 );
3015 elsif ($daysold > $config{'pass_maxdays'}) {
3016 # Password has expired
3017 return ( $user, 1, 0 );
3020 if ($temppass{$user}) {
3021 # Temporary password - force change now
3022 return ( $user, 2, 0 );
3024 return ( $user, 0, 0 );
3027 return ( undef, 0, 0 );
3030 elsif ($canmode == 2 || $canmode == 3) {
3031 # Attempt PAM or passwd file authentication
3032 local $val = &validate_unix_user($canuser, $pass);
3033 print DEBUG "validate_user: unix val=$val\n";
3034 if ($val && $sudo) {
3035 # Need to check if this Unix user can sudo
3036 if (!&check_sudo_permissions($canuser, $pass)) {
3037 print DEBUG "validate_user: sudo failed\n";
3041 print DEBUG "validate_user: sudo passed\n";
3044 return $val == 2 ? ( $canuser, 1, 0 ) :
3045 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3047 elsif ($canmode == 4) {
3048 # Attempt external authentication
3049 return &validate_external_user($canuser, $pass) ?
3050 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3058 # validate_unix_user(user, password)
3059 # Returns 1 if a username and password are valid under unix, 0 if not,
3060 # or 2 if the account has expired.
3061 # Checks PAM if available, and falls back to reading the system password
3063 sub validate_unix_user
3067 $pam_username = $_[0];
3068 $pam_password = $_[1];
3069 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3072 local $pam_ret = $pamh->pam_authenticate();
3073 if ($pam_ret == PAM_SUCCESS()) {
3074 # Logged in OK .. make sure password hasn't expired
3075 local $acct_ret = $pamh->pam_acct_mgmt();
3076 if ($acct_ret == PAM_SUCCESS()) {
3077 $pamh->pam_open_session();
3080 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3081 $acct_ret == PAM_ACCT_EXPIRED()) {
3085 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3092 elsif ($config{'pam_only'}) {
3093 # Pam is not available, but configuration forces it's use!
3096 elsif ($config{'passwd_file'}) {
3097 # Check in a password file
3099 open(FILE, $config{'passwd_file'});
3100 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3101 # Assume in AIX format
3104 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3106 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3107 $rv = $1 eq &password_crypt($_[1], $1) ?
3115 # Read the system password or shadow file
3117 local @l = split(/:/, $_, -1);
3118 local $u = $l[$config{'passwd_uindex'}];
3119 local $p = $l[$config{'passwd_pindex'}];
3121 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3122 if ($config{'passwd_cindex'} ne '' && $rv) {
3123 # Password may have expired!
3124 local $c = $l[$config{'passwd_cindex'}];
3125 local $m = $l[$config{'passwd_mindex'}];
3126 local $day = time()/(24*60*60);
3127 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3133 if ($p eq "" && $config{'passwd_blank'}) {
3134 # Force password change
3142 return $rv if ($rv);
3145 # Fallback option - check password returned by getpw*
3146 local @uinfo = getpwnam($_[0]);
3147 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3151 return 0; # Totally failed
3154 # validate_external_user(user, pass)
3155 # Validate a user by passing the username and password to an external
3156 # squid-style authentication program
3157 sub validate_external_user
3159 return 0 if (!$config{'extauth'});
3161 local $str = "$_[0] $_[1]\n";
3162 syswrite(EXTAUTH, $str, length($str));
3163 local $resp = <EXTAUTH>;
3165 return $resp =~ /^OK/i ? 1 : 0;
3168 # can_user_login(username, no-append, host)
3169 # Checks if a user can login or not.
3170 # First return value is the username.
3171 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3172 # file, 4 if external.
3173 # Third is 1 if the user does not exist at all, 0 if he does.
3174 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3175 # Fifth is a flag indicating if a sudo check is needed.
3178 if (!$users{$_[0]}) {
3179 # See if this user exists in Unix and can be validated by the same
3180 # method as the unixauth webmin user
3181 local $realuser = $unixauth{$_[0]};
3185 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3186 if (!$realuser && @uinfo) {
3187 # No unixauth entry for the username .. try his groups
3188 foreach my $ua (keys %unixauth) {
3189 if ($ua =~ /^\@(.*)$/) {
3190 if (&is_group_member(\@uinfo, $1)) {
3191 $realuser = $unixauth{$ua};
3197 if (!$realuser && @uinfo) {
3198 # Fall back to unix auth for all Unix users
3199 $realuser = $unixauth{"*"};
3201 if (!$realuser && $use_sudo && @uinfo) {
3202 # Allow login effectively as root, if sudo permits it
3206 if (!$realuser && !@uinfo && $config{'pamany'}) {
3207 # If the user completely doesn't exist, we can still allow
3208 # him to authenticate via PAM
3209 $realuser = $config{'pamany'};
3213 # For Usermin, always fall back to unix auth for any user,
3214 # so that later checks with domain added / removed are done.
3215 $realuser = $unixauth{"*"};
3217 return (undef, 0, 1, undef) if (!$realuser);
3218 local $up = $users{$realuser};
3219 return (undef, 0, 1, undef) if (!defined($up));
3221 # Work out possible domain names from the hostname
3222 local @doms = ( $_[2] );
3223 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3227 if ($config{'user_mapping'} && !defined(%user_mapping)) {
3228 # Read the user mapping file
3230 open(MAPPING, $config{'user_mapping'});
3234 if (/^(\S+)\s+(\S+)/) {
3235 if ($config{'user_mapping_reverse'}) {
3236 $user_mapping{$1} = $2;
3239 $user_mapping{$2} = $1;
3246 # Check the user mapping file to see if there is an entry for the
3247 # user login in which specifies a new effective user
3249 foreach my $d (@doms) {
3250 $um ||= $user_mapping{"$_[0]\@$d"};
3252 $um ||= $user_mapping{$_[0]};
3253 if (defined($um) && ($_[1]&4) == 0) {
3254 # A mapping exists - use it!
3255 return &can_user_login($um, $_[1]+4, $_[2]);
3258 # Check if a user with the entered login and the domains appended
3259 # or prepended exists, and if so take it to be the effective user
3260 if (!@uinfo && $config{'domainuser'}) {
3261 # Try again with name.domain and name.firstpart
3262 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3263 if (($_[1]&1) == 0) {
3265 foreach $a (@firsts, @doms) {
3266 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3267 "${a}.$_[0]", "${a}-$_[0]",
3268 "$_[0]_${a}", "${a}_$_[0]") {
3269 local @vu = &can_user_login(
3270 $p, $_[1]+1, $_[2]);
3271 return @vu if ($vu[1]);
3277 # Check if the user entered a domain at the end of his username when
3278 # he really shouldn't have, and if so try without it
3279 if (!@uinfo && $config{'domainstrip'} &&
3280 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3281 local ($stripped, $dom) = ($1, $2);
3282 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3283 return @vu if ($vu[1]);
3284 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3285 return @vu if ($vu[1]);
3288 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3291 if (defined(@allowusers)) {
3292 # Only allow people on the allow list
3293 return ( undef, 0, 0, undef )
3294 if (!&users_match(\@uinfo, @allowusers));
3296 elsif (defined(@denyusers)) {
3297 # Disallow people on the deny list
3298 return ( undef, 0, 0, undef )
3299 if (&users_match(\@uinfo, @denyusers));
3301 if ($config{'shells_deny'}) {
3303 open(SHELLS, $config{'shells_deny'});
3307 $found++ if ($_ eq $uinfo[8]);
3310 return ( undef, 0, 0, undef ) if (!$found);
3315 # PAM or passwd file authentication
3316 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3318 elsif ($up eq 'e') {
3319 # External authentication
3320 return ( $_[0], 4, 0, $realuser, $sudo );
3323 # Fixed Webmin password
3324 return ( $_[0], 1, 0, $realuser, $sudo );
3327 elsif ($users{$_[0]} eq 'x') {
3328 # Webmin user authenticated via PAM or password file
3329 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3331 elsif ($users{$_[0]} eq 'e') {
3332 # Webmin user authenticated externally
3333 return ( $_[0], 4, 0, $_[0] );
3336 # Normal Webmin user
3337 return ( $_[0], 1, 0, $_[0] );
3341 # the PAM conversation function for interactive logins
3344 $pam_conv_func_called++;
3351 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3352 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3354 push @res, PAM_SUCCESS();
3357 push @res, PAM_SUCCESS();
3366 # get_socket_name(handle)
3367 # Returns the local hostname or IP address of some connection
3370 return $config{'host'} if ($config{'host'});
3371 local $sn = getsockname($_[0]);
3372 return undef if (!$sn);
3373 local $myaddr = (unpack_sockaddr_in($sn))[1];
3374 if (!$get_socket_name_cache{$myaddr}) {
3376 if (!$config{'no_resolv_myname'}) {
3377 $myname = gethostbyaddr($myaddr, AF_INET);
3379 if ($myname eq "") {
3380 $myname = inet_ntoa($myaddr);
3382 $get_socket_name_cache{$myaddr} = $myname;
3384 return $get_socket_name_cache{$myaddr};
3387 # run_login_script(username, sid, remoteip, localip)
3388 sub run_login_script
3390 if ($config{'login_script'}) {
3391 system($config{'login_script'}.
3392 " ".join(" ", map { quotemeta($_) } @_).
3393 " >/dev/null 2>&1 </dev/null");
3397 # run_logout_script(username, sid, remoteip, localip)
3398 sub run_logout_script
3400 if ($config{'logout_script'}) {
3401 system($config{'logout_script'}.
3402 " ".join(" ", map { quotemeta($_) } @_).
3403 " >/dev/null 2>&1 </dev/null");
3407 # close_all_sockets()
3408 # Closes all the main listening sockets
3409 sub close_all_sockets
3412 foreach $s (@socketfhs) {
3418 # Close all pipes for talking to sub-processes
3422 foreach $p (@passin) { close($p); }
3423 foreach $p (@passout) { close($p); }
3424 foreach $p (values %conversations) {
3425 if ($p->{'PAMOUTr'}) {
3426 close($p->{'PAMOUTr'});
3427 close($p->{'PAMINw'});
3432 # check_user_ip(user)
3433 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3437 &ip_match($acptip, $localip, @{$deny{$_[0]}}) ||
3439 !&ip_match($acptip, $localip, @{$allow{$_[0]}})) {
3445 # check_user_time(user)
3446 # Returns 1 if some user is allowed to login at the current date and time
3449 return 1 if (!$allowdays{$_[0]} && !$allowhours{$_[0]});
3450 local @tm = localtime(time());
3451 if ($allowdays{$_[0]}) {
3452 # Make sure day is allowed
3453 return 0 if (&indexof($tm[6], @{$allowdays{$_[0]}}) < 0);
3455 if ($allowhours{$_[0]}) {
3456 # Make sure time is allowed
3457 local $m = $tm[2]*60+$tm[1];
3458 return 0 if ($m < $allowhours{$_[0]}->[0] ||
3459 $m > $allowhours{$_[0]}->[1]);
3464 # generate_random_id(password, [force-urandom])
3465 # Returns a random session ID number
3466 sub generate_random_id
3468 local ($pass, $force_urandom) = @_;
3470 if (!$bad_urandom) {
3471 # First try /dev/urandom, unless we have marked it as bad
3472 $SIG{ALRM} = "miniserv::urandom_timeout";
3474 if (open(RANDOM, "/dev/urandom")) {
3476 if (read(RANDOM, $tmpsid, 16) == 16) {
3477 $sid = lc(unpack('h*',$tmpsid));
3483 if (!$sid && !$force_urandom) {
3486 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3487 $sid += ord($c) * $mul;
3494 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3495 # Called from handle_session to either mark a user as logged in, or not
3498 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3499 $authuser = $vu if ($ok);
3501 # check if the test cookie is set
3502 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3503 !$config{'no_testing_cookie'} && !$notest) {
3504 &http_error(500, "No cookies",
3505 "Your browser does not support cookies, ".
3506 "which are required for this web server to ".
3507 "work in session authentication mode");
3510 # check with main process for delay
3511 if ($config{'passdelay'} && $vu) {
3512 print $PASSINw "delay $vu $acptip $ok\n";
3513 <$PASSOUTr> =~ /(\d+) (\d+)/;
3518 if ($ok && (!$expired ||
3519 $config{'passwd_mode'} == 1)) {
3520 # Logged in OK! Tell the main process about
3522 local $sid = &generate_random_id($pass);
3523 print $PASSINw "new $sid $authuser $acptip\n";
3525 # Run the post-login script, if any
3526 &run_login_script($authuser, $sid,
3529 # Check for a redirect URL for the user
3530 local $rurl = &login_redirect($authuser, $pass, $host);
3532 # Got one .. go to it
3533 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3534 &write_data("Date: $datestr\r\n");
3535 &write_data("Server: $config{'server'}\r\n");
3536 &write_data("Location: $rurl\r\n");
3537 &write_keep_alive(0);
3538 &write_data("\r\n");
3539 &log_request($acpthost, $authuser, $reqline, 302, 0);
3542 # Set cookie and redirect to originally requested page
3543 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3544 &write_data("Date: $datestr\r\n");
3545 &write_data("Server: $config{'server'}\r\n");
3546 local $ssl = $use_ssl || $config{'inetd_ssl'};
3547 $portstr = $port == 80 && !$ssl ? "" :
3548 $port == 443 && $ssl ? "" : ":$port";
3549 $prot = $ssl ? "https" : "http";
3550 local $sec = $ssl ? "; secure" : "";
3551 #$sec .= "; httpOnly";
3553 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3556 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3558 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3559 &write_keep_alive(0);
3560 &write_data("\r\n");
3561 &log_request($acpthost, $authuser, $reqline, 302, 0);
3562 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3563 &write_login_utmp($authuser, $acpthost);
3567 elsif ($ok && $expired &&
3568 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3569 # Login was ok, but password has expired or was temporary. Need
3570 # to force display of password change form.
3573 $querystring = "&user=".&urlize($vu).
3575 "&expired=".$expired;
3578 $page = $config{'password_form'};
3580 $miniserv_internal = 2;
3581 syslog("crit", "%s",
3582 "Expired login as $vu ".
3583 "from $acpthost") if ($use_syslog);
3586 # Login failed, or password has expired. The login form will be
3587 # displayed again by later code
3589 $request_uri = $in{'page'};
3590 $already_session_id = undef;
3592 $authuser = $baseauthuser = undef;
3593 syslog("crit", "%s",
3594 ($nonexist ? "Non-existent" :
3595 $expired ? "Expired" : "Invalid").
3596 " login as $vu from $acpthost")
3602 # write_login_utmp(user, host)
3603 # Record the login by some user in utmp
3604 sub write_login_utmp
3607 # Write utmp record for login
3608 %utmp = ( 'ut_host' => $_[1],
3609 'ut_time' => time(),
3611 'ut_type' => 7, # user process
3612 'ut_pid' => $main_process_id,
3613 'ut_line' => $config{'pam'},
3615 if (defined(&User::Utmp::putut)) {
3616 User::Utmp::putut(\%utmp);
3619 User::Utmp::pututline(\%utmp);
3624 # write_logout_utmp(user, host)
3625 # Record the logout by some user in utmp
3626 sub write_logout_utmp
3629 # Write utmp record for logout
3630 %utmp = ( 'ut_host' => $_[1],
3631 'ut_time' => time(),
3633 'ut_type' => 8, # dead process
3634 'ut_pid' => $main_process_id,
3635 'ut_line' => $config{'pam'},
3637 if (defined(&User::Utmp::putut)) {
3638 User::Utmp::putut(\%utmp);
3641 User::Utmp::pututline(\%utmp);
3646 # pam_conversation_process(username, write-pipe, read-pipe)
3647 # This function is called inside a sub-process to communicate with PAM. It sends
3648 # questions down one pipe, and reads responses from another
3649 sub pam_conversation_process
3651 local ($user, $writer, $reader) = @_;
3652 $miniserv::pam_conversation_process_writer = $writer;
3653 $miniserv::pam_conversation_process_reader = $reader;
3654 local $convh = new Authen::PAM(
3655 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3656 local $pam_ret = $convh->pam_authenticate();
3657 if ($pam_ret == PAM_SUCCESS()) {
3658 local $acct_ret = $convh->pam_acct_mgmt();
3659 if ($acct_ret == PAM_SUCCESS()) {
3660 $convh->pam_open_session();
3661 print $writer "x2 $user 1 0 0\n";
3663 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3664 $acct_ret == PAM_ACCT_EXPIRED()) {
3665 print $writer "x2 $user 1 1 0\n";
3668 print $writer "x0 Unknown PAM account status $acct_ret\n";
3672 print $writer "x2 $user 0 0 0\n";
3677 # pam_conversation_process_func(type, message, [type, message, ...])
3678 # A pipe that talks to both PAM and the master process
3679 sub pam_conversation_process_func
3682 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3684 local ($type, $msg) = (shift, shift);
3686 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3687 print $miniserv::pam_conversation_process_writer "\n";
3688 local $answer = <$miniserv::pam_conversation_process_reader>;
3689 $answer =~ s/\r|\n//g;
3690 push(@rv, PAM_SUCCESS(), $answer);
3692 push(@rv, PAM_SUCCESS());
3697 # Returns 4 new pipe file handles
3700 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3702 local %taken = ( (map { $_, 1 } @passin),
3703 (map { $_->{'PASSINr'} } values %conversations) );
3704 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3705 $PASSINr = "PASSINr$p";
3706 $PASSINw = "PASSINw$p";
3707 $PASSOUTr = "PASSOUTr$p";
3708 $PASSOUTw = "PASSOUTw$p";
3709 pipe($PASSINr, $PASSINw);
3710 pipe($PASSOUTr, $PASSOUTw);
3711 select($PASSINw); $| = 1;
3712 select($PASSINr); $| = 1;
3713 select($PASSOUTw); $| = 1;
3714 select($PASSOUTw); $| = 1;
3716 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3719 # recv_pam_question(&conv, fd)
3720 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3721 # Returns 0 if the conversation is over, 1 if not.
3722 sub recv_pam_question
3724 local ($conf, $fh) = @_;
3725 local $pr = $conf->{'PAMOUTr'};
3726 select($pr); $| = 1; select(STDOUT);
3727 local $line = <$pr>;
3728 $line =~ s/\r|\n//g;
3731 $line =~ s/\r|\n//g;
3733 $conf->{'last'} = time();
3736 print $fh "0 PAM conversation error\n";
3740 local ($type, $msg) = split(/\s+/, $line, 2);
3741 if ($type =~ /^x(\d+)/) {
3742 # Pass this status code through
3743 print $fh "$1 $msg\n";
3744 return $1 == 2 || $1 == 0 ? 0 : 1;
3746 elsif ($type == PAM_PROMPT_ECHO_ON()) {
3748 print $fh "1 $msg\n";
3751 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3753 print $fh "3 $msg\n";
3756 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3757 # A message that does not require a response
3758 print $fh "4 $msg\n";
3763 print $fh "0 Unknown PAM message type $type\n";
3769 # send_pam_answer(&conv, answer)
3770 # Sends a response from the user to the PAM sub-process
3773 local ($conf, $answer) = @_;
3774 local $pw = $conf->{'PAMINw'};
3775 $conf->{'last'} = time();
3776 print $pw "$answer\n";
3779 # end_pam_conversation(&conv)
3780 # Clean up PAM conversation pipes and processes
3781 sub end_pam_conversation
3784 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
3785 if ($conv->{'PAMINr'}) {
3786 close($conv->{'PAMINr'});
3787 close($conv->{'PAMOUTr'});
3788 close($conv->{'PAMINw'});
3789 close($conv->{'PAMOUTw'});
3791 delete($conversations{$conv->{'cid'}});
3794 # get_ipkeys(&miniserv)
3795 # Returns a list of IP address to key file mappings from a miniserv.conf entry
3799 foreach $k (keys %{$_[0]}) {
3800 if ($k =~ /^ipkey_(\S+)/) {
3801 local $ipkey = { 'ips' => [ split(/,/, $1) ],
3802 'key' => $_[0]->{$k},
3803 'index' => scalar(@rv) };
3804 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
3811 # create_ssl_context(keyfile, [certfile])
3812 sub create_ssl_context
3814 local ($keyfile, $certfile) = @_;
3816 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
3817 $ssl_ctx ||= Net::SSLeay::CTX_new();
3818 $ssl_ctx || die "Failed to create SSL context : $!";
3819 if ($client_certs) {
3820 Net::SSLeay::CTX_load_verify_locations(
3821 $ssl_ctx, $config{'ca'}, "");
3822 Net::SSLeay::CTX_set_verify(
3823 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
3825 if ($config{'extracas'}) {
3827 foreach $p (split(/\s+/, $config{'extracas'})) {
3828 Net::SSLeay::CTX_load_verify_locations(
3833 Net::SSLeay::CTX_use_RSAPrivateKey_file(
3835 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
3836 Net::SSLeay::CTX_use_certificate_file(
3837 $ssl_ctx, $certfile || $keyfile,
3838 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
3843 # ssl_connection_for_ip(socket)
3844 # Returns a new SSL connection object for some socket, or undef if failed
3845 sub ssl_connection_for_ip
3848 local $sn = getsockname($sock);
3850 print STDERR "Failed to get address for socket $sock\n";
3853 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
3854 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
3855 local $ssl_con = Net::SSLeay::new($ssl_ctx);
3856 if ($config{'ssl_cipher_list'}) {
3857 # Force use of ciphers
3858 eval "Net::SSLeay::set_cipher_list(
3859 \$ssl_con, \$config{'ssl_cipher_list'})";
3861 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
3867 Net::SSLeay::set_fd($ssl_con, fileno($sock));
3868 if (!Net::SSLeay::accept($ssl_con)) {
3869 print STDERR "Failed to initialize SSL connection\n";
3875 # login_redirect(username, password, host)
3876 # Calls the login redirect script (if configured), which may output a URL to
3877 # re-direct a user to after logging in.
3880 return undef if (!$config{'login_redirect'});
3881 local $quser = quotemeta($_[0]);
3882 local $qpass = quotemeta($_[1]);
3883 local $qhost = quotemeta($_[2]);
3884 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
3889 # reload_config_file()
3890 # Re-read %config, and call post-config actions
3891 sub reload_config_file
3893 &log_error("Reloading configuration");
3894 %config = &read_config_file($config_file);
3895 &update_vital_config();
3898 &build_config_mappings();
3899 if ($config{'session'}) {
3900 dbmclose(%sessiondb);
3901 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
3905 # read_config_file(file)
3906 # Reads the given config file, and returns a hash of values
3907 sub read_config_file
3910 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
3913 if (/^#/ || !/\S/) { next; }
3915 $name = $1; $val = $2;
3916 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
3917 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
3924 # update_vital_config()
3925 # Updates %config with defaults, and dies if something vital is missing
3926 sub update_vital_config
3928 my %vital = ("port", 80,
3930 "server", "MiniServ/0.01",
3931 "index_docs", "index.html index.htm index.cgi index.php",
3932 "addtype_html", "text/html",
3933 "addtype_txt", "text/plain",
3934 "addtype_gif", "image/gif",
3935 "addtype_jpg", "image/jpeg",
3936 "addtype_jpeg", "image/jpeg",
3937 "realm", "MiniServ",
3938 "session_login", "/session_login.cgi",
3939 "pam_login", "/pam_login.cgi",
3940 "password_form", "/password_form.cgi",
3941 "password_change", "/password_change.cgi",
3945 "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\$",
3947 "expires", 7*24*60*60,
3949 foreach my $v (keys %vital) {
3951 if ($vital{$v} eq "") {
3952 die "Missing config option $v";
3954 $config{$v} = $vital{$v};
3957 if (!$config{'sessiondb'}) {
3958 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3959 $config{'sessiondb'} = "$1/sessiondb";
3961 if (!$config{'errorlog'}) {
3962 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
3963 $config{'errorlog'} = "$1/miniserv.error";
3965 if (!$config{'tempbase'}) {
3966 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3967 $config{'tempbase'} = "$1/cgitemp";
3969 if (!$config{'blockedfile'}) {
3970 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3971 $config{'blockedfile'} = "$1/blocked";
3976 # Fills the %users and %certs hashes from the users file in %config
3985 undef(%lastchanges);
3988 if ($config{'userfile'}) {
3989 open(USERS, $config{'userfile'});
3992 local @user = split(/:/, $_, -1);
3993 $users{$user[0]} = $user[1];
3994 $certs{$user[0]} = $user[3] if ($user[3]);
3995 if ($user[4] =~ /^allow\s+(.*)/) {
3996 $allow{$user[0]} = $config{'alwaysresolve'} ?
3997 [ split(/\s+/, $1) ] :
3998 [ &to_ipaddress(split(/\s+/, $1)) ];
4000 elsif ($user[4] =~ /^deny\s+(.*)/) {
4001 $deny{$user[0]} = $config{'alwaysresolve'} ?
4002 [ split(/\s+/, $1) ] :
4003 [ &to_ipaddress(split(/\s+/, $1)) ];
4005 if ($user[5] =~ /days\s+(\S+)/) {
4006 $allowdays{$user[0]} = [ split(/,/, $1) ];
4008 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4009 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4011 $lastchanges{$user[0]} = $user[6];
4012 $nochange{$user[0]} = $user[9];
4013 $temppass{$user[0]} = $user[10];
4020 # Fills %mime with entries from file in %config and extra settings in %config
4024 if ($config{"mimetypes"} ne "") {
4025 open(MIME, $config{"mimetypes"});
4028 if (/^(\S+)\s+(.*)$/) {
4030 my @exts = split(/\s+/, $2);
4031 foreach my $ext (@exts) {
4032 $mime{$ext} = $type;
4038 foreach my $k (keys %config) {
4039 if ($k !~ /^addtype_(.*)$/) { next; }
4040 $mime{$1} = $config{$k};
4044 # build_config_mappings()
4045 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4046 # redirect mapping and allow and deny lists from %config
4047 sub build_config_mappings
4049 # build anonymous access list
4051 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4052 if ($a =~ /^([^=]+)=(\S+)$/) {
4053 $anonymous{$1} = $2;
4057 # build IP access list
4059 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4060 if ($a =~ /^([^=]+)=(\S+)$/) {
4065 # build unauthenticated URLs list
4066 @unauth = split(/\s+/, $config{'unauth'});
4068 # build redirect mapping
4070 foreach my $r (split(/\s+/, $config{'redirect'})) {
4071 if ($r =~ /^([^=]+)=(\S+)$/) {
4076 # build prefixes to be stripped
4077 undef(@strip_prefix);
4078 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4079 push(@strip_prefix, $r);
4082 # Init allow and deny lists
4083 @deny = split(/\s+/, $config{"deny"});
4084 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4085 @allow = split(/\s+/, $config{"allow"});
4086 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4089 if ($config{'allowusers'}) {
4090 @allowusers = split(/\s+/, $config{'allowusers'});
4092 elsif ($config{'denyusers'}) {
4093 @denyusers = split(/\s+/, $config{'denyusers'});
4096 # Build list of unixauth mappings
4098 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4099 if ($ua =~ /^(\S+)=(\S+)$/) {
4103 $unixauth{"*"} = $ua;
4107 # Build list of non-session-auth pages
4108 undef(%sessiononly);
4109 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4110 $sessiononly{$sp} = 1;
4113 # Build list of logout times
4114 undef(@logouttimes);
4115 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4116 if ($a =~ /^([^=]+)=(\S+)$/) {
4117 push(@logouttimes, [ $1, $2 ]);
4120 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4122 # Build list of DAV pathss
4124 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4125 push(@davpaths, $d);
4127 @davusers = split(/\s+/, $config{'dav_users'});
4129 # Mobile agent substrings and hostname prefixes
4130 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4131 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4135 if ($config{'debug'}) {
4136 open(DEBUG, ">>$config{'debug'}");
4139 open(DEBUG, ">/dev/null");
4142 # Reset cache of sudo checks
4146 # is_group_member(&uinfo, groupname)
4147 # Returns 1 if some user is a primary or secondary member of a group
4150 local ($uinfo, $group) = @_;
4151 local @ginfo = getgrnam($group);
4152 return 0 if (!@ginfo);
4153 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4154 foreach my $m (split(/\s+/, $ginfo[3])) {
4155 return 1 if ($m eq $uinfo->[0]);
4160 # prefix_to_mask(prefix)
4161 # Converts a number like 24 to a mask like 255.255.255.0
4164 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4165 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4166 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4167 (256-(2 ** (8-$_[0]))).".0.0.0";
4170 # get_logout_time(user, session-id)
4171 # Given a username, returns the idle time before he will be logged out
4174 local ($user, $sid) = @_;
4175 if (!defined($logout_time_cache{$user,$sid})) {
4177 foreach my $l (@logouttimes) {
4178 if ($l->[0] =~ /^\@(.*)$/) {
4179 # Check group membership
4180 local @uinfo = getpwnam($user);
4181 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4185 elsif ($l->[0] =~ /^\//) {
4186 # Check file contents
4187 open(FILE, $l->[0]);
4204 if ($l->[0] eq $user) {
4208 last if (defined($time));
4210 $logout_time_cache{$user,$sid} = $time;
4212 return $logout_time_cache{$user,$sid};
4215 # password_crypt(password, salt)
4216 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4217 # of a password. Otherwise, do Unix crypt.
4220 local ($pass, $salt) = @_;
4221 if ($salt =~ /^\$1\$/ && $use_md5) {
4222 return &encrypt_md5($pass, $salt);
4225 return &unix_crypt($pass, $salt);
4229 # unix_crypt(password, salt)
4230 # Performs standard Unix hashing for a password
4233 local ($pass, $salt) = @_;
4234 if ($use_perl_crypt) {
4235 return Crypt::UnixCrypt::crypt($pass, $salt);
4238 return crypt($pass, $salt);
4242 # handle_dav_request(davpath)
4243 # Pass a request on to the Net::DAV::Server module
4244 sub handle_dav_request
4247 eval "use Filesys::Virtual::Plain";
4248 eval "use Net::DAV::Server";
4249 eval "use HTTP::Request";
4250 eval "use HTTP::Headers";
4252 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4253 delete $Net::DAV::Server::implemented{lock};
4254 delete $Net::DAV::Server::implemented{unlock};
4257 # Read in request data
4258 if (!$posted_data) {
4259 local $clen = $header{"content-length"};
4260 while(length($posted_data) < $clen) {
4261 $buf = &read_data($clen - length($posted_data));
4262 if (!length($buf)) {
4263 &http_error(500, "Failed to read POST request");
4265 chomp($posted_data);
4266 #$posted_data =~ s/\015$//mg;
4267 $posted_data .= $buf;
4271 # For subsequent logging
4272 open(MINISERVLOG, ">>$config{'logfile'}");
4276 local @u = getpwnam($authuser);
4277 if ($config{'dav_remoteuser'} && !$< && $validated) {
4280 $( = $u[3]; $) = "$u[3] $u[3]";
4281 ($>, $<) = ($u[2], $u[2]);
4283 if ($config{'dav_root'} eq '*') {
4288 &http_error(500, "Unix user $authuser does not exist");
4292 $root ||= $config{'dav_root'};
4295 # Check if this user can use DAV
4297 &users_match(\@u, @davusers) ||
4298 &http_error(500, "You are not allowed to access DAV");
4302 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4303 my $webdav = Net::DAV::Server->new();
4304 $webdav->filesys($filesys);
4306 # Make up a request object, and feed to DAV
4307 local $ho = HTTP::Headers->new;
4308 foreach my $h (keys %header) {
4309 next if (lc($h) eq "connection");
4310 $ho->header($h => $header{$h});
4313 $request_uri =~ s/^\Q$path\E//;
4314 $request_uri = "/" if ($request_uri eq "");
4316 my $request = HTTP::Request->new($method, $request_uri, $ho,
4318 if ($config{'dav_debug'}) {
4319 print STDERR "DAV request :\n";
4320 print STDERR "---------------------------------------------\n";
4321 print STDERR $request->as_string();
4322 print STDERR "---------------------------------------------\n";
4324 my $response = $webdav->run($request);
4326 # Send back the reply
4327 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4328 local $content = $response->content();
4330 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4331 $content =~ s|href>/<|href>$path<|g;
4333 foreach my $h ($response->header_field_names) {
4334 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4335 &write_data("$h: ",$response->header($h),"\r\n");
4337 &write_data("Content-length: ",length($content),"\r\n");
4338 local $rv = &write_keep_alive(0);
4339 &write_data("\r\n");
4340 &write_data($content);
4342 if ($config{'dav_debug'}) {
4343 print STDERR "DAV reply :\n";
4344 print STDERR "---------------------------------------------\n";
4345 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4346 foreach my $h ($response->header_field_names) {
4347 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4348 print STDERR "$h: ",$response->header($h),"\r\n";
4350 print STDERR "Content-length: ",length($content),"\r\n";
4351 print STDERR "\r\n";
4352 print STDERR $content;
4353 print STDERR "---------------------------------------------\n";
4357 &log_request($acpthost, $authuser, $reqline, $response->code(),
4358 length($response->content()));
4361 # get_system_hostname()
4362 # Returns the hostname of this system, for reporting to listeners
4363 sub get_system_hostname
4365 # On Windows, try computername environment variable
4366 return $ENV{'computername'} if ($ENV{'computername'});
4367 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4369 # If a specific command is set, use it first
4370 if ($config{'hostname_command'}) {
4371 local $out = `($config{'hostname_command'}) 2>&1`;
4378 # First try the hostname command
4379 local $out = `hostname 2>&1`;
4380 if (!$? && $out =~ /\S/) {
4385 # Try the Sys::Hostname module
4386 eval "use Sys::Hostname";
4388 local $rv = eval "hostname()";
4394 # Must use net name on Windows
4395 local $out = `net name 2>&1`;
4396 if ($out =~ /\-+\r?\n(\S+)/) {
4403 # indexof(string, array)
4404 # Returns the index of some value in an array, or -1
4407 for($i=1; $i <= $#_; $i++) {
4408 if ($_[$i] eq $_[0]) { return $i - 1; }
4414 # has_command(command)
4415 # Returns the full path if some command is in the path, undef if not
4419 if (!$_[0]) { return undef; }
4420 if (exists($has_command_cache{$_[0]})) {
4421 return $has_command_cache{$_[0]};
4424 if ($_[0] =~ /^\//) {
4425 $rv = -x $_[0] ? $_[0] : undef;
4428 local $sp = $on_windows ? ';' : ':';
4429 foreach $d (split($sp, $ENV{PATH})) {
4430 if (-x "$d/$_[0]") {
4435 foreach my $sfx (".exe", ".com", ".bat") {
4436 if (-r "$d/$_[0]".$sfx) {
4437 $rv = "$d/$_[0]".$sfx;
4444 $has_command_cache{$_[0]} = $rv;
4448 # check_sudo_permissions(user, pass)
4449 # Returns 1 if some user can run any command via sudo
4450 sub check_sudo_permissions
4452 local ($user, $pass) = @_;
4454 # First try the pipes
4456 print DEBUG "check_sudo_permissions: querying cache for $user\n";
4457 print $PASSINw "readsudo $user\n";
4458 local $can = <$PASSOUTr>;
4460 print DEBUG "check_sudo_permissions: cache said $can\n";
4461 if ($can =~ /^\d+$/ && $can != 2) {
4466 local $ptyfh = new IO::Pty;
4467 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
4469 print STDERR "Failed to create new PTY with IO::Pty\n";
4472 local @uinfo = getpwnam($user);
4474 print STDERR "Unix user $user does not exist for sudo\n";
4478 # Execute sudo in a sub-process, via a pty
4479 local $ttyfh = $ptyfh->slave();
4480 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
4481 local $tty = $ptyfh->ttyname();
4482 print DEBUG "check_sudo_permissions: tty=$tty\n";
4483 chown($uinfo[2], $uinfo[3], $tty);
4485 print DEBUG "check_sudo_permissions: about to fork..\n";
4486 local $pid = fork();
4487 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
4489 print STDERR "fork for sudo failed : $!\n";
4494 $ptyfh->make_slave_controlling_terminal();
4495 close(STDIN); close(STDOUT); close(STDERR);
4496 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
4497 close($PASSINw); close($PASSOUTr);
4498 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
4499 ($>, $<) = ($uinfo[2], $uinfo[2]);
4504 open(STDIN, "<&SUDOr");
4505 open(STDOUT, ">$tty");
4506 open(STDERR, ">&STDOUT");
4509 print "Exec failed : $!\n";
4512 print DEBUG "check_sudo_permissions: pid=$pid\n";
4514 $ptyfh->close_slave();
4516 # Send password, and get back response
4517 local $oldfh = select(SUDOw);
4520 print DEBUG "check_sudo_permissions: about to send pass\n";
4521 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
4522 print SUDOw $pass,"\n";
4523 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
4527 print DEBUG "check_sudo_permissions: got $_";
4533 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
4537 print $PASSINw "writesudo $user $ok\n";
4543 # is_mobile_useragent(agent)
4544 # Returns 1 if some user agent looks like a cellphone or other mobile device,
4546 sub is_mobile_useragent
4548 local ($agent) = @_;
4550 "UP.Link", # Openwave
4551 "Nokia", # All Nokias start with Nokia
4552 "MOT-", # All Motorola phones start with MOT-
4553 "SAMSUNG", # Samsung browsers
4554 "Samsung", # Samsung browsers
4555 "SEC-", # Samsung browsers
4556 "AU-MIC", # Samsung browsers
4557 "AUDIOVOX", # Audiovox
4558 "BlackBerry", # BlackBerry
4559 "hiptop", # Danger hiptop Sidekick
4560 "SonyEricsson", # Sony Ericsson
4561 "Ericsson", # Old Ericsson browsers , mostly WAP
4562 "Mitsu/1.1.A", # Mitsubishi phones
4563 "Panasonic WAP", # Panasonic old WAP phones
4564 "DoCoMo", # DoCoMo phones
4565 "Lynx", # Lynx text-mode linux browser
4566 "Links", # Another text-mode linux browser
4568 local @substrings = (
4569 "UP.Browser", # Openwave
4570 "MobilePhone", # NetFront
4571 "AU-MIC-A700", # Samsung A700 Obigo browsers
4572 "Danger hiptop", # Danger Sidekick hiptop
4573 "Windows CE", # Windows CE Pocket PC
4574 "IEMobile", # Windows mobile browser
4575 "Blazer", # Palm Treo Blazer
4576 "BlackBerry", # BlackBerries can emulate other browsers, but
4577 # they still keep this string in the UserAgent
4578 "SymbianOS", # New Series60 browser has safari in it and
4579 # SymbianOS is the only distinguishing string
4580 "iPhone", # Apple iPhone KHTML browser
4581 "iPod", # iPod touch browser
4582 "MobileSafari", # HTTP client in iPhone
4584 "Opera Mini", # Opera Mini
4585 "HTC_P3700", # HTC mobile device
4587 foreach my $p (@prefixes) {
4588 return 1 if ($agent =~ /^\Q$p\E/);
4590 foreach my $s (@substrings, @mobile_agents) {
4591 return 1 if ($agent =~ /\Q$s\E/);
4596 # write_blocked_file()
4597 # Writes out a text file of blocked hosts and users
4598 sub write_blocked_file
4600 open(BLOCKED, ">$config{'blockedfile'}");
4601 foreach my $d (grep { $hostfail{$_} } @deny) {
4602 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
4604 foreach my $d (grep { $userfail{$_} } @denyusers) {
4605 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
4608 chmod(0700, $config{'blockedfile'});
4613 open(PIDFILE, ">$config{'pidfile'}");
4614 printf PIDFILE "%d\n", getpid();
4618 # lock_user_password(user)
4619 # Updates a user's password file entry to lock it, both in memory and on disk.
4620 # Returns 1 if done, -1 if no such user, 0 if already locked
4621 sub lock_user_password
4624 if ($users{$user}) {
4625 if ($users{$user} !~ /^\!/) {
4627 $users{$user} = "!".$users{$user};
4628 open(USERS, $config{'userfile'});
4629 local @ufile = <USERS>;
4631 foreach my $u (@ufile) {
4632 local @uinfo = split(/:/, $u);
4633 if ($uinfo[0] eq $user) {
4634 $uinfo[1] = $users{$user};
4636 $u = join(":", @uinfo);
4638 open(USERS, ">$config{'userfile'}");
4648 # hash_session_id(sid)
4649 # Returns an MD5 or Unix-crypted session ID
4653 if (!$hash_session_id_cache{$sid}) {
4656 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
4660 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
4663 return $hash_session_id_cache{$sid};
4666 # encrypt_md5(string, [salt])
4667 # Returns a string encrypted in MD5 format
4670 local ($passwd, $salt) = @_;
4671 local $magic = '$1$';
4672 if ($salt =~ /^\$1\$([^\$]+)/) {
4673 # Extract actual salt from already encrypted password
4678 local $ctx = eval "new $use_md5";
4685 # Add some more stuff from the hash of the password and salt
4686 local $ctx1 = eval "new $use_md5";
4687 $ctx1->add($passwd);
4691 $ctx1->add($passwd);
4692 local $final = $ctx1->digest();
4693 for($pl=length($passwd); $pl>0; $pl-=16) {
4694 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
4697 # This piece of code seems rather pointless, but it's in the C code that
4698 # does MD5 in PAM so it has to go in!
4701 for($i=length($passwd); $i; $i >>= 1) {
4706 $ctx->add(substr($passwd, $j, 1));
4709 $final = $ctx->digest();
4712 # This loop exists only to waste time
4713 for($i=0; $i<1000; $i++) {
4714 $ctx1 = eval "new $use_md5";
4715 $ctx1->add($i & 1 ? $passwd : $final);
4716 $ctx1->add($salt) if ($i % 3);
4717 $ctx1->add($passwd) if ($i % 7);
4718 $ctx1->add($i & 1 ? $final : $passwd);
4719 $final = $ctx1->digest();
4723 # Convert the 16-byte final string into a readable form
4725 local @final = map { ord($_) } split(//, $final);
4726 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
4727 $rv .= &to64($l, 4);
4728 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
4729 $rv .= &to64($l, 4);
4730 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
4731 $rv .= &to64($l, 4);
4732 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
4733 $rv .= &to64($l, 4);
4734 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
4735 $rv .= &to64($l, 4);
4737 $rv .= &to64($l, 2);
4739 # Add salt if needed
4741 return $magic.$salt.'$'.$rv;
4750 local ($v, $n) = @_;
4753 $r .= $itoa64[$v & 0x3f];