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 print STDERR $pam_msg;
130 print STDERR "PAM use is mandatory, but could not be enabled!\n";
133 elsif ($pam_msg && !$use_pam) {
134 $pam_msg2 = "Continuing without the Authen::PAM perl module";
137 # Check if the User::Utmp perl module is installed
138 if ($config{'utmp'}) {
139 eval "use User::Utmp;";
142 $utmp_msg = "UTMP logging enabled";
145 $utmp_msg = "Perl module User::Utmp needed for Utmp logging is not installed : $@";
149 # See if the crypt function fails
150 eval "crypt('foo', 'xx')";
152 eval "use Crypt::UnixCrypt";
155 $crypt_msg = "Using Crypt::UnixCrypt for password encryption\n";
158 $crypt_msg = "crypt() function un-implemented, and Crypt::UnixCrypt not installed - password authentication will probably fail\n";
162 # Check if /dev/urandom really generates random IDs, by calling it twice
163 local $rand1 = &generate_random_id("foo", 1);
164 local $rand2 = &generate_random_id("foo", 2);
166 if ($rand1 eq $rand2) {
168 $rand_msg = "Random number generator file /dev/urandom is not reliable";
171 # Check if we can call sudo
172 if ($config{'sudo'} && &has_command("sudo")) {
178 $sudo_msg = "Perl module IO::Pty needed for calling sudo is not installed : $@";
182 # init days and months for http_date
183 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
184 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
185 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
187 # Change dir to the server root
188 @roots = ( $config{'root'} );
189 for($i=0; defined($config{"extraroot_$i"}); $i++) {
190 push(@roots, $config{"extraroot_$i"});
193 eval { $user_homedir = (getpwuid($<))[7]; };
195 # getpwuid doesn't work on windows
196 $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
203 # Setup SSL if possible and if requested
204 if (!-r $config{'keyfile'} ||
205 $config{'certfile'} && !-r $config{'certfile'}) {
206 # Key file doesn't exist!
209 @ipkeys = &get_ipkeys(\%config);
211 if ($config{'ssl_version'}) {
212 # Force an SSL version
213 $Net::SSLeay::version = $config{'ssl_version'};
214 $Net::SSLeay::ssl_version = $config{'ssl_version'};
216 $client_certs = 0 if (!-r $config{'ca'} || !%certs);
217 $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
218 $config{'certfile'});
219 foreach $ipkey (@ipkeys) {
220 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'});
221 foreach $ip (@{$ipkey->{'ips'}}) {
222 $ssl_contexts{$ip} = $ctx;
227 # Setup syslog support if possible and if requested
229 open(ERRDUP, ">&STDERR");
230 open(STDERR, ">/dev/null");
231 $log_socket = $config{"logsock"} || "unix";
232 eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
237 local $msg = ucfirst($config{'pam'})." starting";
238 eval { syslog("info", "%s", $msg); };
242 syslog("info", "%s", $msg);
245 # All attempts to use syslog have failed..
250 open(STDERR, ">&ERRDUP");
254 # Read MIME types file and add extra types
258 if ($config{'log'}) {
259 local(@gmt, @lct, $days, $hours, $mins);
260 @gmt = gmtime(time());
261 @lct = localtime(time());
262 $days = $lct[3] - $gmt[3];
263 $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
265 $mins = $hours * 60 + $lct[1] - $gmt[1];
266 $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
267 $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
270 # Build various maps from the config files
271 &build_config_mappings();
273 # start up external authentication program, if needed
274 if ($config{'extauth'}) {
275 socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
276 if (!($extauth = fork())) {
280 open(STDIN, "<&EXTAUTH2");
281 open(STDOUT, ">&EXTAUTH2");
282 exec($config{'extauth'}) or die "exec failed : $!\n";
285 local $os = select(EXTAUTH);
289 # Pre-load any libraries
290 if (!$config{'inetd'}) {
291 foreach $pl (split(/\s+/, $config{'preload'})) {
292 ($pkg, $lib) = split(/=/, $pl);
293 $pkg =~ s/[^A-Za-z0-9]/_/g;
294 eval "package $pkg; do '$config{'root'}/$lib'";
296 print STDERR "Failed to pre-load $lib in $pkg : $@\n";
299 print STDERR "Pre-loaded $lib in $pkg\n";
302 foreach $pl (split(/\s+/, $config{'premodules'})) {
304 ($dir, $mod) = split(/\//, $pl);
307 ($dir, $mod) = (undef, $pl);
309 push(@INC, "$config{'root'}/$dir");
310 eval "package $mod; use $mod ()";
312 print STDERR "Failed to pre-load $mod : $@\n";
315 print STDERR "Pre-loaded $mod\n";
320 # Open debug log if set
321 if ($config{'debuglog'}) {
322 open(DEBUG, ">>$config{'debuglog'}");
323 chmod(0700, $config{'debuglog'});
324 select(DEBUG); $| = 1; select(STDOUT);
325 print DEBUG "miniserv.pl starting ..\n";
328 # Write out (empty) blocked hosts file
329 &write_blocked_file();
331 # Re-direct STDERR to a log file
332 if ($config{'errorlog'} ne '-') {
333 open(STDERR, ">>$config{'errorlog'}") || die "failed to open $config{'errorlog'} : $!";
334 if ($config{'logperms'}) {
335 chmod(oct($config{'logperms'}), $config{'errorlog'});
338 select(STDERR); $| = 1; select(STDOUT);
340 if ($config{'inetd'}) {
341 # We are being run from inetd - go direct to handling the request
342 $SIG{'HUP'} = 'IGNORE';
343 $SIG{'TERM'} = 'DEFAULT';
344 $SIG{'PIPE'} = 'DEFAULT';
345 open(SOCK, "+>&STDIN");
347 # Check if it is time for the logfile to be cleared
348 if ($config{'logclear'}) {
349 local $write_logtime = 0;
350 local @st = stat("$config{'logfile'}.time");
352 if ($st[9]+$config{'logtime'}*60*60 < time()){
355 unlink($config{'logfile'});
358 else { $write_logtime = 1; }
359 if ($write_logtime) {
360 open(LOGTIME, ">$config{'logfile'}.time");
361 print LOGTIME time(),"\n";
366 # Initialize SSL for this connection
368 $ssl_con = &ssl_connection_for_ip(SOCK);
372 # Work out the hostname for this web server
373 $host = &get_socket_name(SOCK);
375 $port = $config{'port'};
376 $acptaddr = getpeername(SOCK);
379 print DEBUG "main: Starting handle_request loop pid=$$\n";
380 while(&handle_request($acptaddr, getsockname(SOCK))) { }
381 print DEBUG "main: Done handle_request loop pid=$$\n";
386 # Build list of sockets to listen on
387 if ($config{"bind"} && $config{"bind"} ne "*") {
388 push(@sockets, [ inet_aton($config{'bind'}), $config{'port'} ]);
391 push(@sockets, [ INADDR_ANY, $config{'port'} ]);
393 foreach $s (split(/\s+/, $config{'sockets'})) {
394 if ($s =~ /^(\d+)$/) {
395 # Just listen on another port on the main IP
396 push(@sockets, [ $sockets[0]->[0], $s ]);
398 elsif ($s =~ /^(\S+):(\d+)$/) {
399 # Listen on a specific port and IP
400 push(@sockets, [ $1 eq "*" ? INADDR_ANY : inet_aton($1), $2 ]);
402 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
403 # Listen on the main port on another IP
404 push(@sockets, [ inet_aton($1), $sockets[0]->[1] ]);
408 # Open all the sockets
409 $proto = getprotobyname('tcp');
411 $tried_inaddr_any = 0;
412 for($i=0; $i<@sockets; $i++) {
414 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
415 die "Failed to open socket : $!";
416 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
417 for($j=0; $j<5; $j++) {
418 last if (bind($fh, pack_sockaddr_in($sockets[$i]->[1],
419 $sockets[$i]->[0])));
423 # All attempts failed .. give up
424 if ($sockets[$i]->[0] eq INADDR_ANY) {
425 push(@sockerrs, "Failed to bind to port $sockets[$i]->[1] : $!");
426 $tried_inaddr_any = 1;
429 $ip = inet_ntoa($sockets[$i]->[0]);
430 push(@sockerrs, "Failed to bind to IP $ip port $sockets[$i]->[1] : $!");
434 listen($fh, SOMAXCONN);
435 push(@socketfhs, $fh);
438 foreach $se (@sockerrs) {
439 print STDERR $se,"\n";
442 # If all binds failed, try binding to any address
443 if (!@socketfhs && !$tried_inaddr_any) {
444 print STDERR "Falling back to listening on any address\n";
446 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
447 die "Failed to open socket : $!";
448 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
449 bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY)) ||
450 die "Failed to bind to port $sockets[0]->[1] : $!";
451 listen($fh, SOMAXCONN);
452 push(@socketfhs, $fh);
454 elsif (!@socketfhs && $tried_inaddr_any) {
455 die "Could not listen on any ports";
458 if ($config{'listen'}) {
459 # Open the socket that allows other webmin servers to find this one
460 $proto = getprotobyname('udp');
461 if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
462 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
463 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
464 listen(LISTEN, SOMAXCONN);
467 $config{'listen'} = 0;
471 # Split from the controlling terminal, unless configured not to
472 if (!$config{'nofork'}) {
473 if (fork()) { exit; }
475 eval { setsid(); }; # may not work on Windows
477 # Close standard file handles
478 open(STDIN, "</dev/null");
479 open(STDOUT, ">/dev/null");
480 &log_error("miniserv.pl started");
481 &log_error($pam_msg) if ($pam_msg);
482 &log_error($pam_msg2) if ($pam_msg2);
483 &log_error($utmp_msg) if ($utmp_msg);
484 &log_error($crypt_msg) if ($crypt_msg);
485 &log_error($sudo_msg) if ($sudo_msg);
486 &log_error($rand_msg) if ($rand_msg);
488 # write out the PID file
491 # Start the log-clearing process, if needed. This checks every minute
492 # to see if the log has passed its reset time, and if so clears it
493 if ($config{'logclear'}) {
494 if (!($logclearer = fork())) {
495 &close_all_sockets();
498 local $write_logtime = 0;
499 local @st = stat("$config{'logfile'}.time");
501 if ($st[9]+$config{'logtime'}*60*60 < time()){
504 unlink($config{'logfile'});
507 else { $write_logtime = 1; }
508 if ($write_logtime) {
509 open(LOGTIME, ">$config{'logfile'}.time");
510 print LOGTIME time(),"\n";
517 push(@childpids, $logclearer);
520 # Setup the logout time dbm if needed
521 if ($config{'session'}) {
522 eval "use SDBM_File";
523 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
524 eval "\$sessiondb{'1111111111'} = 'foo bar';";
526 dbmclose(%sessiondb);
527 eval "use NDBM_File";
528 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
531 delete($sessiondb{'1111111111'});
536 $SIG{'HUP'} = 'miniserv::trigger_restart';
537 $SIG{'TERM'} = 'miniserv::term_handler';
538 $SIG{'USR1'} = 'miniserv::trigger_reload';
539 $SIG{'PIPE'} = 'IGNORE';
540 local $remove_session_count = 0;
541 $need_pipes = $config{'passdelay'} || $config{'session'};
543 # wait for a new connection, or a message from a child process
545 if (@childpids <= $config{'maxconns'}) {
546 # Only accept new main socket connects when ready
548 foreach $s (@socketfhs) {
549 vec($rmask, fileno($s), 1) = 1;
553 printf STDERR "too many children (%d > %d)\n",
554 scalar(@childpids), $config{'maxconns'};
557 for($i=0; $i<@passin; $i++) {
558 vec($rmask, fileno($passin[$i]), 1) = 1;
561 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
563 # Wait for a connection
564 local $sel = select($rmask, undef, undef, 10);
566 # Check the flag files
567 if ($config{'restartflag'} && -r $config{'restartflag'}) {
568 print STDERR "restart flag file detected\n";
569 unlink($config{'restartflag'});
572 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
573 unlink($config{'reloadflag'});
578 # Got a HUP signal while in select() .. restart now
582 # Got a USR1 signal while in select() .. re-read config
584 &reload_config_file();
586 local $time_now = time();
588 # Clean up finished processes
590 do { $pid = waitpid(-1, WNOHANG);
591 @childpids = grep { $_ != $pid } @childpids;
592 } while($pid != 0 && $pid != -1);
594 # run the unblocking procedure to check if enough time has passed to
595 # unblock hosts that heve been blocked because of password failures
597 if ($config{'blockhost_failures'}) {
599 while ($i <= $#deny) {
600 if ($blockhosttime{$deny[$i]} &&
601 $config{'blockhost_time'} != 0 &&
602 ($time_now - $blockhosttime{$deny[$i]}) >=
603 $config{'blockhost_time'}) {
604 # the host can be unblocked now
605 $hostfail{$deny[$i]} = 0;
606 splice(@deny, $i, 1);
613 # Do the same for blocked users
614 if ($config{'blockuser_failures'}) {
616 while ($i <= $#deny) {
617 if ($blockusertime{$deny[$i]} &&
618 $config{'blockuser_time'} != 0 &&
619 ($time_now - $blockusertime{$deny[$i]}) >=
620 $config{'blockuser_time'}) {
621 # the user can be unblocked now
622 $userfail{$deny[$i]} = 0;
623 splice(@denyusers, $i, 1);
630 &write_blocked_file();
633 if ($config{'session'} && (++$remove_session_count%50) == 0) {
634 # Remove sessions with more than 7 days of inactivity,
636 foreach $s (keys %sessiondb) {
637 local ($user, $ltime, $lip) =
638 split(/\s+/, $sessiondb{$s});
639 if ($time_now - $ltime > 7*24*60*60) {
640 &run_logout_script($s, $user);
641 &write_logout_utmp($user, $lip);
642 delete($sessiondb{$s});
645 "Timeout of session for $user");
651 if ($use_pam && $config{'pam_conv'}) {
652 # Remove PAM sessions with more than 5 minutes of inactivity
654 foreach $c (values %conversations) {
655 if ($time_now - $c->{'time'} > 5*60) {
656 &end_pam_conversation($c);
658 syslog("info", "%s", "Timeout of PAM ".
659 "session for $c->{'user'}");
665 # Don't check any sockets if there is no activity
668 # Check if any of the main sockets have received a new connection
670 foreach $s (@socketfhs) {
671 if (vec($rmask, fileno($s), 1)) {
673 $acptaddr = accept(SOCK, $s);
674 if (!$acptaddr) { next; }
675 binmode(SOCK); # turn off any Perl IO stuff
678 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
680 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
684 # Check username of connecting user
685 local ($peerp, $peera) = unpack_sockaddr_in($acptaddr);
686 $localauth_user = undef;
687 if ($config{'localauth'} && inet_ntoa($peera) eq "127.0.0.1") {
688 if (open(TCP, "/proc/net/tcp")) {
689 # Get the info direct from the kernel
692 local @t = split(/[\s:]+/, $_);
693 if ($t[1] eq '0100007F' &&
694 $t[2] eq sprintf("%4.4X", $peerp)) {
695 $localauth_user = getpwuid($t[11]);
701 if (!$localauth_user) {
702 # Call lsof for the info
703 local $lsofpid = open(LSOF,
704 "$config{'localauth'} -i TCP\@127.0.0.1:$peerp |");
706 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
707 $2 != $$ && $2 != $lsofpid) {
708 $localauth_user = $3;
715 # Work out the hostname for this web server
716 $host = &get_socket_name(SOCK);
718 print STDERR "Failed to get local socket name : $!\n";
722 $port = $sockets[$sn]->[1];
724 # fork the subprocess
726 if (!($handpid = fork())) {
727 # setup signal handlers
728 $SIG{'TERM'} = 'DEFAULT';
729 $SIG{'PIPE'} = 'DEFAULT';
730 #$SIG{'CHLD'} = 'IGNORE';
731 $SIG{'HUP'} = 'IGNORE';
732 $SIG{'USR1'} = 'IGNORE';
734 # Initialize SSL for this connection
736 $ssl_con = &ssl_connection_for_ip(SOCK);
740 # Close the file handle for the session DBM
741 dbmclose(%sessiondb);
743 # close useless pipes
746 close($PASSINr); close($PASSOUTw);
748 &close_all_sockets();
752 "main: Starting handle_request loop pid=$$\n";
753 while(&handle_request($acptaddr,
754 getsockname(SOCK))) { }
756 "main: Done handle_request loop pid=$$\n";
759 close($PASSINw); close($PASSOUTw);
762 push(@childpids, $handpid);
764 close($PASSINw); close($PASSOUTr);
765 push(@passin, $PASSINr);
766 push(@passout, $PASSOUTw);
773 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
774 # Got UDP packet from another webmin server
776 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
778 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
779 local $toip = inet_ntoa((unpack_sockaddr_in(
780 getsockname(LISTEN)))[1]);
781 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
782 (!@allow || &ip_match($fromip, $toip, @allow))) {
783 local $listenhost = &get_socket_name(LISTEN);
784 send(LISTEN, "$listenhost:$config{'port'}:".
785 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
786 ($config{'listenhost'} ?
787 &get_system_hostname() : ""),
793 # check for session, password-timeout and PAM messages from subprocesses
794 for($i=0; $i<@passin; $i++) {
795 if (vec($rmask, fileno($passin[$i]), 1)) {
796 # this sub-process is asking about a password
797 local $infd = $passin[$i];
798 local $outfd = $passout[$i];
799 #local $inline = <$infd>;
800 local $inline = &sysread_line($infd);
802 print DEBUG "main: inline $inline";
805 print DEBUG "main: inline EOF\n";
807 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
808 # Got a delay request from a subprocess.. for
809 # valid logins, there is no delay (to prevent
810 # denial of service attacks), but for invalid
811 # logins the delay increases with each failed
814 # login OK.. no delay
815 print $outfd "0 0\n";
816 $wasblocked = $hostfail{$2} ||
821 &write_blocked_file();
830 # add the host to the block list,
832 if ($config{'blockhost_failures'} &&
834 $config{'blockhost_failures'}) {
836 $blockhosttime{$2} = $time_now;
839 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
845 # add the user to the user block list,
847 if ($config{'blockuser_failures'} &&
849 $config{'blockuser_failures'}) {
850 push(@denyusers, $1);
851 $blockusertime{$1} = $time_now;
854 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
860 # Lock out the user's password, if enabled
861 if ($config{'blocklock'} &&
863 $config{'blockuser_failures'}) {
864 my $lk = &lock_user_password($1);
867 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";
874 $dl = $userdlay{$1} -
875 int(($time_now - $userlast{$1})/50);
876 $dl = $dl < 0 ? 0 : $dl+1;
877 print $outfd "$dl $blocked\n";
880 # Write out blocked status file
882 &write_blocked_file();
885 $userlast{$1} = $time_now;
887 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
888 # Verifying a session ID
889 local $session_id = $1;
890 local $notimeout = $2;
891 local $skey = $sessiondb{$session_id} ?
893 &hash_session_id($session_id);
894 if (!defined($sessiondb{$skey})) {
895 # Session doesn't exist
896 print $outfd "0 0\n";
899 local ($user, $ltime) =
900 split(/\s+/, $sessiondb{$skey});
901 local $lot = &get_logout_time($user, $session_id);
903 $time_now - $ltime > $lot*60 &&
905 # Session has timed out
906 print $outfd "1 ",$time_now - $ltime,"\n";
907 #delete($sessiondb{$skey});
911 print $outfd "2 $user\n";
915 $sessiondb{$skey} = "$user $time_now";
920 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
921 # Creating a new session
922 local $session_id = $1;
925 $sessiondb{&hash_session_id($session_id)} =
926 "$user $time_now $ip";
928 elsif ($inline =~ /^delete\s+(\S+)/) {
929 # Logging out a session
930 local $session_id = $1;
931 local $skey = $sessiondb{$session_id} ?
933 &hash_session_id($session_id);
934 local @sdb = split(/\s+/, $sessiondb{$skey});
935 print $outfd $sdb[0],"\n";
936 delete($sessiondb{$skey});
938 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
939 # Starting a new PAM conversation
940 local ($cid, $host, $user) = ($1, $2, $3);
942 # Does this user even need PAM?
943 local ($realuser, $canlogin) =
944 &can_user_login($user, undef, $host);
946 if ($canlogin == 0) {
948 print $outfd "0 Invalid username\n";
950 elsif ($canlogin != 2) {
951 # Not using PAM .. so just ask for
953 $conv = { 'user' => $realuser,
958 print $outfd "3 Password\n";
961 # Start the PAM conversation
962 # sub-process, and get a question
963 $conv = { 'user' => $realuser,
967 local ($PAMINr, $PAMINw, $PAMOUTr,
968 $PAMOUTw) = &allocate_pipes();
969 local $pampid = fork();
971 close($PAMOUTr); close($PAMINw);
972 &pam_conversation_process(
976 close($PAMOUTw); close($PAMINr);
977 $conv->{'pid'} = $pampid;
978 $conv->{'PAMOUTr'} = $PAMOUTr;
979 $conv->{'PAMINw'} = $PAMINw;
980 push(@childpids, $pampid);
982 # Get the first PAM question
983 local $pok = &recv_pam_question(
986 &end_pam_conversation($conv);
990 $conversations{$cid} = $conv if ($conv);
992 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
993 # A response to a PAM question
994 local ($cid, $answer) = ($1, $2);
995 local $conv = $conversations{$cid};
997 # No such conversation?
998 print $outfd "0 Bad login session\n";
1000 elsif ($conv->{'pid'}) {
1001 # Send the PAM response and get
1003 &send_pam_answer($conv, $answer);
1004 local $pok = &recv_pam_question($conv, $outfd);
1006 &end_pam_conversation($conv);
1010 # This must be the password .. try it
1011 # and send back the results
1012 local ($vu, $expired, $nonexist) =
1013 &validate_user($conv->{'user'},
1016 local $ok = $vu ? 1 : 0;
1017 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1018 &end_pam_conversation($conv);
1021 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1022 # Store the fact that some user can sudo to root
1023 local ($user, $ok) = ($1, $2);
1024 $sudocache{$user} = $ok." ".time();
1026 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1027 # Query the user sudo cache (valid for 1 minute)
1029 local ($ok, $last) =
1030 split(/\s+/, $sudocache{$user});
1031 if ($last < time()-60) {
1036 # Tell client OK or not
1037 print $outfd "$ok\n";
1040 elsif ($inline =~ /\S/) {
1041 # Unknown line from pipe?
1042 print DEBUG "main: Unknown line from pipe $inline\n";
1043 print STDERR "Unknown line from pipe $inline\n";
1047 close($infd); close($outfd);
1048 $passin[$i] = $passout[$i] = undef;
1052 @passin = grep { defined($_) } @passin;
1053 @passout = grep { defined($_) } @passout;
1056 # handle_request(remoteaddress, localaddress)
1057 # Where the real work is done
1060 $acptip = inet_ntoa((unpack_sockaddr_in($_[0]))[1]);
1061 $localip = $_[1] ? inet_ntoa((unpack_sockaddr_in($_[1]))[1]) : undef;
1062 print DEBUG "handle_request: from $acptip to $localip\n";
1063 if ($config{'loghost'}) {
1064 $acpthost = gethostbyaddr(inet_aton($acptip), AF_INET);
1065 $acpthost = $acptip if (!$acpthost);
1068 $acpthost = $acptip;
1070 $datestr = &http_date(time());
1072 $ok_message = "Document follows";
1073 $logged_code = undef;
1074 $reqline = $request_uri = $page = undef;
1078 # check address against access list
1079 if (@deny && &ip_match($acptip, $localip, @deny) ||
1080 @allow && !&ip_match($acptip, $localip, @allow)) {
1081 &http_error(403, "Access denied for $acptip");
1086 # Check address with TCP-wrappers
1087 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1088 $acptip, STRING_UNKNOWN)) {
1089 &http_error(403, "Access denied for $acptip by TCP wrappers");
1093 print DEBUG "handle_request: passed IP checks\n";
1095 # Compute a timeout for the start of headers, based on the number of
1096 # child processes. As this increases, we use a shorter timeout to avoid
1097 # an attacker overloading the system.
1098 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1100 # Wait at most 60 secs for start of headers for initial requests, or
1101 # 10 minutes for kept-alive connections
1103 vec($rmask, fileno(SOCK), 1) = 1;
1104 local $to = $checked_timeout ? 10*60 : $header_timeout;
1105 local $sel = select($rmask, undef, undef, $to);
1107 if ($checked_timeout) {
1108 print DEBUG "handle_request: exiting due to timeout of $to\n";
1112 &http_error(400, "Timeout",
1113 "Waited for that $to seconds for start of headers");
1117 print DEBUG "handle_request: passed timeout check\n";
1119 # Read the HTTP request and headers
1120 local $origreqline = &read_line();
1121 ($reqline = $origreqline) =~ s/\r|\n//g;
1122 $method = $page = $request_uri = undef;
1123 print DEBUG "handle_request reqline=$reqline\n";
1124 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1125 # An empty request .. just close the connection
1126 print DEBUG "handle_request: rejecting empty request\n";
1129 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1130 print DEBUG "handle_request: invalid reqline=$reqline\n";
1132 # This could be an http request when it should be https
1134 local $url = $config{'musthost'} ?
1135 "https://$config{'musthost'}:$port/" :
1136 "https://$host:$port/";
1137 if ($config{'ssl_redirect'}) {
1138 # Just re-direct to the correct URL
1139 sleep(1); # Give browser a change to finish
1140 # sending its request
1141 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1142 &write_data("Date: $datestr\r\n");
1143 &write_data("Server: $config{'server'}\r\n");
1144 &write_data("Location: $url\r\n");
1145 &write_keep_alive(0);
1146 &write_data("\r\n");
1150 # Tell user the correct URL
1151 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1154 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1155 # This could be an https request when it should be http ..
1156 # need to fake a HTTP response
1159 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1160 eval "Net::SSLeay::load_error_strings()";
1161 $ssl_ctx = Net::SSLeay::CTX_new();
1162 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1163 $ssl_ctx, $config{'keyfile'},
1164 &Net::SSLeay::FILETYPE_PEM);
1165 Net::SSLeay::CTX_use_certificate_file(
1167 $config{'certfile'} || $config{'keyfile'},
1168 &Net::SSLeay::FILETYPE_PEM);
1169 $ssl_con = Net::SSLeay::new($ssl_ctx);
1173 select(SSLw); $| = 1; select(STDOUT);
1174 print SSLw $origreqline;
1176 while(sysread(SOCK, $buf, 1) > 0) {
1183 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1184 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1185 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1187 local $url = $config{'musthost'} ?
1188 "https://$config{'musthost'}:$port/" :
1189 "https://$host:$port/";
1190 if ($config{'ssl_redirect'}) {
1191 # Just re-direct to the correct URL
1192 sleep(1); # Give browser a change to
1193 # finish sending its request
1194 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1195 &write_data("Date: $datestr\r\n");
1196 &write_data("Server: $config{'server'}\r\n");
1197 &write_data("Location: $url\r\n");
1198 &write_keep_alive(0);
1199 &write_data("\r\n");
1203 # Tell user the correct URL
1204 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1208 &http_error(400, "Bad Request");
1212 &http_error(400, "Bad Request");
1216 $request_uri = $page = $2;
1220 ($headline = &read_line()) =~ s/\r|\n//g;
1221 last if ($headline eq "");
1222 print DEBUG "handle_request: got headline $headline\n";
1223 if ($headline =~ /^(\S+):\s*(.*)$/) {
1224 $header{$lastheader = lc($1)} = $2;
1226 elsif ($headline =~ /^\s+(.*)$/) {
1227 $header{$lastheader} .= $headline;
1230 &http_error(400, "Bad Header $headline");
1233 if (defined($header{'host'})) {
1234 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1235 ($host, $port) = ($1, $2);
1238 $host = $header{'host'};
1240 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1241 # Disallowed hostname used
1242 &http_error(400, "Invalid HTTP hostname");
1246 if ($page =~ /^([^\?]+)\?(.*)$/) {
1247 # There is some query string information
1250 print DEBUG "handle_request: querystring=$querystring\n";
1251 if ($querystring !~ /=/) {
1252 $queryargs = $querystring;
1253 $queryargs =~ s/\+/ /g;
1254 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1258 # Parse query-string parameters
1259 local @in = split(/\&/, $querystring);
1261 local ($k, $v) = split(/=/, $i, 2);
1262 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1263 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1268 $posted_data = undef;
1269 if ($method eq 'POST' &&
1270 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1271 # Read in posted query string information, up the configured maximum
1272 # post request length
1273 $clen = $header{"content-length"};
1274 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1275 while(length($posted_data) < $clen_read) {
1276 $buf = &read_data($clen_read - length($posted_data));
1277 if (!length($buf)) {
1278 &http_error(500, "Failed to read POST request");
1280 chomp($posted_data);
1281 $posted_data =~ s/\015$//mg;
1282 $posted_data .= $buf;
1284 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1285 if ($clen_read != $clen && length($posted_data) > $clen) {
1286 # If the client sent more data than we asked for, chop the
1288 $posted_data = substr($posted_data, 0, $clen);
1290 if (length($posted_data) > $clen) {
1291 # When the client sent too much, delay so that it gets headers
1294 if ($header{'user-agent'} =~ /MSIE/ &&
1295 $header{'user-agent'} !~ /Opera/i) {
1296 # MSIE includes an extra newline in the data
1297 $posted_data =~ s/\r|\n//g;
1299 local @in = split(/\&/, $posted_data);
1301 local ($k, $v) = split(/=/, $i, 2);
1303 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1304 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1307 print DEBUG "handle_request: posted_data=$posted_data\n";
1310 # replace %XX sequences in page
1311 $page =~ s/%(..)/pack("c",hex($1))/ge;
1313 # Check if the browser's user agent indicates a mobile device
1314 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1316 # Check if Host: header is for a mobile URL
1317 foreach my $m (@mobile_prefixes) {
1318 if ($header{'host'} =~ /^\Q$m\E/i) {
1323 # check for the logout flag file, and if existant deny authentication
1324 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1325 print DEBUG "handle_request: logout flag set\n";
1326 $deny_authentication++;
1327 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1328 chop($count = <LOGOUT>);
1332 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1333 print LOGOUT "$count\n";
1337 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1341 # check for any redirect for the requested URL
1342 foreach my $pfx (@strip_prefix) {
1343 my $l = length($pfx);
1344 if(length($page) >= $l &&
1345 substr($page,0,$l) eq $pfx) {
1346 $page=substr($page,$l);
1350 $simple = &simplify_path($page, $bogus);
1352 $rpath .= "&".$querystring if (defined($querystring));
1353 $redir = $redirect{$rpath};
1354 if (defined($redir)) {
1355 print DEBUG "handle_request: redir=$redir\n";
1356 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1357 &write_data("Date: $datestr\r\n");
1358 &write_data("Server: $config{'server'}\r\n");
1359 local $ssl = $use_ssl || $config{'inetd_ssl'};
1360 $portstr = $port == 80 && !$ssl ? "" :
1361 $port == 443 && $ssl ? "" : ":$port";
1362 $prot = $ssl ? "https" : "http";
1363 &write_data("Location: $prot://$host$portstr$redir\r\n");
1364 &write_keep_alive(0);
1365 &write_data("\r\n");
1369 # Check for a DAV request
1371 foreach my $d (@davpaths) {
1372 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1377 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1378 &http_error(400, "Bad Request method $method");
1381 # Check for password if needed
1383 print DEBUG "handle_request: Need authentication\n";
1387 # Session authentication is never used for connections by
1388 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1389 # or mobile browsers if requested.
1390 if ($header{'user-agent'} =~ /webmin/i ||
1391 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1392 $sessiononly{$simple} || $davpath ||
1393 $simple eq "/xmlrpc.cgi" ||
1394 $acptip eq $config{'host_nosession'} ||
1395 $mobile_device && $config{'mobile_nosession'}) {
1396 print DEBUG "handle_request: Forcing HTTP authentication\n";
1397 $config{'session'} = 0;
1400 # check for SSL authentication
1401 if ($use_ssl && $verified_client) {
1402 $peername = Net::SSLeay::X509_NAME_oneline(
1403 Net::SSLeay::X509_get_subject_name(
1404 Net::SSLeay::get_peer_certificate(
1406 local $peername2 = $peername;
1407 $peername2 =~ s/Email=/emailAddress=/ ||
1408 $peername2 =~ s/emailAddress=/Email=/;
1409 foreach $u (keys %certs) {
1410 if ($certs{$u} eq $peername ||
1411 $certs{$u} eq $peername2) {
1414 #syslog("info", "%s", "SSL login as $authuser from $acpthost") if ($use_syslog);
1418 if ($use_syslog && !$validated) {
1419 syslog("crit", "%s",
1420 "Unknown SSL certificate $peername");
1424 if (!$validated && !$deny_authentication) {
1425 # check for IP-based authentication
1427 foreach $a (keys %ipaccess) {
1428 if ($acptip eq $a) {
1429 # It does! Auth as the user
1431 $baseauthuser = $authuser =
1437 # Check for normal HTTP authentication
1438 if (!$validated && !$deny_authentication && !$config{'session'} &&
1439 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1440 # authorization given..
1441 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1442 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1443 local ($vu, $expired, $nonexist) =
1444 &validate_user($authuser, $authpass, $host);
1445 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1446 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1453 if ($use_syslog && !$validated) {
1454 syslog("crit", "%s",
1455 ($nonexist ? "Non-existent" :
1456 $expired ? "Expired" : "Invalid").
1457 " login as $authuser from $acpthost");
1459 if ($authuser =~ /\r|\n|\s/) {
1460 &http_error(500, "Invalid username",
1461 "Username contains invalid characters");
1463 if ($authpass =~ /\r|\n/) {
1464 &http_error(500, "Invalid password",
1465 "Password contains invalid characters");
1468 if ($config{'passdelay'} && !$config{'inetd'}) {
1469 # check with main process for delay
1470 print DEBUG "handle_request: about to ask for password delay\n";
1471 print $PASSINw "delay $authuser $acptip $validated\n";
1472 <$PASSOUTr> =~ /(\d+) (\d+)/;
1474 print DEBUG "handle_request: password delay $1 $2\n";
1479 # Check for a visit to the special session login page
1480 if ($config{'session'} && !$deny_authentication &&
1481 $page eq $config{'session_login'}) {
1482 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1483 # Logout clicked .. remove the session
1485 print $PASSINw "delete $sid\n";
1486 local $louser = <$PASSOUTr>;
1489 $already_session_id = undef;
1490 $authuser = $baseauthuser = undef;
1493 syslog("info", "%s", "Logout by $louser from $acpthost");
1495 &run_logout_script($louser, $sid,
1497 &write_logout_utmp($louser, $actphost);
1502 if ($in{'user'} =~ /\r|\n|\s/) {
1503 &http_error(500, "Invalid username",
1504 "Username contains invalid characters");
1506 if ($in{'pass'} =~ /\r|\n/) {
1507 &http_error(500, "Invalid password",
1508 "Password contains invalid characters");
1511 local ($vu, $expired, $nonexist) =
1512 &validate_user($in{'user'}, $in{'pass'}, $host);
1513 local $hrv = &handle_login(
1514 $vu || $in{'user'}, $vu ? 1 : 0,
1515 $expired, $nonexist, $in{'pass'},
1516 $in{'notestingcookie'});
1517 return $hrv if (defined($hrv));
1521 # Check for a visit to the special PAM login page
1522 if ($config{'session'} && !$deny_authentication &&
1523 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1525 # A question has been entered .. submit it to the main process
1526 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1527 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1528 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1529 &http_error(500, "Invalid response",
1530 "Response contains invalid characters");
1534 # Start of a new conversation - answer must be username
1535 $cid = &generate_random_id($in{'answer'});
1536 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1539 # A response to a previous question
1541 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1544 # Read back the response, and the next question (if any)
1545 local $line = <$PASSOUTr>;
1546 $line =~ s/\r|\n//g;
1547 local ($rv, $question) = split(/\s+/, $line, 2);
1550 local $hrv = &handle_login(
1551 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1554 return $hrv if (defined($hrv));
1556 elsif ($rv == 1 || $rv == 3) {
1557 # Another question .. force use of PAM CGI
1560 $querystring .= "&cid=$cid&question=".
1562 $querystring .= "&password=1" if ($rv == 3);
1564 $page = $config{'pam_login'};
1565 $miniserv_internal = 1;
1569 # Got back a final ok or failure
1570 local ($user, $ok, $expired, $nonexist) =
1571 split(/\s+/, $question);
1572 local $hrv = &handle_login(
1573 $user, $ok, $expired, $nonexist, undef,
1574 $in{'notestingcookie'});
1575 return $hrv if (defined($hrv));
1578 # A message from PAM .. tell the user
1581 $querystring .= "&cid=$cid&message=".
1584 $page = $config{'pam_login'};
1585 $miniserv_internal = 1;
1590 # Check for a visit to the special password change page
1591 if ($config{'session'} && !$deny_authentication &&
1592 $page eq $config{'password_change'} && !$validated) {
1593 # Just let this slide ..
1595 $miniserv_internal = 3;
1598 # Check for an existing session
1599 if ($config{'session'} && !$validated) {
1600 if ($already_session_id) {
1601 $session_id = $already_session_id;
1602 $authuser = $already_authuser;
1605 elsif (!$deny_authentication &&
1606 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1607 # Try all session cookies
1608 local $cookie = $header{'cookie'};
1609 while($cookie =~ s/(^|\s)$sidname=([a-f0-9]+)//) {
1612 $in{'webmin_notimeout'} ? 1 : 0;
1613 print $PASSINw "verify $session_id $notimeout\n";
1614 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1616 # Valid session continuation
1619 $already_authuser = $authuser;
1628 # Invalid session ID .. don't set
1635 # Check for local authentication
1636 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1637 if (defined($users{$localauth_user})) {
1638 # Local user exists in webmin users file
1640 $authuser = $localauth_user;
1643 # Check if local user is allowed by unixauth
1644 local @can = &can_user_login($localauth_user,
1648 $authuser = $localauth_user;
1651 $localauth_user = undef;
1657 # Check if this path allows anonymous access
1659 foreach $a (keys %anonymous) {
1660 if (substr($simple, 0, length($a)) eq $a) {
1661 # It does! Auth as the user, if IP access
1662 # control allows him.
1663 if (&check_user_ip($anonymous{$a}) &&
1664 &check_user_time($anonymous{$a})) {
1666 $baseauthuser = $authuser =
1674 # Check if this path allows unauthenticated access
1675 local ($u, $unauth);
1676 foreach $u (@unauth) {
1677 $unauth++ if ($simple =~ /$u/);
1679 if (!$bogus && $unauth) {
1680 # Unauthenticated directory or file request - approve it
1682 $baseauthuser = $authuser = undef;
1687 if ($blocked == 0) {
1688 # No password given.. ask
1689 if ($config{'pam_conv'} && $use_pam) {
1690 # Force CGI for PAM question, starting with
1691 # the username which is always needed
1694 $querystring .= "&initial=1&question=".
1695 &urlize("Username");
1696 $querystring .= "&failed=$failed_user" if ($failed_user);
1697 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1699 $page = $config{'pam_login'};
1700 $miniserv_internal = 1;
1703 elsif ($config{'session'}) {
1704 # Force CGI for session login
1707 $querystring .= "&logout=1&page=/";
1710 # Re-direct to current module only
1711 local $rpage = $request_uri;
1712 if (!$config{'loginkeeppage'}) {
1713 $rpage =~ s/\?.*$//;
1714 $rpage =~ s/[^\/]+$//
1716 $querystring = "page=".&urlize($rpage);
1719 $querystring .= "&failed=$failed_user" if ($failed_user);
1720 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1722 $page = $config{'session_login'};
1723 $miniserv_internal = 1;
1727 # Ask for login with HTTP authentication
1728 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1729 &write_data("Date: $datestr\r\n");
1730 &write_data("Server: $config{'server'}\r\n");
1731 &write_data("WWW-authenticate: Basic ".
1732 "realm=\"$config{'realm'}\"\r\n");
1733 &write_keep_alive(0);
1734 &write_data("Content-type: text/html\r\n");
1735 &write_data("\r\n");
1736 &reset_byte_count();
1737 &write_data("<html>\n");
1738 &write_data("<head><title>Unauthorized</title></head>\n");
1739 &write_data("<body><h1>Unauthorized</h1>\n");
1740 &write_data("A password is required to access this\n");
1741 &write_data("web server. Please try again. <p>\n");
1742 &write_data("</body></html>\n");
1743 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1747 elsif ($blocked == 1) {
1748 # when the host has been blocked, give it an error
1749 &http_error(403, "Access denied for $acptip. The host ".
1750 "has been blocked because of too ".
1751 "many authentication failures.");
1753 elsif ($blocked == 2) {
1754 # when the user has been blocked, give it an error
1755 &http_error(403, "Access denied. The user ".
1756 "has been blocked because of too ".
1757 "many authentication failures.");
1761 # Get the real Webmin username
1762 local @can = &can_user_login($authuser, undef, $host);
1763 $baseauthuser = $can[3] || $authuser;
1765 if ($config{'remoteuser'} && !$< && $validated) {
1766 # Switch to the UID of the remote user (if he exists)
1767 local @u = getpwnam($authuser);
1768 if (@u && $< != $u[2]) {
1769 $( = $u[3]; $) = "$u[3] $u[3]";
1770 ($>, $<) = ($u[2], $u[2]);
1773 &http_error(500, "Unix user $authuser does not exist");
1779 # Check per-user IP access control
1780 if (!&check_user_ip($baseauthuser)) {
1781 &http_error(403, "Access denied for $acptip for $baseauthuser");
1785 # Check per-user allowed times
1786 if (!&check_user_time($baseauthuser)) {
1787 &http_error(403, "Access denied at the current time");
1792 # Validate the path, and convert to canonical form
1794 $simple = &simplify_path($page, $bogus);
1795 print DEBUG "handle_request: page=$page simple=$simple\n";
1797 &http_error(400, "Invalid path");
1800 # Check for a DAV request
1802 return &handle_dav_request($davpath);
1805 # Work out the active theme(s)
1806 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1807 $config{'mobile_preroot'} :
1808 $authuser && defined($config{'preroot_'.$authuser}) ?
1809 $config{'preroot_'.$authuser} :
1810 $authuser && $baseauthuser &&
1811 defined($config{'preroot_'.$baseauthuser}) ?
1812 $config{'preroot_'.$baseauthuser} :
1814 local @preroots = reverse(split(/\s+/, $preroots));
1816 # Canonicalize the directories
1817 foreach my $preroot (@preroots) {
1818 # Always under the current webmin root
1819 $preroot =~ s/^.*\///g;
1820 $preroot = $roots[0].'/'.$preroot;
1823 # Look in the theme root directories first
1824 local ($full, @stfull);
1826 foreach my $preroot (@preroots) {
1829 $full = $preroot.$sofar;
1830 $scriptname = $simple;
1831 foreach $b (split(/\//, $simple)) {
1832 if ($b ne "") { $sofar .= "/$b"; }
1833 $full = $preroot.$sofar;
1834 @stfull = stat($full);
1835 if (!@stfull) { undef($full); last; }
1837 # Check if this is a directory
1839 # It is.. go on parsing
1847 # Check if this is a CGI program
1848 if (&get_type($full) eq "internal/cgi") {
1849 $pathinfo = substr($simple, length($sofar));
1850 $pathinfo .= "/" if ($page =~ /\/$/);
1851 $scriptname = $sofar;
1856 # Don't stop at a directory unless this is the last theme, which
1857 # is the 'real' one that provides the .cgi scripts
1858 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1865 $cgi_pwd = $roots[0];
1867 elsif ($is_directory) {
1868 $cgi_pwd = "$roots[0]$sofar";
1871 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1874 $foundroot = $preroot;
1875 if ($is_directory) {
1876 # Check for index files in the directory
1878 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1879 $idxfull = "$full/$idx";
1880 local @stidxfull = stat($idxfull);
1881 if (-r _ && !-d _) {
1883 @stfull = @stidxfull;
1886 if ($scriptname ne "/");
1891 @stfull = stat($full) if (!$foundidx);
1894 last if ($foundroot);
1896 print DEBUG "handle_request: initial full=$full\n";
1898 # Look in the real root directories, stopping when we find a file or directory
1899 if (!$full || $is_directory) {
1900 ROOT: foreach $root (@roots) {
1902 $full = $root.$sofar;
1903 $scriptname = $simple;
1904 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
1905 if ($b ne "") { $sofar .= "/$b"; }
1906 $full = $root.$sofar;
1907 @stfull = stat($full);
1912 # Check if this is a directory
1914 # It is.. go on parsing
1918 # Check if this is a CGI program
1919 if (&get_type($full) eq "internal/cgi") {
1920 $pathinfo = substr($simple, length($sofar));
1921 $pathinfo .= "/" if ($page =~ /\/$/);
1922 $scriptname = $sofar;
1927 # Run CGI in the same directory as whatever file
1929 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
1938 if (!@stfull) { &http_error(404, "File not found"); }
1940 print DEBUG "handle_request: full=$full\n";
1941 @stfull = stat($full) if (!@stfull);
1943 # check filename against denyfile regexp
1944 local $denyfile = $config{'denyfile'};
1945 if ($denyfile && $full =~ /$denyfile/) {
1946 &http_error(403, "Access denied to $page");
1950 # Reached the end of the path OK.. see what we've got
1952 # See if the URL ends with a / as it should
1953 print DEBUG "handle_request: found a directory\n";
1954 if ($page !~ /\/$/) {
1955 # It doesn't.. redirect
1956 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1957 $ssl = $use_ssl || $config{'inetd_ssl'};
1958 $portstr = $port == 80 && !$ssl ? "" :
1959 $port == 443 && $ssl ? "" : ":$port";
1960 &write_data("Date: $datestr\r\n");
1961 &write_data("Server: $config{server}\r\n");
1962 $prot = $ssl ? "https" : "http";
1963 &write_data("Location: $prot://$host$portstr$page/\r\n");
1964 &write_keep_alive(0);
1965 &write_data("\r\n");
1966 &log_request($acpthost, $authuser, $reqline, 302, 0);
1969 # A directory.. check for index files
1971 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1972 $idxfull = "$full/$idx";
1973 @stidxfull = stat($idxfull);
1974 if (-r _ && !-d _) {
1977 @stfull = @stidxfull;
1978 $scriptname .= "/" if ($scriptname ne "/");
1983 @stfull = stat($full) if (!$foundidx);
1986 # This is definately a directory.. list it
1987 print DEBUG "handle_request: listing directory\n";
1988 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
1989 "Date: $datestr\r\n".
1990 "Server: $config{server}\r\n".
1991 "Content-type: text/html\r\n";
1993 &write_keep_alive(0);
1994 &write_data("\r\n");
1995 &reset_byte_count();
1996 &write_data("<h1>Index of $simple</h1>\n");
1997 &write_data("<pre>\n");
1998 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
1999 "Name", "Last Modified", "Size");
2000 &write_data("<hr>\n");
2001 opendir(DIR, $full);
2002 while($df = readdir(DIR)) {
2003 if ($df =~ /^\./) { next; }
2004 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2005 (@stbuf = stat($fulldf)) || next;
2006 if (-d _) { $df .= "/"; }
2007 @tm = localtime($stbuf[9]);
2008 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2009 $tm[3],$tm[4]+1,$tm[5]+1900,
2010 $tm[0],$tm[1],$tm[2];
2011 $len = length($df); $rest = " "x(35-$len);
2013 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2014 $df, $df, $fdate, $stbuf[7]);
2017 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2021 # CGI or normal file
2023 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2024 # A CGI program to execute
2025 print DEBUG "handle_request: executing CGI\n";
2026 $envtz = $ENV{"TZ"};
2027 $envuser = $ENV{"USER"};
2028 $envpath = $ENV{"PATH"};
2029 $envlang = $ENV{"LANG"};
2030 $envroot = $ENV{"SystemRoot"};
2031 $envperllib = $ENV{'PERLLIB'};
2032 foreach my $k (keys %ENV) {
2035 $ENV{"PATH"} = $envpath if ($envpath);
2036 $ENV{"TZ"} = $envtz if ($envtz);
2037 $ENV{"USER"} = $envuser if ($envuser);
2038 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2039 $ENV{"SystemRoot"} = $envroot if ($envroot);
2040 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2041 $ENV{"HOME"} = $user_homedir;
2042 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2043 $ENV{"SERVER_NAME"} = $host;
2044 $ENV{"SERVER_ADMIN"} = $config{"email"};
2045 $ENV{"SERVER_ROOT"} = $roots[0];
2046 $ENV{"SERVER_REALROOT"} = $realroot;
2047 $ENV{"SERVER_PORT"} = $port;
2048 $ENV{"REMOTE_HOST"} = $acpthost;
2049 $ENV{"REMOTE_ADDR"} = $acptip;
2050 $ENV{"REMOTE_USER"} = $authuser;
2051 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2052 $baseauthuser : undef;
2053 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2054 $config{'pass_password'});
2055 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2056 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2057 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2058 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2059 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2060 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2061 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2062 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2063 $ENV{"REQUEST_METHOD"} = $method;
2064 $ENV{"SCRIPT_NAME"} = $scriptname;
2065 $ENV{"SCRIPT_FILENAME"} = $full;
2066 $ENV{"REQUEST_URI"} = $request_uri;
2067 $ENV{"PATH_INFO"} = $pathinfo;
2069 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2070 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2072 $ENV{"QUERY_STRING"} = $querystring;
2073 $ENV{"MINISERV_CONFIG"} = $config_file;
2074 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2075 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2076 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2077 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2078 if (defined($header{"content-length"})) {
2079 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2081 if (defined($header{"content-type"})) {
2082 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2084 foreach $h (keys %header) {
2085 ($hname = $h) =~ tr/a-z/A-Z/;
2087 $ENV{"HTTP_$hname"} = $header{$h};
2089 $ENV{"PWD"} = $cgi_pwd;
2090 foreach $k (keys %config) {
2091 if ($k =~ /^env_(\S+)$/) {
2092 $ENV{$1} = $config{$k};
2095 delete($ENV{'HTTP_AUTHORIZATION'});
2096 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2097 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2099 # Check if the CGI can be handled internally
2101 local $first = <CGI>;
2103 $first =~ s/[#!\r\n]//g;
2104 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2106 if (!$config{'forkcgis'} &&
2107 ($first eq $perl_path || $first eq $linked_perl_path) &&
2109 $config{'internalcgis'}) {
2110 # setup environment for eval
2112 @ARGV = split(/\s+/, $queryargs);
2115 # Already read the post input
2116 $postinput = $posted_data;
2118 $clen = $header{"content-length"};
2119 $SIG{'CHLD'} = 'DEFAULT';
2121 # Have SOCK closed if the perl exec's something
2123 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2127 if ($config{'log'}) {
2128 open(MINISERVLOG, ">>$config{'logfile'}");
2129 if ($config{'logperms'}) {
2130 chmod(oct($config{'logperms'}),
2131 $config{'logfile'});
2134 chmod(0600, $config{'logfile'});
2138 $main_process_id = $$;
2140 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2141 # Eval in package from Webmin module name
2143 $pkg =~ s/[^A-Za-z0-9]/_/g;
2148 tie(*STDOUT, 'miniserv');
2149 tie(*STDIN, 'miniserv');
2150 do \$miniserv::full;
2156 &http_error(500, "Perl execution failed",
2157 $config{'noshowstderr'} ? undef : $@);
2159 elsif (!$doneheaders && !$nph_script) {
2160 &http_error(500, "Missing Headers");
2167 # fork the process that actually executes the CGI
2168 pipe(CGIINr, CGIINw);
2169 pipe(CGIOUTr, CGIOUTw);
2170 pipe(CGIERRr, CGIERRw);
2171 if (!($cgipid = fork())) {
2172 @execargs = ( $full, split(/\s+/, $queryargs) );
2175 open(STDIN, "<&CGIINr");
2176 open(STDOUT, ">&CGIOUTw");
2177 open(STDERR, ">&CGIERRw");
2178 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2180 die "Failed to exec $full : $!\n";
2183 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2186 # write CGI input to a temp file
2187 $infile = "$config{'tempbase'}.$$";
2188 open(CGIINw, ">$infile");
2189 # NOT binary mode, as CGIs don't read in it!
2194 # already read the posted data
2195 print CGIINw $posted_data;
2197 $clen = $header{"content-length"};
2198 if ($method eq "POST" && $clen_read < $clen) {
2199 $SIG{'PIPE'} = 'IGNORE';
2201 while($got < $clen) {
2202 $buf = &read_data($clen-$got);
2203 if (!length($buf)) {
2204 kill('TERM', $cgipid);
2205 unlink($infile) if ($infile);
2206 &http_error(500, "Failed to read ".
2209 $got += length($buf);
2210 local ($wrote) = (print CGIINw $buf);
2213 # If the CGI terminated early, we still need to read
2214 # from the browser and throw away
2215 while($got < $clen) {
2216 $buf = &read_data($clen-$got);
2217 if (!length($buf)) {
2218 kill('TERM', $cgipid);
2219 unlink($infile) if ($infile);
2220 &http_error(500, "Failed to read ".
2223 $got += length($buf);
2225 $SIG{'PIPE'} = 'DEFAULT';
2231 # Run the CGI program, and feed it input
2233 local $qqueryargs = join(" ", map { "\"$_\"" }
2234 split(/\s+/, $queryargs));
2235 if ($first =~ /(perl|perl.exe)$/i) {
2236 # On Windows, run with Perl
2237 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2240 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2246 # read back cgi headers
2247 select(CGIOUTr); $|=1; select(STDOUT);
2251 $line =~ s/\r|\n//g;
2253 if ($got_blank || %cgiheader) { last; }
2257 if ($line !~ /^(\S+):\s+(.*)$/) {
2258 $errs = &read_errors(CGIERRr);
2259 close(CGIOUTr); close(CGIERRr);
2260 unlink($infile) if ($infile);
2261 &http_error(500, "Bad Header", $errs);
2263 $cgiheader{lc($1)} = $2;
2264 push(@cgiheader, [ $1, $2 ]);
2266 if ($cgiheader{"location"}) {
2267 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2268 &write_data("Date: $datestr\r\n");
2269 &write_data("Server: $config{'server'}\r\n");
2270 &write_keep_alive(0);
2271 # ignore the rest of the output. This is a hack,
2272 # but is necessary for IE in some cases :(
2273 close(CGIOUTr); close(CGIERRr);
2275 elsif ($cgiheader{"content-type"} eq "") {
2276 close(CGIOUTr); close(CGIERRr);
2277 unlink($infile) if ($infile);
2278 $errs = &read_errors(CGIERRr);
2279 &http_error(500, "Missing Content-Type Header",
2280 $config{'noshowstderr'} ? undef : $errs);
2283 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2284 &write_data("Date: $datestr\r\n");
2285 &write_data("Server: $config{'server'}\r\n");
2286 &write_keep_alive(0);
2288 foreach $h (@cgiheader) {
2289 &write_data("$h->[0]: $h->[1]\r\n");
2291 &write_data("\r\n");
2293 &reset_byte_count();
2294 while($line = <CGIOUTr>) {
2299 unlink($infile) if ($infile);
2305 print DEBUG "handle_request: outputting file\n";
2306 open(FILE, $full) || &http_error(404, "Failed to open file");
2308 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2309 "Date: $datestr\r\n".
2310 "Server: $config{server}\r\n".
2311 "Content-type: ".&get_type($full)."\r\n".
2312 "Content-length: $stfull[7]\r\n".
2313 "Last-Modified: ".&http_date($stfull[9])."\r\n".
2314 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2316 $rv = &write_keep_alive();
2317 &write_data("\r\n");
2318 &reset_byte_count();
2319 while(read(FILE, $buf, 1024) > 0) {
2326 &log_request($acpthost, $authuser, $reqline,
2327 $logged_code ? $logged_code :
2328 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2332 # http_error(code, message, body, [dontexit])
2335 local $eh = $error_handler_recurse ? undef :
2336 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2337 $config{'error_handler'} ? $config{'error_handler'} : undef;
2338 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2340 # Call a CGI program for the error
2342 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2343 "&body=".&urlize($_[2]);
2344 $error_handler_recurse++;
2346 $ok_message = $_[1];
2350 # Use the standard error message display
2351 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2352 &write_data("Server: $config{server}\r\n");
2353 &write_data("Date: $datestr\r\n");
2354 &write_data("Content-type: text/html\r\n");
2355 &write_keep_alive(0);
2356 &write_data("\r\n");
2357 &reset_byte_count();
2358 &write_data("<h1>Error - $_[1]</h1>\n");
2360 &write_data("<pre>$_[2]</pre>\n");
2363 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2365 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2372 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2378 return "text/plain";
2381 # simplify_path(path, bogus)
2382 # Given a path, maybe containing stuff like ".." and "." convert it to a
2383 # clean, absolute form.
2386 local($dir, @bits, @fixedbits, $b);
2388 $dir =~ s/\\/\//g; # fix windows \ in path
2391 $dir =~ s/\0//g; # remove null bytes
2392 @bits = split(/\/+/, $dir);
2395 foreach $b (@bits) {
2399 elsif ($b eq ".." || $b eq "...") {
2401 if (scalar(@fixedbits) == 0) {
2409 push(@fixedbits, $b);
2412 return "/" . join('/', @fixedbits);
2416 # Converts a string from base64 format to normal
2419 local($str) = $_[0];
2421 $str =~ tr|A-Za-z0-9+=/||cd;
2423 $str =~ tr|A-Za-z0-9+/| -_|;
2424 while ($str =~ /(.{1,60})/gs) {
2425 my $len = chr(32 + length($1)*3/4);
2426 $res .= unpack("u", $len . $1 );
2431 # ip_match(remoteip, localip, [match]+)
2432 # Checks an IP address against a list of IPs, networks and networks/masks
2435 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2436 @io = split(/\./, $_[0]);
2437 for($i=2; $i<@_; $i++) {
2438 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2440 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2441 $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
2442 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2443 $ip_match_cache{$_[0]} = $hn;
2445 for($i=2; $i<@_; $i++) {
2446 local $mismatch = 0;
2447 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2448 # Convert CIDR to netmask format
2449 $_[$i] = $1."/".&prefix_to_mask($2);
2451 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2452 # Compare with network/mask
2453 @mo = split(/\./, $1); @ms = split(/\./, $2);
2454 for($j=0; $j<4; $j++) {
2455 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2460 elsif ($_[$i] =~ /^\*(\S+)$/) {
2461 # Compare with hostname regexp
2462 $mismatch = 1 if ($hn !~ /$1$/);
2464 elsif ($_[$i] eq 'LOCAL') {
2465 # Compare with local network
2466 local @lo = split(/\./, $_[1]);
2468 $mismatch = 1 if ($lo[0] != $io[0]);
2470 elsif ($lo[0] < 192) {
2471 $mismatch = 1 if ($lo[0] != $io[0] ||
2475 $mismatch = 1 if ($lo[0] != $io[0] ||
2480 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2481 # Compare with hostname
2482 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2485 # Compare with IP or network
2486 @mo = split(/\./, $_[$i]);
2487 while(@mo && !$mo[$#mo]) { pop(@mo); }
2488 for($j=0; $j<@mo; $j++) {
2489 if ($mo[$j] != $io[$j]) {
2494 return 1 if (!$mismatch);
2499 # users_match(&uinfo, user, ...)
2500 # Returns 1 if a user is in a list of users and groups
2503 local $uinfo = shift(@_);
2505 local @ginfo = getgrgid($uinfo->[3]);
2507 if ($u =~ /^\@(\S+)$/) {
2508 return 1 if (&is_group_member($uinfo, $1));
2510 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2511 return (!$1 || $uinfo[2] >= $1) &&
2512 (!$2 || $uinfo[2] <= $2);
2515 return 1 if ($u eq $uinfo->[0]);
2521 # restart_miniserv()
2522 # Called when a SIGHUP is received to restart the web server. This is done
2523 # by exec()ing perl with the same command line as was originally used
2524 sub restart_miniserv
2526 print STDERR "restarting miniserv\n";
2527 &log_error("Restarting");
2529 &close_all_sockets();
2531 dbmclose(%sessiondb);
2532 kill('KILL', $logclearer) if ($logclearer);
2533 kill('KILL', $extauth) if ($extauth);
2534 exec($perl_path, $miniserv_path, @miniserv_argv);
2535 die "Failed to restart miniserv with $perl_path $miniserv_path";
2552 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2553 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/) { push(@rv, $i); }
2554 else { push(@rv, join('.', unpack("CCCC", inet_aton($i)))); }
2556 return wantarray ? @rv : $rv[0];
2559 # read_line(no-wait, no-limit)
2560 # Reads one line from SOCK or SSL
2563 local ($nowait, $nolimit) = @_;
2564 local($idx, $more, $rv);
2565 while(($idx = index($main::read_buffer, "\n")) < 0) {
2566 if (length($main::read_buffer) > 10000 && !$nolimit) {
2567 &http_error(414, "Request too long",
2568 "Received excessive line <pre>$main::read_buffer</pre>");
2571 # need to read more..
2572 &wait_for_data_error() if (!$nowait);
2574 $more = Net::SSLeay::read($ssl_con);
2577 local $ok = sysread(SOCK, $more, 1024);
2578 $more = undef if ($ok <= 0);
2582 $rv = $main::read_buffer;
2583 undef($main::read_buffer);
2586 $main::read_buffer .= $more;
2588 $rv = substr($main::read_buffer, 0, $idx+1);
2589 $main::read_buffer = substr($main::read_buffer, $idx+1);
2594 # Reads up to some amount of data from SOCK or the SSL connection
2598 if (length($main::read_buffer)) {
2599 if (length($main::read_buffer) > $_[0]) {
2600 # Return the first part of the buffer
2601 $rv = substr($main::read_buffer, 0, $_[0]);
2602 $main::read_buffer = substr($main::read_buffer, $_[0]);
2606 # Return the whole buffer
2607 $rv = $main::read_buffer;
2608 undef($main::read_buffer);
2613 # Call SSL read function
2614 return Net::SSLeay::read($ssl_con, $_[0]);
2617 # Just do a normal read
2619 sysread(SOCK, $buf, $_[0]) || return undef;
2625 # Read a line from a file handle, using sysread to get a byte at a time
2632 $got = sysread($fh, $buf, 1);
2633 last if ($got <= 0);
2635 last if ($buf eq "\n");
2640 # wait_for_data(secs)
2641 # Waits at most the given amount of time for some data on SOCK, returning
2642 # 0 if not found, 1 if some arrived.
2646 vec($rmask, fileno(SOCK), 1) = 1;
2647 local $got = select($rmask, undef, undef, $_[0]);
2648 return $got == 0 ? 0 : 1;
2651 # wait_for_data_error()
2652 # Waits 60 seconds for data on SOCK, and fails if none arrives
2653 sub wait_for_data_error
2655 local $got = &wait_for_data(60);
2657 &http_error(400, "Timeout",
2658 "Waited more than 60 seconds for request data");
2662 # write_data(data, ...)
2663 # Writes a string to SOCK or the SSL connection
2666 local $str = join("", @_);
2668 Net::SSLeay::write($ssl_con, $str);
2671 syswrite(SOCK, $str, length($str));
2673 # Intentionally introduce a small delay to avoid problems where IE reports
2674 # the page as empty / DNS failed when it get a large response too quickly!
2675 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2676 $write_data_count += length($str);
2679 # reset_byte_count()
2680 sub reset_byte_count { $write_data_count = 0; }
2683 sub byte_count { return $write_data_count; }
2685 # log_request(hostname, user, request, code, bytes)
2688 if ($config{'log'}) {
2689 local ($user, $ident, $headers);
2690 if ($config{'logident'}) {
2691 # add support for rfc1413 identity checking here
2693 else { $ident = "-"; }
2694 $user = $_[1] ? $_[1] : "-";
2695 local $dstr = &make_datestr();
2696 if (fileno(MINISERVLOG)) {
2697 seek(MINISERVLOG, 0, 2);
2700 open(MINISERVLOG, ">>$config{'logfile'}");
2701 chmod(0600, $config{'logfile'});
2703 if (defined($config{'logheaders'})) {
2704 foreach $h (split(/\s+/, $config{'logheaders'})) {
2705 $headers .= " $h=\"$header{$h}\"";
2708 elsif ($config{'logclf'}) {
2709 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2714 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2715 "$_[3] $_[4]$headers\n";
2723 local @tm = localtime(time());
2724 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2725 $tm[3], $month[$tm[4]], $tm[5]+1900,
2726 $tm[2], $tm[1], $tm[0], $timezone;
2729 # log_error(message)
2733 print STDERR "[",&make_datestr(),"] ",
2734 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2735 $page ? ( $page," : " ) : ( ),
2739 # read_errors(handle)
2740 # Read and return all input from some filehandle
2743 local($fh, $_, $rv);
2745 while(<$fh>) { $rv .= $_; }
2749 sub write_keep_alive
2752 if ($config{'nokeepalive'}) {
2753 # Keep alives have been disabled in config
2756 elsif (@childpids > $config{'maxconns'}*.8) {
2757 # Disable because nearing process limit
2761 # Keep alive specified by caller
2765 # Keep alive determined by browser
2766 $mode = $header{'connection'} =~ /keep-alive/i;
2768 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2774 kill('TERM', @childpids) if (@childpids);
2775 kill('KILL', $logclearer) if ($logclearer);
2776 kill('KILL', $extauth) if ($extauth);
2782 local @tm = gmtime($_[0]);
2783 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2784 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2785 $tm[2], $tm[1], $tm[0];
2790 my $i; bless \$i, shift;
2796 my($buf,$len,$offset) = @_;
2797 &write_to_sock(substr($buf, $offset, $len));
2804 my $buf = join(defined($,) ? $, : "", @_);
2805 $buf .= $\ if defined($\);
2806 &write_to_sock($buf);
2813 &write_to_sock(sprintf $fmt, @_);
2816 # Send back already read data while we have it, then read from SOCK
2820 my $bufref = \$_[0];
2823 if ($postpos < length($postinput)) {
2824 # Reading from already fetched array
2825 my $left = length($postinput) - $postpos;
2826 my $canread = $len > $left ? $left : $len;
2827 substr($$bufref, $offset, $canread) =
2828 substr($postinput, $postpos, $canread);
2829 $postpos += $canread;
2833 # Read from network socket
2834 local $data = &read_data($len);
2835 if ($data eq '' && $len) {
2837 print STDERR "finished reading - shutting down socket\n";
2840 substr($$bufref, $offset, length($data)) = $data;
2841 return length($data);
2847 #print STDERR "open() called - should never happen!\n";
2850 # Read a line of input
2854 if ($postpos < length($postinput) &&
2855 ($idx = index($postinput, "\n", $postpos)) >= 0) {
2856 # A line exists in the memory buffer .. use it
2857 my $line = substr($postinput, $postpos, $idx-$postpos+1);
2862 # Need to read from the socket
2864 if ($postpos < length($postinput)) {
2865 # Start with in-memory data
2866 $line = substr($postinput, $postpos);
2867 $postpos = length($postinput);
2869 my $nl = &read_line(0, 1);
2872 print STDERR "finished reading - shutting down socket\n";
2875 $line .= $nl if (defined($nl));
2880 # Read one character of input
2885 my $got = READ($r, \$buf, 1, 0);
2886 return $got > 0 ? $buf : undef;
2891 return fileno(SOCK);
2898 # write_to_sock(data, ...)
2903 if ($doneheaders || $miniserv::nph_script) {
2908 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
2909 if ($1 =~ /^(\S+):\s+(.*)$/) {
2910 $cgiheader{lc($1)} = $2;
2911 push(@cgiheader, [ $1, $2 ]);
2913 elsif ($1 !~ /\S/) {
2917 &http_error(500, "Bad Header");
2921 if ($cgiheader{"location"}) {
2923 "HTTP/1.0 302 Moved Temporarily\r\n");
2924 &write_data("Date: $datestr\r\n");
2925 &write_data("Server: $config{server}\r\n");
2926 &write_keep_alive(0);
2928 elsif ($cgiheader{"content-type"} eq "") {
2929 &http_error(500, "Missing Content-Type Header");
2932 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2933 &write_data("Date: $datestr\r\n");
2934 &write_data("Server: $config{server}\r\n");
2935 &write_keep_alive(0);
2937 foreach $h (@cgiheader) {
2938 &write_data("$h->[0]: $h->[1]\r\n");
2940 &write_data("\r\n");
2941 &reset_byte_count();
2942 &write_data($headers);
2950 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
2952 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
2953 $verified_client = 1 if (!$errnum);
2960 if ($doing_eval && $$ == $main_process_id) {
2961 # A CGI program called exit! This is a horrible hack to
2962 # finish up before really exiting
2965 close($PASSINw); close($PASSOUTw);
2966 &log_request($acpthost, $authuser, $reqline,
2967 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2972 # Convert a string to a form ok for putting in a URL
2974 local($tmp, $tmp2, $c);
2977 while(($c = chop($tmp)) ne "") {
2978 if ($c !~ /[A-z0-9]/) {
2979 $c = sprintf("%%%2.2X", ord($c));
2986 # validate_user(username, password, host)
2987 # Checks if some username and password are valid. Returns the modified username,
2988 # the expired / temp pass flag, and the non-existence flag
2991 local ($user, $pass, $host) = @_;
2992 return ( ) if (!$user);
2993 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
2994 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
2995 &can_user_login($user, undef, $host);
2996 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
2998 # User doesn't even exist, so go no further
2999 return ( undef, 0, 1 );
3001 elsif ($canmode == 0) {
3002 # User does exist but cannot login
3003 return ( $canuser, 0, 0 );
3005 elsif ($canmode == 1) {
3006 # Attempt Webmin authentication
3007 if ($users{$webminuser} eq
3008 &password_crypt($pass, $users{$webminuser})) {
3009 # Password is valid .. but check for expiry
3010 local $lc = $lastchanges{$user};
3011 if ($config{'pass_maxdays'} && $lc && !$nochange{$user}) {
3012 local $daysold = (time() - $lc)/(24*60*60);
3013 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$temppass{$user}\n";
3014 if ($config{'pass_lockdays'} &&
3015 $daysold > $config{'pass_lockdays'}) {
3016 # So old that the account is locked
3017 return ( undef, 0, 0 );
3019 elsif ($daysold > $config{'pass_maxdays'}) {
3020 # Password has expired
3021 return ( $user, 1, 0 );
3024 if ($temppass{$user}) {
3025 # Temporary password - force change now
3026 return ( $user, 2, 0 );
3028 return ( $user, 0, 0 );
3031 return ( undef, 0, 0 );
3034 elsif ($canmode == 2 || $canmode == 3) {
3035 # Attempt PAM or passwd file authentication
3036 local $val = &validate_unix_user($canuser, $pass);
3037 print DEBUG "validate_user: unix val=$val\n";
3038 if ($val && $sudo) {
3039 # Need to check if this Unix user can sudo
3040 if (!&check_sudo_permissions($canuser, $pass)) {
3041 print DEBUG "validate_user: sudo failed\n";
3045 print DEBUG "validate_user: sudo passed\n";
3048 return $val == 2 ? ( $canuser, 1, 0 ) :
3049 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3051 elsif ($canmode == 4) {
3052 # Attempt external authentication
3053 return &validate_external_user($canuser, $pass) ?
3054 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3062 # validate_unix_user(user, password)
3063 # Returns 1 if a username and password are valid under unix, 0 if not,
3064 # or 2 if the account has expired.
3065 # Checks PAM if available, and falls back to reading the system password
3067 sub validate_unix_user
3071 $pam_username = $_[0];
3072 $pam_password = $_[1];
3073 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3076 local $pam_ret = $pamh->pam_authenticate();
3077 if ($pam_ret == PAM_SUCCESS()) {
3078 # Logged in OK .. make sure password hasn't expired
3079 local $acct_ret = $pamh->pam_acct_mgmt();
3080 if ($acct_ret == PAM_SUCCESS()) {
3081 $pamh->pam_open_session();
3084 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3085 $acct_ret == PAM_ACCT_EXPIRED()) {
3089 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3096 elsif ($config{'pam_only'}) {
3097 # Pam is not available, but configuration forces it's use!
3100 elsif ($config{'passwd_file'}) {
3101 # Check in a password file
3103 open(FILE, $config{'passwd_file'});
3104 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3105 # Assume in AIX format
3108 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3110 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3111 $rv = $1 eq &password_crypt($_[1], $1) ?
3119 # Read the system password or shadow file
3121 local @l = split(/:/, $_, -1);
3122 local $u = $l[$config{'passwd_uindex'}];
3123 local $p = $l[$config{'passwd_pindex'}];
3125 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3126 if ($config{'passwd_cindex'} ne '' && $rv) {
3127 # Password may have expired!
3128 local $c = $l[$config{'passwd_cindex'}];
3129 local $m = $l[$config{'passwd_mindex'}];
3130 local $day = time()/(24*60*60);
3131 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3137 if ($p eq "" && $config{'passwd_blank'}) {
3138 # Force password change
3146 return $rv if ($rv);
3149 # Fallback option - check password returned by getpw*
3150 local @uinfo = getpwnam($_[0]);
3151 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3155 return 0; # Totally failed
3158 # validate_external_user(user, pass)
3159 # Validate a user by passing the username and password to an external
3160 # squid-style authentication program
3161 sub validate_external_user
3163 return 0 if (!$config{'extauth'});
3165 local $str = "$_[0] $_[1]\n";
3166 syswrite(EXTAUTH, $str, length($str));
3167 local $resp = <EXTAUTH>;
3169 return $resp =~ /^OK/i ? 1 : 0;
3172 # can_user_login(username, no-append, host)
3173 # Checks if a user can login or not.
3174 # First return value is the username.
3175 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3176 # file, 4 if external.
3177 # Third is 1 if the user does not exist at all, 0 if he does.
3178 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3179 # Fifth is a flag indicating if a sudo check is needed.
3182 if (!$users{$_[0]}) {
3183 # See if this user exists in Unix and can be validated by the same
3184 # method as the unixauth webmin user
3185 local $realuser = $unixauth{$_[0]};
3189 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3190 if (!$realuser && @uinfo) {
3191 # No unixauth entry for the username .. try his groups
3192 foreach my $ua (keys %unixauth) {
3193 if ($ua =~ /^\@(.*)$/) {
3194 if (&is_group_member(\@uinfo, $1)) {
3195 $realuser = $unixauth{$ua};
3201 if (!$realuser && @uinfo) {
3202 # Fall back to unix auth for all Unix users
3203 $realuser = $unixauth{"*"};
3205 if (!$realuser && $use_sudo && @uinfo) {
3206 # Allow login effectively as root, if sudo permits it
3210 if (!$realuser && !@uinfo && $config{'pamany'}) {
3211 # If the user completely doesn't exist, we can still allow
3212 # him to authenticate via PAM
3213 $realuser = $config{'pamany'};
3217 # For Usermin, always fall back to unix auth for any user,
3218 # so that later checks with domain added / removed are done.
3219 $realuser = $unixauth{"*"};
3221 return (undef, 0, 1, undef) if (!$realuser);
3222 local $up = $users{$realuser};
3223 return (undef, 0, 1, undef) if (!defined($up));
3225 # Work out possible domain names from the hostname
3226 local @doms = ( $_[2] );
3227 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3231 if ($config{'user_mapping'} && !defined(%user_mapping)) {
3232 # Read the user mapping file
3234 open(MAPPING, $config{'user_mapping'});
3238 if (/^(\S+)\s+(\S+)/) {
3239 if ($config{'user_mapping_reverse'}) {
3240 $user_mapping{$1} = $2;
3243 $user_mapping{$2} = $1;
3250 # Check the user mapping file to see if there is an entry for the
3251 # user login in which specifies a new effective user
3253 foreach my $d (@doms) {
3254 $um ||= $user_mapping{"$_[0]\@$d"};
3256 $um ||= $user_mapping{$_[0]};
3257 if (defined($um) && ($_[1]&4) == 0) {
3258 # A mapping exists - use it!
3259 return &can_user_login($um, $_[1]+4, $_[2]);
3262 # Check if a user with the entered login and the domains appended
3263 # or prepended exists, and if so take it to be the effective user
3264 if (!@uinfo && $config{'domainuser'}) {
3265 # Try again with name.domain and name.firstpart
3266 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3267 if (($_[1]&1) == 0) {
3269 foreach $a (@firsts, @doms) {
3270 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3271 "${a}.$_[0]", "${a}-$_[0]",
3272 "$_[0]_${a}", "${a}_$_[0]") {
3273 local @vu = &can_user_login(
3274 $p, $_[1]+1, $_[2]);
3275 return @vu if ($vu[1]);
3281 # Check if the user entered a domain at the end of his username when
3282 # he really shouldn't have, and if so try without it
3283 if (!@uinfo && $config{'domainstrip'} &&
3284 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3285 local ($stripped, $dom) = ($1, $2);
3286 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3287 return @vu if ($vu[1]);
3288 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3289 return @vu if ($vu[1]);
3292 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3295 if (defined(@allowusers)) {
3296 # Only allow people on the allow list
3297 return ( undef, 0, 0, undef )
3298 if (!&users_match(\@uinfo, @allowusers));
3300 elsif (defined(@denyusers)) {
3301 # Disallow people on the deny list
3302 return ( undef, 0, 0, undef )
3303 if (&users_match(\@uinfo, @denyusers));
3305 if ($config{'shells_deny'}) {
3307 open(SHELLS, $config{'shells_deny'});
3311 $found++ if ($_ eq $uinfo[8]);
3314 return ( undef, 0, 0, undef ) if (!$found);
3319 # PAM or passwd file authentication
3320 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3322 elsif ($up eq 'e') {
3323 # External authentication
3324 return ( $_[0], 4, 0, $realuser, $sudo );
3327 # Fixed Webmin password
3328 return ( $_[0], 1, 0, $realuser, $sudo );
3331 elsif ($users{$_[0]} eq 'x') {
3332 # Webmin user authenticated via PAM or password file
3333 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3335 elsif ($users{$_[0]} eq 'e') {
3336 # Webmin user authenticated externally
3337 return ( $_[0], 4, 0, $_[0] );
3340 # Normal Webmin user
3341 return ( $_[0], 1, 0, $_[0] );
3345 # the PAM conversation function for interactive logins
3348 $pam_conv_func_called++;
3355 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3356 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3358 push @res, PAM_SUCCESS();
3361 push @res, PAM_SUCCESS();
3370 # get_socket_name(handle)
3371 # Returns the local hostname or IP address of some connection
3374 return $config{'host'} if ($config{'host'});
3375 local $sn = getsockname($_[0]);
3376 return undef if (!$sn);
3377 local $myaddr = (unpack_sockaddr_in($sn))[1];
3378 if (!$get_socket_name_cache{$myaddr}) {
3380 if (!$config{'no_resolv_myname'}) {
3381 $myname = gethostbyaddr($myaddr, AF_INET);
3383 if ($myname eq "") {
3384 $myname = inet_ntoa($myaddr);
3386 $get_socket_name_cache{$myaddr} = $myname;
3388 return $get_socket_name_cache{$myaddr};
3391 # run_login_script(username, sid, remoteip, localip)
3392 sub run_login_script
3394 if ($config{'login_script'}) {
3395 system($config{'login_script'}.
3396 " ".join(" ", map { quotemeta($_) || '""' } @_).
3397 " >/dev/null 2>&1 </dev/null");
3401 # run_logout_script(username, sid, remoteip, localip)
3402 sub run_logout_script
3404 if ($config{'logout_script'}) {
3405 system($config{'logout_script'}.
3406 " ".join(" ", map { quotemeta($_) || '""' } @_).
3407 " >/dev/null 2>&1 </dev/null");
3411 # close_all_sockets()
3412 # Closes all the main listening sockets
3413 sub close_all_sockets
3416 foreach $s (@socketfhs) {
3422 # Close all pipes for talking to sub-processes
3426 foreach $p (@passin) { close($p); }
3427 foreach $p (@passout) { close($p); }
3428 foreach $p (values %conversations) {
3429 if ($p->{'PAMOUTr'}) {
3430 close($p->{'PAMOUTr'});
3431 close($p->{'PAMINw'});
3436 # check_user_ip(user)
3437 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3441 &ip_match($acptip, $localip, @{$deny{$_[0]}}) ||
3443 !&ip_match($acptip, $localip, @{$allow{$_[0]}})) {
3449 # check_user_time(user)
3450 # Returns 1 if some user is allowed to login at the current date and time
3453 return 1 if (!$allowdays{$_[0]} && !$allowhours{$_[0]});
3454 local @tm = localtime(time());
3455 if ($allowdays{$_[0]}) {
3456 # Make sure day is allowed
3457 return 0 if (&indexof($tm[6], @{$allowdays{$_[0]}}) < 0);
3459 if ($allowhours{$_[0]}) {
3460 # Make sure time is allowed
3461 local $m = $tm[2]*60+$tm[1];
3462 return 0 if ($m < $allowhours{$_[0]}->[0] ||
3463 $m > $allowhours{$_[0]}->[1]);
3468 # generate_random_id(password, [force-urandom])
3469 # Returns a random session ID number
3470 sub generate_random_id
3472 local ($pass, $force_urandom) = @_;
3474 if (!$bad_urandom) {
3475 # First try /dev/urandom, unless we have marked it as bad
3476 $SIG{ALRM} = "miniserv::urandom_timeout";
3478 if (open(RANDOM, "/dev/urandom")) {
3480 if (read(RANDOM, $tmpsid, 16) == 16) {
3481 $sid = lc(unpack('h*',$tmpsid));
3487 if (!$sid && !$force_urandom) {
3490 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3491 $sid += ord($c) * $mul;
3498 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3499 # Called from handle_session to either mark a user as logged in, or not
3502 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3503 $authuser = $vu if ($ok);
3505 # check if the test cookie is set
3506 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3507 !$config{'no_testing_cookie'} && !$notest) {
3508 &http_error(500, "No cookies",
3509 "Your browser does not support cookies, ".
3510 "which are required for this web server to ".
3511 "work in session authentication mode");
3514 # check with main process for delay
3515 if ($config{'passdelay'} && $vu) {
3516 print $PASSINw "delay $vu $acptip $ok\n";
3517 <$PASSOUTr> =~ /(\d+) (\d+)/;
3522 if ($ok && (!$expired ||
3523 $config{'passwd_mode'} == 1)) {
3524 # Logged in OK! Tell the main process about
3526 local $sid = &generate_random_id($pass);
3527 print $PASSINw "new $sid $authuser $acptip\n";
3529 # Run the post-login script, if any
3530 &run_login_script($authuser, $sid,
3533 # Check for a redirect URL for the user
3534 local $rurl = &login_redirect($authuser, $pass, $host);
3536 # Got one .. go to it
3537 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3538 &write_data("Date: $datestr\r\n");
3539 &write_data("Server: $config{'server'}\r\n");
3540 &write_data("Location: $rurl\r\n");
3541 &write_keep_alive(0);
3542 &write_data("\r\n");
3543 &log_request($acpthost, $authuser, $reqline, 302, 0);
3546 # Set cookie and redirect to originally requested page
3547 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3548 &write_data("Date: $datestr\r\n");
3549 &write_data("Server: $config{'server'}\r\n");
3550 local $ssl = $use_ssl || $config{'inetd_ssl'};
3551 $portstr = $port == 80 && !$ssl ? "" :
3552 $port == 443 && $ssl ? "" : ":$port";
3553 $prot = $ssl ? "https" : "http";
3554 local $sec = $ssl ? "; secure" : "";
3555 #$sec .= "; httpOnly";
3557 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3560 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3562 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3563 &write_keep_alive(0);
3564 &write_data("\r\n");
3565 &log_request($acpthost, $authuser, $reqline, 302, 0);
3566 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3567 &write_login_utmp($authuser, $acpthost);
3571 elsif ($ok && $expired &&
3572 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3573 # Login was ok, but password has expired or was temporary. Need
3574 # to force display of password change form.
3577 $querystring = "&user=".&urlize($vu).
3579 "&expired=".$expired;
3582 $page = $config{'password_form'};
3584 $miniserv_internal = 2;
3585 syslog("crit", "%s",
3586 "Expired login as $vu ".
3587 "from $acpthost") if ($use_syslog);
3590 # Login failed, or password has expired. The login form will be
3591 # displayed again by later code
3593 $request_uri = $in{'page'};
3594 $already_session_id = undef;
3596 $authuser = $baseauthuser = undef;
3597 syslog("crit", "%s",
3598 ($nonexist ? "Non-existent" :
3599 $expired ? "Expired" : "Invalid").
3600 " login as $vu from $acpthost")
3606 # write_login_utmp(user, host)
3607 # Record the login by some user in utmp
3608 sub write_login_utmp
3611 # Write utmp record for login
3612 %utmp = ( 'ut_host' => $_[1],
3613 'ut_time' => time(),
3615 'ut_type' => 7, # user process
3616 'ut_pid' => $main_process_id,
3617 'ut_line' => $config{'pam'},
3619 if (defined(&User::Utmp::putut)) {
3620 User::Utmp::putut(\%utmp);
3623 User::Utmp::pututline(\%utmp);
3628 # write_logout_utmp(user, host)
3629 # Record the logout by some user in utmp
3630 sub write_logout_utmp
3633 # Write utmp record for logout
3634 %utmp = ( 'ut_host' => $_[1],
3635 'ut_time' => time(),
3637 'ut_type' => 8, # dead process
3638 'ut_pid' => $main_process_id,
3639 'ut_line' => $config{'pam'},
3641 if (defined(&User::Utmp::putut)) {
3642 User::Utmp::putut(\%utmp);
3645 User::Utmp::pututline(\%utmp);
3650 # pam_conversation_process(username, write-pipe, read-pipe)
3651 # This function is called inside a sub-process to communicate with PAM. It sends
3652 # questions down one pipe, and reads responses from another
3653 sub pam_conversation_process
3655 local ($user, $writer, $reader) = @_;
3656 $miniserv::pam_conversation_process_writer = $writer;
3657 $miniserv::pam_conversation_process_reader = $reader;
3658 local $convh = new Authen::PAM(
3659 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3660 local $pam_ret = $convh->pam_authenticate();
3661 if ($pam_ret == PAM_SUCCESS()) {
3662 local $acct_ret = $convh->pam_acct_mgmt();
3663 if ($acct_ret == PAM_SUCCESS()) {
3664 $convh->pam_open_session();
3665 print $writer "x2 $user 1 0 0\n";
3667 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3668 $acct_ret == PAM_ACCT_EXPIRED()) {
3669 print $writer "x2 $user 1 1 0\n";
3672 print $writer "x0 Unknown PAM account status $acct_ret\n";
3676 print $writer "x2 $user 0 0 0\n";
3681 # pam_conversation_process_func(type, message, [type, message, ...])
3682 # A pipe that talks to both PAM and the master process
3683 sub pam_conversation_process_func
3686 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3688 local ($type, $msg) = (shift, shift);
3690 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3691 print $miniserv::pam_conversation_process_writer "\n";
3692 local $answer = <$miniserv::pam_conversation_process_reader>;
3693 $answer =~ s/\r|\n//g;
3694 push(@rv, PAM_SUCCESS(), $answer);
3696 push(@rv, PAM_SUCCESS());
3701 # Returns 4 new pipe file handles
3704 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3706 local %taken = ( (map { $_, 1 } @passin),
3707 (map { $_->{'PASSINr'} } values %conversations) );
3708 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3709 $PASSINr = "PASSINr$p";
3710 $PASSINw = "PASSINw$p";
3711 $PASSOUTr = "PASSOUTr$p";
3712 $PASSOUTw = "PASSOUTw$p";
3713 pipe($PASSINr, $PASSINw);
3714 pipe($PASSOUTr, $PASSOUTw);
3715 select($PASSINw); $| = 1;
3716 select($PASSINr); $| = 1;
3717 select($PASSOUTw); $| = 1;
3718 select($PASSOUTw); $| = 1;
3720 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3723 # recv_pam_question(&conv, fd)
3724 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3725 # Returns 0 if the conversation is over, 1 if not.
3726 sub recv_pam_question
3728 local ($conf, $fh) = @_;
3729 local $pr = $conf->{'PAMOUTr'};
3730 select($pr); $| = 1; select(STDOUT);
3731 local $line = <$pr>;
3732 $line =~ s/\r|\n//g;
3735 $line =~ s/\r|\n//g;
3737 $conf->{'last'} = time();
3740 print $fh "0 PAM conversation error\n";
3744 local ($type, $msg) = split(/\s+/, $line, 2);
3745 if ($type =~ /^x(\d+)/) {
3746 # Pass this status code through
3747 print $fh "$1 $msg\n";
3748 return $1 == 2 || $1 == 0 ? 0 : 1;
3750 elsif ($type == PAM_PROMPT_ECHO_ON()) {
3752 print $fh "1 $msg\n";
3755 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3757 print $fh "3 $msg\n";
3760 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3761 # A message that does not require a response
3762 print $fh "4 $msg\n";
3767 print $fh "0 Unknown PAM message type $type\n";
3773 # send_pam_answer(&conv, answer)
3774 # Sends a response from the user to the PAM sub-process
3777 local ($conf, $answer) = @_;
3778 local $pw = $conf->{'PAMINw'};
3779 $conf->{'last'} = time();
3780 print $pw "$answer\n";
3783 # end_pam_conversation(&conv)
3784 # Clean up PAM conversation pipes and processes
3785 sub end_pam_conversation
3788 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
3789 if ($conv->{'PAMINr'}) {
3790 close($conv->{'PAMINr'});
3791 close($conv->{'PAMOUTr'});
3792 close($conv->{'PAMINw'});
3793 close($conv->{'PAMOUTw'});
3795 delete($conversations{$conv->{'cid'}});
3798 # get_ipkeys(&miniserv)
3799 # Returns a list of IP address to key file mappings from a miniserv.conf entry
3803 foreach $k (keys %{$_[0]}) {
3804 if ($k =~ /^ipkey_(\S+)/) {
3805 local $ipkey = { 'ips' => [ split(/,/, $1) ],
3806 'key' => $_[0]->{$k},
3807 'index' => scalar(@rv) };
3808 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
3815 # create_ssl_context(keyfile, [certfile])
3816 sub create_ssl_context
3818 local ($keyfile, $certfile) = @_;
3820 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
3821 $ssl_ctx ||= Net::SSLeay::CTX_new();
3822 $ssl_ctx || die "Failed to create SSL context : $!";
3823 if ($client_certs) {
3824 Net::SSLeay::CTX_load_verify_locations(
3825 $ssl_ctx, $config{'ca'}, "");
3826 Net::SSLeay::CTX_set_verify(
3827 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
3829 if ($config{'extracas'}) {
3831 foreach $p (split(/\s+/, $config{'extracas'})) {
3832 Net::SSLeay::CTX_load_verify_locations(
3837 Net::SSLeay::CTX_use_RSAPrivateKey_file(
3839 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
3840 Net::SSLeay::CTX_use_certificate_file(
3841 $ssl_ctx, $certfile || $keyfile,
3842 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
3847 # ssl_connection_for_ip(socket)
3848 # Returns a new SSL connection object for some socket, or undef if failed
3849 sub ssl_connection_for_ip
3852 local $sn = getsockname($sock);
3854 print STDERR "Failed to get address for socket $sock\n";
3857 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
3858 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
3859 local $ssl_con = Net::SSLeay::new($ssl_ctx);
3860 if ($config{'ssl_cipher_list'}) {
3861 # Force use of ciphers
3862 eval "Net::SSLeay::set_cipher_list(
3863 \$ssl_con, \$config{'ssl_cipher_list'})";
3865 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
3871 Net::SSLeay::set_fd($ssl_con, fileno($sock));
3872 if (!Net::SSLeay::accept($ssl_con)) {
3873 print STDERR "Failed to initialize SSL connection\n";
3879 # login_redirect(username, password, host)
3880 # Calls the login redirect script (if configured), which may output a URL to
3881 # re-direct a user to after logging in.
3884 return undef if (!$config{'login_redirect'});
3885 local $quser = quotemeta($_[0]);
3886 local $qpass = quotemeta($_[1]);
3887 local $qhost = quotemeta($_[2]);
3888 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
3893 # reload_config_file()
3894 # Re-read %config, and call post-config actions
3895 sub reload_config_file
3897 &log_error("Reloading configuration");
3898 %config = &read_config_file($config_file);
3899 &update_vital_config();
3902 &build_config_mappings();
3903 if ($config{'session'}) {
3904 dbmclose(%sessiondb);
3905 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
3909 # read_config_file(file)
3910 # Reads the given config file, and returns a hash of values
3911 sub read_config_file
3914 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
3917 if (/^#/ || !/\S/) { next; }
3919 $name = $1; $val = $2;
3920 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
3921 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
3928 # update_vital_config()
3929 # Updates %config with defaults, and dies if something vital is missing
3930 sub update_vital_config
3932 my %vital = ("port", 80,
3934 "server", "MiniServ/0.01",
3935 "index_docs", "index.html index.htm index.cgi index.php",
3936 "addtype_html", "text/html",
3937 "addtype_txt", "text/plain",
3938 "addtype_gif", "image/gif",
3939 "addtype_jpg", "image/jpeg",
3940 "addtype_jpeg", "image/jpeg",
3941 "realm", "MiniServ",
3942 "session_login", "/session_login.cgi",
3943 "pam_login", "/pam_login.cgi",
3944 "password_form", "/password_form.cgi",
3945 "password_change", "/password_change.cgi",
3949 "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\$",
3951 "expires", 7*24*60*60,
3953 foreach my $v (keys %vital) {
3955 if ($vital{$v} eq "") {
3956 die "Missing config option $v";
3958 $config{$v} = $vital{$v};
3961 if (!$config{'sessiondb'}) {
3962 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3963 $config{'sessiondb'} = "$1/sessiondb";
3965 if (!$config{'errorlog'}) {
3966 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
3967 $config{'errorlog'} = "$1/miniserv.error";
3969 if (!$config{'tempbase'}) {
3970 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3971 $config{'tempbase'} = "$1/cgitemp";
3973 if (!$config{'blockedfile'}) {
3974 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3975 $config{'blockedfile'} = "$1/blocked";
3980 # Fills the %users and %certs hashes from the users file in %config
3989 undef(%lastchanges);
3992 if ($config{'userfile'}) {
3993 open(USERS, $config{'userfile'});
3996 local @user = split(/:/, $_, -1);
3997 $users{$user[0]} = $user[1];
3998 $certs{$user[0]} = $user[3] if ($user[3]);
3999 if ($user[4] =~ /^allow\s+(.*)/) {
4000 $allow{$user[0]} = $config{'alwaysresolve'} ?
4001 [ split(/\s+/, $1) ] :
4002 [ &to_ipaddress(split(/\s+/, $1)) ];
4004 elsif ($user[4] =~ /^deny\s+(.*)/) {
4005 $deny{$user[0]} = $config{'alwaysresolve'} ?
4006 [ split(/\s+/, $1) ] :
4007 [ &to_ipaddress(split(/\s+/, $1)) ];
4009 if ($user[5] =~ /days\s+(\S+)/) {
4010 $allowdays{$user[0]} = [ split(/,/, $1) ];
4012 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4013 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4015 $lastchanges{$user[0]} = $user[6];
4016 $nochange{$user[0]} = $user[9];
4017 $temppass{$user[0]} = $user[10];
4024 # Fills %mime with entries from file in %config and extra settings in %config
4028 if ($config{"mimetypes"} ne "") {
4029 open(MIME, $config{"mimetypes"});
4032 if (/^(\S+)\s+(.*)$/) {
4034 my @exts = split(/\s+/, $2);
4035 foreach my $ext (@exts) {
4036 $mime{$ext} = $type;
4042 foreach my $k (keys %config) {
4043 if ($k !~ /^addtype_(.*)$/) { next; }
4044 $mime{$1} = $config{$k};
4048 # build_config_mappings()
4049 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4050 # redirect mapping and allow and deny lists from %config
4051 sub build_config_mappings
4053 # build anonymous access list
4055 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4056 if ($a =~ /^([^=]+)=(\S+)$/) {
4057 $anonymous{$1} = $2;
4061 # build IP access list
4063 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4064 if ($a =~ /^([^=]+)=(\S+)$/) {
4069 # build unauthenticated URLs list
4070 @unauth = split(/\s+/, $config{'unauth'});
4072 # build redirect mapping
4074 foreach my $r (split(/\s+/, $config{'redirect'})) {
4075 if ($r =~ /^([^=]+)=(\S+)$/) {
4080 # build prefixes to be stripped
4081 undef(@strip_prefix);
4082 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4083 push(@strip_prefix, $r);
4086 # Init allow and deny lists
4087 @deny = split(/\s+/, $config{"deny"});
4088 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4089 @allow = split(/\s+/, $config{"allow"});
4090 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4093 if ($config{'allowusers'}) {
4094 @allowusers = split(/\s+/, $config{'allowusers'});
4096 elsif ($config{'denyusers'}) {
4097 @denyusers = split(/\s+/, $config{'denyusers'});
4100 # Build list of unixauth mappings
4102 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4103 if ($ua =~ /^(\S+)=(\S+)$/) {
4107 $unixauth{"*"} = $ua;
4111 # Build list of non-session-auth pages
4112 undef(%sessiononly);
4113 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4114 $sessiononly{$sp} = 1;
4117 # Build list of logout times
4118 undef(@logouttimes);
4119 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4120 if ($a =~ /^([^=]+)=(\S+)$/) {
4121 push(@logouttimes, [ $1, $2 ]);
4124 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4126 # Build list of DAV pathss
4128 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4129 push(@davpaths, $d);
4131 @davusers = split(/\s+/, $config{'dav_users'});
4133 # Mobile agent substrings and hostname prefixes
4134 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4135 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4139 if ($config{'debug'}) {
4140 open(DEBUG, ">>$config{'debug'}");
4143 open(DEBUG, ">/dev/null");
4146 # Reset cache of sudo checks
4150 # is_group_member(&uinfo, groupname)
4151 # Returns 1 if some user is a primary or secondary member of a group
4154 local ($uinfo, $group) = @_;
4155 local @ginfo = getgrnam($group);
4156 return 0 if (!@ginfo);
4157 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4158 foreach my $m (split(/\s+/, $ginfo[3])) {
4159 return 1 if ($m eq $uinfo->[0]);
4164 # prefix_to_mask(prefix)
4165 # Converts a number like 24 to a mask like 255.255.255.0
4168 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4169 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4170 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4171 (256-(2 ** (8-$_[0]))).".0.0.0";
4174 # get_logout_time(user, session-id)
4175 # Given a username, returns the idle time before he will be logged out
4178 local ($user, $sid) = @_;
4179 if (!defined($logout_time_cache{$user,$sid})) {
4181 foreach my $l (@logouttimes) {
4182 if ($l->[0] =~ /^\@(.*)$/) {
4183 # Check group membership
4184 local @uinfo = getpwnam($user);
4185 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4189 elsif ($l->[0] =~ /^\//) {
4190 # Check file contents
4191 open(FILE, $l->[0]);
4208 if ($l->[0] eq $user) {
4212 last if (defined($time));
4214 $logout_time_cache{$user,$sid} = $time;
4216 return $logout_time_cache{$user,$sid};
4219 # password_crypt(password, salt)
4220 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4221 # of a password. Otherwise, do Unix crypt.
4224 local ($pass, $salt) = @_;
4225 if ($salt =~ /^\$1\$/ && $use_md5) {
4226 return &encrypt_md5($pass, $salt);
4229 return &unix_crypt($pass, $salt);
4233 # unix_crypt(password, salt)
4234 # Performs standard Unix hashing for a password
4237 local ($pass, $salt) = @_;
4238 if ($use_perl_crypt) {
4239 return Crypt::UnixCrypt::crypt($pass, $salt);
4242 return crypt($pass, $salt);
4246 # handle_dav_request(davpath)
4247 # Pass a request on to the Net::DAV::Server module
4248 sub handle_dav_request
4251 eval "use Filesys::Virtual::Plain";
4252 eval "use Net::DAV::Server";
4253 eval "use HTTP::Request";
4254 eval "use HTTP::Headers";
4256 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4257 delete $Net::DAV::Server::implemented{lock};
4258 delete $Net::DAV::Server::implemented{unlock};
4261 # Read in request data
4262 if (!$posted_data) {
4263 local $clen = $header{"content-length"};
4264 while(length($posted_data) < $clen) {
4265 $buf = &read_data($clen - length($posted_data));
4266 if (!length($buf)) {
4267 &http_error(500, "Failed to read POST request");
4269 $posted_data .= $buf;
4273 # For subsequent logging
4274 open(MINISERVLOG, ">>$config{'logfile'}");
4278 local @u = getpwnam($authuser);
4279 if ($config{'dav_remoteuser'} && !$< && $validated) {
4282 $( = $u[3]; $) = "$u[3] $u[3]";
4283 ($>, $<) = ($u[2], $u[2]);
4285 if ($config{'dav_root'} eq '*') {
4290 &http_error(500, "Unix user $authuser does not exist");
4294 $root ||= $config{'dav_root'};
4297 # Check if this user can use DAV
4299 &users_match(\@u, @davusers) ||
4300 &http_error(500, "You are not allowed to access DAV");
4304 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4305 my $webdav = Net::DAV::Server->new();
4306 $webdav->filesys($filesys);
4308 # Make up a request object, and feed to DAV
4309 local $ho = HTTP::Headers->new;
4310 foreach my $h (keys %header) {
4311 next if (lc($h) eq "connection");
4312 $ho->header($h => $header{$h});
4315 $request_uri =~ s/^\Q$path\E//;
4316 $request_uri = "/" if ($request_uri eq "");
4318 my $request = HTTP::Request->new($method, $request_uri, $ho,
4320 if ($config{'dav_debug'}) {
4321 print STDERR "DAV request :\n";
4322 print STDERR "---------------------------------------------\n";
4323 print STDERR $request->as_string();
4324 print STDERR "---------------------------------------------\n";
4326 my $response = $webdav->run($request);
4328 # Send back the reply
4329 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4330 local $content = $response->content();
4332 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4333 $content =~ s|href>/<|href>$path<|g;
4335 foreach my $h ($response->header_field_names) {
4336 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4337 &write_data("$h: ",$response->header($h),"\r\n");
4339 &write_data("Content-length: ",length($content),"\r\n");
4340 local $rv = &write_keep_alive(0);
4341 &write_data("\r\n");
4342 &write_data($content);
4344 if ($config{'dav_debug'}) {
4345 print STDERR "DAV reply :\n";
4346 print STDERR "---------------------------------------------\n";
4347 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4348 foreach my $h ($response->header_field_names) {
4349 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4350 print STDERR "$h: ",$response->header($h),"\r\n";
4352 print STDERR "Content-length: ",length($content),"\r\n";
4353 print STDERR "\r\n";
4354 print STDERR $content;
4355 print STDERR "---------------------------------------------\n";
4359 &log_request($acpthost, $authuser, $reqline, $response->code(),
4360 length($response->content()));
4363 # get_system_hostname()
4364 # Returns the hostname of this system, for reporting to listeners
4365 sub get_system_hostname
4367 # On Windows, try computername environment variable
4368 return $ENV{'computername'} if ($ENV{'computername'});
4369 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4371 # If a specific command is set, use it first
4372 if ($config{'hostname_command'}) {
4373 local $out = `($config{'hostname_command'}) 2>&1`;
4380 # First try the hostname command
4381 local $out = `hostname 2>&1`;
4382 if (!$? && $out =~ /\S/) {
4387 # Try the Sys::Hostname module
4388 eval "use Sys::Hostname";
4390 local $rv = eval "hostname()";
4396 # Must use net name on Windows
4397 local $out = `net name 2>&1`;
4398 if ($out =~ /\-+\r?\n(\S+)/) {
4405 # indexof(string, array)
4406 # Returns the index of some value in an array, or -1
4409 for($i=1; $i <= $#_; $i++) {
4410 if ($_[$i] eq $_[0]) { return $i - 1; }
4416 # has_command(command)
4417 # Returns the full path if some command is in the path, undef if not
4421 if (!$_[0]) { return undef; }
4422 if (exists($has_command_cache{$_[0]})) {
4423 return $has_command_cache{$_[0]};
4426 if ($_[0] =~ /^\//) {
4427 $rv = -x $_[0] ? $_[0] : undef;
4430 local $sp = $on_windows ? ';' : ':';
4431 foreach $d (split($sp, $ENV{PATH})) {
4432 if (-x "$d/$_[0]") {
4437 foreach my $sfx (".exe", ".com", ".bat") {
4438 if (-r "$d/$_[0]".$sfx) {
4439 $rv = "$d/$_[0]".$sfx;
4446 $has_command_cache{$_[0]} = $rv;
4450 # check_sudo_permissions(user, pass)
4451 # Returns 1 if some user can run any command via sudo
4452 sub check_sudo_permissions
4454 local ($user, $pass) = @_;
4456 # First try the pipes
4458 print DEBUG "check_sudo_permissions: querying cache for $user\n";
4459 print $PASSINw "readsudo $user\n";
4460 local $can = <$PASSOUTr>;
4462 print DEBUG "check_sudo_permissions: cache said $can\n";
4463 if ($can =~ /^\d+$/ && $can != 2) {
4468 local $ptyfh = new IO::Pty;
4469 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
4471 print STDERR "Failed to create new PTY with IO::Pty\n";
4474 local @uinfo = getpwnam($user);
4476 print STDERR "Unix user $user does not exist for sudo\n";
4480 # Execute sudo in a sub-process, via a pty
4481 local $ttyfh = $ptyfh->slave();
4482 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
4483 local $tty = $ptyfh->ttyname();
4484 print DEBUG "check_sudo_permissions: tty=$tty\n";
4485 chown($uinfo[2], $uinfo[3], $tty);
4487 print DEBUG "check_sudo_permissions: about to fork..\n";
4488 local $pid = fork();
4489 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
4491 print STDERR "fork for sudo failed : $!\n";
4496 $ptyfh->make_slave_controlling_terminal();
4497 close(STDIN); close(STDOUT); close(STDERR);
4498 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
4499 close($PASSINw); close($PASSOUTr);
4500 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
4501 ($>, $<) = ($uinfo[2], $uinfo[2]);
4506 open(STDIN, "<&SUDOr");
4507 open(STDOUT, ">$tty");
4508 open(STDERR, ">&STDOUT");
4511 print "Exec failed : $!\n";
4514 print DEBUG "check_sudo_permissions: pid=$pid\n";
4516 $ptyfh->close_slave();
4518 # Send password, and get back response
4519 local $oldfh = select(SUDOw);
4522 print DEBUG "check_sudo_permissions: about to send pass\n";
4523 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
4524 print SUDOw $pass,"\n";
4525 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
4529 print DEBUG "check_sudo_permissions: got $_";
4535 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
4539 print $PASSINw "writesudo $user $ok\n";
4545 # is_mobile_useragent(agent)
4546 # Returns 1 if some user agent looks like a cellphone or other mobile device,
4548 sub is_mobile_useragent
4550 local ($agent) = @_;
4552 "UP.Link", # Openwave
4553 "Nokia", # All Nokias start with Nokia
4554 "MOT-", # All Motorola phones start with MOT-
4555 "SAMSUNG", # Samsung browsers
4556 "Samsung", # Samsung browsers
4557 "SEC-", # Samsung browsers
4558 "AU-MIC", # Samsung browsers
4559 "AUDIOVOX", # Audiovox
4560 "BlackBerry", # BlackBerry
4561 "hiptop", # Danger hiptop Sidekick
4562 "SonyEricsson", # Sony Ericsson
4563 "Ericsson", # Old Ericsson browsers , mostly WAP
4564 "Mitsu/1.1.A", # Mitsubishi phones
4565 "Panasonic WAP", # Panasonic old WAP phones
4566 "DoCoMo", # DoCoMo phones
4567 "Lynx", # Lynx text-mode linux browser
4568 "Links", # Another text-mode linux browser
4570 local @substrings = (
4571 "UP.Browser", # Openwave
4572 "MobilePhone", # NetFront
4573 "AU-MIC-A700", # Samsung A700 Obigo browsers
4574 "Danger hiptop", # Danger Sidekick hiptop
4575 "Windows CE", # Windows CE Pocket PC
4576 "IEMobile", # Windows mobile browser
4577 "Blazer", # Palm Treo Blazer
4578 "BlackBerry", # BlackBerries can emulate other browsers, but
4579 # they still keep this string in the UserAgent
4580 "SymbianOS", # New Series60 browser has safari in it and
4581 # SymbianOS is the only distinguishing string
4582 "iPhone", # Apple iPhone KHTML browser
4583 "iPod", # iPod touch browser
4584 "MobileSafari", # HTTP client in iPhone
4586 "Opera Mini", # Opera Mini
4587 "HTC_P3700", # HTC mobile device
4589 "webOS/", # Palm WebOS
4591 foreach my $p (@prefixes) {
4592 return 1 if ($agent =~ /^\Q$p\E/);
4594 foreach my $s (@substrings, @mobile_agents) {
4595 return 1 if ($agent =~ /\Q$s\E/);
4600 # write_blocked_file()
4601 # Writes out a text file of blocked hosts and users
4602 sub write_blocked_file
4604 open(BLOCKED, ">$config{'blockedfile'}");
4605 foreach my $d (grep { $hostfail{$_} } @deny) {
4606 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
4608 foreach my $d (grep { $userfail{$_} } @denyusers) {
4609 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
4612 chmod(0700, $config{'blockedfile'});
4617 open(PIDFILE, ">$config{'pidfile'}");
4618 printf PIDFILE "%d\n", getpid();
4622 # lock_user_password(user)
4623 # Updates a user's password file entry to lock it, both in memory and on disk.
4624 # Returns 1 if done, -1 if no such user, 0 if already locked
4625 sub lock_user_password
4628 if ($users{$user}) {
4629 if ($users{$user} !~ /^\!/) {
4631 $users{$user} = "!".$users{$user};
4632 open(USERS, $config{'userfile'});
4633 local @ufile = <USERS>;
4635 foreach my $u (@ufile) {
4636 local @uinfo = split(/:/, $u);
4637 if ($uinfo[0] eq $user) {
4638 $uinfo[1] = $users{$user};
4640 $u = join(":", @uinfo);
4642 open(USERS, ">$config{'userfile'}");
4652 # hash_session_id(sid)
4653 # Returns an MD5 or Unix-crypted session ID
4657 if (!$hash_session_id_cache{$sid}) {
4660 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
4664 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
4667 return $hash_session_id_cache{$sid};
4670 # encrypt_md5(string, [salt])
4671 # Returns a string encrypted in MD5 format
4674 local ($passwd, $salt) = @_;
4675 local $magic = '$1$';
4676 if ($salt =~ /^\$1\$([^\$]+)/) {
4677 # Extract actual salt from already encrypted password
4682 local $ctx = eval "new $use_md5";
4689 # Add some more stuff from the hash of the password and salt
4690 local $ctx1 = eval "new $use_md5";
4691 $ctx1->add($passwd);
4695 $ctx1->add($passwd);
4696 local $final = $ctx1->digest();
4697 for($pl=length($passwd); $pl>0; $pl-=16) {
4698 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
4701 # This piece of code seems rather pointless, but it's in the C code that
4702 # does MD5 in PAM so it has to go in!
4705 for($i=length($passwd); $i; $i >>= 1) {
4710 $ctx->add(substr($passwd, $j, 1));
4713 $final = $ctx->digest();
4716 # This loop exists only to waste time
4717 for($i=0; $i<1000; $i++) {
4718 $ctx1 = eval "new $use_md5";
4719 $ctx1->add($i & 1 ? $passwd : $final);
4720 $ctx1->add($salt) if ($i % 3);
4721 $ctx1->add($passwd) if ($i % 7);
4722 $ctx1->add($i & 1 ? $final : $passwd);
4723 $final = $ctx1->digest();
4727 # Convert the 16-byte final string into a readable form
4729 local @final = map { ord($_) } split(//, $final);
4730 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
4731 $rv .= &to64($l, 4);
4732 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
4733 $rv .= &to64($l, 4);
4734 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
4735 $rv .= &to64($l, 4);
4736 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
4737 $rv .= &to64($l, 4);
4738 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
4739 $rv .= &to64($l, 4);
4741 $rv .= &to64($l, 2);
4743 # Add salt if needed
4745 return $magic.$salt.'$'.$rv;
4754 local ($v, $n) = @_;
4757 $r .= $itoa64[$v & 0x3f];